chiark / gitweb /
Argument naming changes. Describe naming conventions for array types.
[mLib] / darray.c
index 0825bcae50fc222243d0e06bcd966d3ceaebe165..d7967c6219387859341085b15398ebf546f8c44d 100644 (file)
--- a/darray.c
+++ b/darray.c
@@ -1,6 +1,6 @@
 /* -*-c-*-
  *
- * $Id: darray.c,v 1.1 1999/10/22 22:37:26 mdw Exp $
+ * $Id: darray.c,v 1.3 1999/10/29 22:59:22 mdw Exp $
  *
  * Dynamically growing dense arrays
  *
 /*----- Revision history --------------------------------------------------* 
  *
  * $Log: darray.c,v $
+ * Revision 1.3  1999/10/29 22:59:22  mdw
+ * New array adjustment macros for unsigned arguments.
+ *
+ * Revision 1.2  1999/10/28 22:05:28  mdw
+ * Modify and debug allocation routines.
+ *
  * Revision 1.1  1999/10/22 22:37:26  mdw
  * New dynamic array implementation replaces `dynarray.h'.
  *
@@ -46,7 +52,7 @@
 
 /*----- Magic numbers -----------------------------------------------------*/
 
-#define DA_INITSZ 64                   /* Default size for new array */
+#define DA_INITSZ 16                   /* Default size for new array */
 #define DA_SLOTS 8                     /* Number of preshifted slots */
 
 /*----- Main code ---------------------------------------------------------*/
@@ -112,15 +118,26 @@ void *da_ensure(da_base *b, void *v, size_t sz, size_t n)
     return (q);
   }
 
-  /* --- Reallocate the array --- */
+  /* --- Reallocate the array --- *
+   *
+   * If the offset isn't changing, it's sensible to use @realloc@ if
+   * available.  Otherwise the overhead of copying all the data twice
+   * probably isn't worth it.
+   */
 
-  nsz = v ? b->sz + b->off : DA_INITSZ;
+  nsz = v ? b->sz + b->off : (DA_INITSZ >> 1);
   do nsz <<= 1; while (nsz < rq);
-  q = xmalloc(nsz * sz);
-  q += slots * sz;
-  memcpy(q, p, b->len * sz);
-  if (p)
-    free(p - b->off * sz);
+  if (p && slots == b->off) {
+    q = xrealloc(p - b->off * sz, nsz * sz);
+    q += slots * sz;
+  } else {
+    q = xmalloc(nsz * sz);
+    q += slots * sz;
+    if (p) {
+      memcpy(q, p, b->len * sz);
+      free(p - b->off * sz);
+    }
+  }
   b->off = slots;
   b->sz = nsz - slots;
   b->unshift = b->push = 0;
@@ -191,15 +208,20 @@ void *da_shunt(da_base *b, void *v, size_t sz, size_t n)
     return (q);
   }
 
-  /* --- Reallocate the array --- */
+  /* --- Reallocate the array --- *
+   *
+   * The neat @realloc@ code doesn't need to be here: the offset changes
+   * almost all the time -- that's the whole point of this routine!
+   */
 
-  nsz = v ? b->sz + b->off : DA_INITSZ;
+  nsz = v ? b->sz + b->off : (DA_INITSZ >> 1);
   do nsz <<= 1; while (nsz < rq);
   q = xmalloc(nsz * sz);
   q += (nsz - slots) * sz;
-  memcpy(q, p, b->len * sz);
-  if (p)
+  if (p) {
+    memcpy(q, p, b->len * sz);
     free(p - b->off * sz);
+  }
   b->off = nsz - slots;
   b->sz = slots;
   b->unshift = b->push = 0;