parent
5a10bda561
commit
9330b401d5
@ -0,0 +1,6 @@
|
||||
.yotta.json
|
||||
build
|
||||
*.swp
|
||||
yotta_modules
|
||||
yotta_targets
|
||||
Makefile
|
@ -0,0 +1,51 @@
|
||||
#ifndef REF_COUNTED_H
|
||||
#define REF_COUNTED_H
|
||||
|
||||
#include "mbed.h"
|
||||
|
||||
/**
|
||||
* Base class for payload for ref-counted objects. Used by ManagedString and MicroBitImage.
|
||||
* There is no constructor, as this struct is typically malloc()ed.
|
||||
*/
|
||||
struct RefCounted
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Number of outstanding references. Should never be zero (object should be deleted then).
|
||||
* When it's set to 0xffff, it means the object sits in flash and should not be counted.
|
||||
*/
|
||||
uint16_t refcnt;
|
||||
|
||||
/**
|
||||
* For strings this is length. For images this is both width and length (8 bit each).
|
||||
* A value of 0xffff indicates that this is in fact an instance of VirtualRefCounted
|
||||
* and therefore when the reference count reaches zero, the virtual destructor
|
||||
* should be called.
|
||||
*/
|
||||
union {
|
||||
uint16_t size;
|
||||
struct {
|
||||
uint8_t width;
|
||||
uint8_t height;
|
||||
};
|
||||
};
|
||||
|
||||
/** Increment reference count. */
|
||||
void incr();
|
||||
|
||||
/** Decrement reference count. */
|
||||
void decr();
|
||||
|
||||
};
|
||||
|
||||
/**
|
||||
* Base class for ref-counted objects. Used in native compiler in TD for Collections,
|
||||
* user-defined records, closures etc.
|
||||
*/
|
||||
class VirtualRefCounted : RefCounted
|
||||
{
|
||||
public:
|
||||
virtual ~VirtualRefCounted();
|
||||
};
|
||||
|
||||
#endif
|
@ -0,0 +1,31 @@
|
||||
#include "mbed.h"
|
||||
#include "MicroBit.h"
|
||||
|
||||
void RefCounted::incr()
|
||||
{
|
||||
if (refcnt == 0xffff)
|
||||
return;
|
||||
if (refcnt == 0)
|
||||
uBit.panic(30);
|
||||
refcnt++;
|
||||
}
|
||||
|
||||
void RefCounted::decr()
|
||||
{
|
||||
if (refcnt == 0xffff)
|
||||
return;
|
||||
if (refcnt == 0)
|
||||
uBit.panic(31);
|
||||
refcnt--;
|
||||
if (refcnt == 0) {
|
||||
// size of 0xffff indicates a class with a virtual destructor
|
||||
if (size == 0xffff)
|
||||
delete (VirtualRefCounted*)this;
|
||||
else
|
||||
free(this);
|
||||
}
|
||||
}
|
||||
|
||||
VirtualRefCounted::~VirtualRefCounted()
|
||||
{
|
||||
}
|
Loading…
Reference in new issue