]> git.mdlowis.com Git - projs/libcds.git/commitdiff
Added mem_swap routine and update mem_release to accept null pointers
authorMichael D. Lowis <mike@mdlowis.com>
Thu, 23 Oct 2014 02:19:31 +0000 (22:19 -0400)
committerMichael D. Lowis <mike@mdlowis.com>
Thu, 23 Oct 2014 02:19:31 +0000 (22:19 -0400)
source/mem/mem.c
source/mem/mem.h

index c926c5c805e73ac63122d3f1057f15d4177a2cae..dae47292d8c9f270a3c6e3e1da64e75e89c91c4c 100644 (file)
@@ -69,22 +69,30 @@ void* mem_retain(void* p_obj)
 void mem_release(void* p_obj)
 {
     obj_t* p_hdr;
-    assert(NULL != p_obj);
-    p_hdr = (((obj_t*)p_obj)-1);
-    p_hdr->refcount -= 1;
-    if(p_hdr->refcount < 1)
-    {
-#if (LEAK_DETECT_LEVEL > 0)
-        Num_Allocations--;
-#endif
-        if(p_hdr->p_finalize)
+    if (NULL != p_obj) {
+        p_hdr = (((obj_t*)p_obj)-1);
+        p_hdr->refcount -= 1;
+        if(p_hdr->refcount < 1)
         {
-            p_hdr->p_finalize(p_obj);
+            #if (LEAK_DETECT_LEVEL > 0)
+            Num_Allocations--;
+            #endif
+            if(p_hdr->p_finalize)
+            {
+                p_hdr->p_finalize(p_obj);
+            }
+            free(p_hdr);
         }
-        free(p_hdr);
     }
 }
 
+void mem_swap(void** loc, void* obj)
+{
+    void* old = *loc;
+    *loc = obj;
+    mem_release(old);
+}
+
 void* mem_box(intptr_t val)
 {
     box_t* p_box = (box_t*)mem_allocate(sizeof(box_t), NULL);
index 3ad87dc8d8bc3fb2e55ae170f1aced4f05006b79..0e6e8467e12ae9ad955acbe6522862b0f6682674 100644 (file)
@@ -53,6 +53,15 @@ void* mem_retain(void* p_obj);
  */
 void mem_release(void* p_obj);
 
+/**
+ * @brief Replaces the object reference in the given location with the new
+ *        object releasing the old one.
+ *
+ * @param loc Pointer to the location where the reference is kept.
+ * @param obj The new object the location will point to.
+ */
+void mem_swap(void** loc, void* obj);
+
 /**
  * @brief Create a reference counted box holding the given value so that it can
  *        be placed in a container.