]> mj.ucw.cz Git - libucw.git/blobdiff - ucw/gary.c
Doc: Updated the list of contributors
[libucw.git] / ucw / gary.c
index 10b73288d57f250e6a1d1a7f7668e0cd637c001b..8207de392347571c889b063939d1a30f40ba74d8 100644 (file)
@@ -1,7 +1,7 @@
 /*
  *     UCW Library -- A simple growing array of an arbitrary type
  *
- *     (c) 2010--2012 Martin Mares <mj@ucw.cz>
+ *     (c) 2010--2014 Martin Mares <mj@ucw.cz>
  */
 
 #undef LOCAL_DEBUG
 
 #include <string.h>
 
+struct gary_hdr gary_empty_hdr;
+
 void *
-gary_init(size_t elt_size, size_t num_elts, int zeroed)
+gary_init(size_t elt_size, size_t num_elts, struct ucw_allocator *allocator)
 {
   DBG("GARY: Init to %zd elements", num_elts);
-  struct gary_hdr *h = xmalloc(GARY_HDR_SIZE + elt_size * num_elts);
+  struct gary_hdr *h = allocator->alloc(allocator, GARY_HDR_SIZE + elt_size * num_elts);
   h->num_elts = h->have_space = num_elts;
   h->elt_size = elt_size;
-  h->zeroed = zeroed;
-  if (zeroed)
-    bzero(GARY_BODY(h), elt_size * num_elts);
+  h->allocator = allocator;
   return GARY_BODY(h);
 }
 
@@ -33,10 +33,7 @@ gary_realloc(struct gary_hdr *h, size_t n)
   else
     h->have_space *= 2;
   DBG("GARY: Resize from %zd to %zd elements (need %zd)", old_size, h->have_space, n);
-  h = xrealloc(h, GARY_HDR_SIZE + h->have_space * h->elt_size);
-  if (h->zeroed)
-    bzero(GARY_BODY(h) + h->elt_size * old_size, h->elt_size * (h->have_space - old_size));
-  return h;
+  return h->allocator->realloc(h->allocator, h, GARY_HDR_SIZE + old_size * h->elt_size, GARY_HDR_SIZE + h->have_space * h->elt_size);
 }
 
 void *
@@ -66,7 +63,7 @@ gary_fix(void *array)
   struct gary_hdr *h = GARY_HDR(array);
   if (h->num_elts != h->have_space)
     {
-      h = xrealloc(h, GARY_HDR_SIZE + h->num_elts * h->elt_size);
+      h = h->allocator->realloc(h->allocator, h, GARY_HDR_SIZE + h->have_space * h->elt_size, GARY_HDR_SIZE + h->num_elts * h->elt_size);
       h->have_space = h->num_elts;
     }
   return GARY_BODY(h);
@@ -74,16 +71,26 @@ gary_fix(void *array)
 
 #ifdef TEST
 
+#include <ucw/mempool.h>
+
 #include <stdio.h>
 
-int main(void)
+int main(int argc, char **argv UNUSED)
 {
   int *a;
-  GARY_INIT_ZERO(a, 5);
+  struct mempool *mp = NULL;
+
+  if (argc < 2)
+    GARY_INIT_ZERO(a, 5);
+  else
+    {
+      mp = mp_new(4096);
+      GARY_INIT_ALLOC(a, 5, mp_get_allocator(mp));
+    }
 
   for (int i=0; i<5; i++)
     {
-      ASSERT(!a[i]);
+      ASSERT(!a[i] || mp);
       a[i] = i+1;
     }
 
@@ -98,6 +105,8 @@ int main(void)
     printf("%d\n", a[i]);
 
   GARY_FREE(a);
+  if (mp)
+    mp_delete(mp);
   return 0;
 }