Advertisement
microwerx

Object reference counter

Apr 29th, 2023
1,083
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.18 KB | Source Code | 0 0
  1. // Copyright (c) 2023 Jonathan Metzgar
  2. //
  3. // This software is released under the MIT License.
  4. // https://opensource.org/licenses/MIT
  5.  
  6. #include <stdlib.h>
  7. #include <stdint.h>
  8. #include <memory.h>
  9.  
  10. typedef struct Object_t
  11. {
  12.     int64_t refCount;
  13. } Object_t;
  14.  
  15. typedef Object_t *ObjectPtr;
  16.  
  17. /**
  18.  * @brief
  19.  *
  20.  * @param obj
  21.  */
  22. static inline
  23. ObjectPtr retainObject(ObjectPtr obj)
  24. {
  25.     if (obj != NULL)
  26.     {
  27.         obj->refCount++;
  28.     }
  29.     return obj;
  30. }
  31.  
  32. /**
  33.  * @brief Release an object from ownership. Deallocate if reference count <= 0.
  34.  *
  35.  * @param obj
  36.  */
  37. static inline
  38. ObjectPtr releaseObject(ObjectPtr obj)
  39. {
  40.     if (obj != NULL)
  41.     {
  42.         obj->refCount--;
  43.         if (obj->refCount <= 0)
  44.         {
  45.             free(obj);
  46.             return NULL;
  47.         }
  48.     }
  49.     return obj;
  50. }
  51.  
  52. /**
  53.  * @brief Allocates an object from the heap and adds a reference count.
  54.  *
  55.  * @param sizeInBytes
  56.  * @return ObjectPtr
  57.  */
  58. static inline
  59. ObjectPtr allocObject(size_t sizeInBytes)
  60. {
  61.     ObjectPtr obj = (ObjectPtr)malloc(sizeInBytes);
  62.     if (!obj) {
  63.         return NULL;
  64.     }
  65.     memset(obj, 0, sizeInBytes);
  66.     return retainObject(obj);
  67. }
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement