// Copyright (c) 2023 Jonathan Metzgar
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#include <stdlib.h>
#include <stdint.h>
#include <memory.h>
typedef struct Object_t
{
int64_t refCount;
} Object_t;
typedef Object_t *ObjectPtr;
/**
* @brief
*
* @param obj
*/
static inline
ObjectPtr retainObject(ObjectPtr obj)
{
if (obj != NULL)
{
obj->refCount++;
}
return obj;
}
/**
* @brief Release an object from ownership. Deallocate if reference count <= 0.
*
* @param obj
*/
static inline
ObjectPtr releaseObject(ObjectPtr obj)
{
if (obj != NULL)
{
obj->refCount--;
if (obj->refCount <= 0)
{
free(obj);
return NULL;
}
}
return obj;
}
/**
* @brief Allocates an object from the heap and adds a reference count.
*
* @param sizeInBytes
* @return ObjectPtr
*/
static inline
ObjectPtr allocObject(size_t sizeInBytes)
{
ObjectPtr obj = (ObjectPtr)malloc(sizeInBytes);
if (!obj) {
return NULL;
}
memset(obj, 0, sizeInBytes);
return retainObject(obj);
}
Comments