lib.[ch]: Move the memory allocation out-of-line.
authorMark Wooding <mdw@distorted.org.uk>
Fri, 8 Apr 2022 14:29:13 +0000 (15:29 +0100)
committerMark Wooding <mdw@distorted.org.uk>
Fri, 8 Apr 2022 14:29:13 +0000 (15:29 +0100)
lib.c
lib.h

diff --git a/lib.c b/lib.c
index 7021661..25cc829 100644 (file)
--- a/lib.c
+++ b/lib.c
@@ -98,6 +98,19 @@ long parse_int(const char **p_inout, unsigned f,
   return (x);
 }
 
+/*----- Resizing arrays ---------------------------------------------------*/
+
+void *vec__grow(void *p, size_t esz, size_t *sz_inout)
+{
+  size_t sz = *sz_inout, want;
+
+  sz = sz ? 2*sz : 32;
+  want = sz*esz;
+  p = realloc(p, want);
+  if (!p) bail("out of memory allocating %zu bytes", want);
+  *sz_inout = sz; return (p);
+}
+
 /*----- System utilities --------------------------------------------------*/
 
 void sit(double t)
diff --git a/lib.h b/lib.h
index 553a5fe..2b127e3 100644 (file)
--- a/lib.h
+++ b/lib.h
@@ -160,14 +160,16 @@ extern PRINTF_LIKE(2, 3) NORETURN
 } while (0)
        /* Free the vector VV.  It's safe to free a vector multiple times. */
 
+extern void *vec__grow(void *p, size_t esz, size_t *sz_inout);
+       /* Extend the buffer P, which currently has space for *SZ_INOUT
+        * elements, each ESZ bytes in size, so that there's space for at
+        * least one one more; return the new buffer address, and update
+        * *SZ_INOUT with the new size.
+        */
+
 #define VEC_PUSH(p, vv) do {                                           \
-  size_t _want;                                                                \
-  if ((vv)->n >= (vv)->sz) {                                           \
-    (vv)->sz = (vv)->sz ? 2*(vv)->sz : 32;                             \
-    _want = (vv)->sz*sizeof(*(vv)->v);                                 \
-    (vv)->v = realloc((vv)->v, _want);                                 \
-    if (!(vv)->v) bail("out of memory allocating %zu bytes", _want);   \
-  }                                                                    \
+  if ((vv)->n >= (vv)->sz)                                             \
+    (vv)->v = vec__grow((vv)->v, sizeof(*(vv)->v), &(vv)->sz);         \
   (p) = &(vv)->v[(vv)->n++];                                           \
 } while (0)
        /* Add an initialized element to the end of vector VV, storing its