Add array push/pop; fix ghastly memory overrun bug.
authorDavid Given <dg@cowlark.com>
Sun, 2 Oct 2016 15:24:31 +0000 (17:24 +0200)
committerDavid Given <dg@cowlark.com>
Sun, 2 Oct 2016 15:24:31 +0000 (17:24 +0200)
modules/src/data/array.c
modules/src/data/array.h

index bfaaf8e..13c0b6c 100644 (file)
@@ -1,6 +1,7 @@
 #include <stdlib.h>
 #include <stdbool.h>
 #include <string.h>
+#include <assert.h>
 #include "array.h"
 
 static void extend(struct array* array)
@@ -8,7 +9,7 @@ static void extend(struct array* array)
        if (array->count == array->max)
        {
                int newmax = (array->max == 0) ? 8 : (array->max * 2);
-               void** newarray = realloc(array->item, newmax * sizeof(void*));
+               struct array* newarray = realloc(array->item, newmax * sizeof(*newarray));
 
                array->max = newmax;
                array->item = newarray;
@@ -24,16 +25,21 @@ void array_append(void* arrayp, void* value)
     array->count++;
 }
 
-bool array_contains(void* arrayp, void* value)
+int array_indexof(void* arrayp, void* value)
 {
     struct array* array = arrayp;
        int i;
 
        for (i=0; i<array->count; i++)
                if (array->item[i] == value)
-                       return true;
+                       return i;
+
+       return -1;
+}
 
-       return false;
+bool array_contains(void* arrayp, void* value)
+{
+    return (array_indexof(arrayp, value) != -1);
 }
 
 bool array_appendu(void* arrayp, void* value)
@@ -76,5 +82,13 @@ void array_remove(void* arrayp, void* value)
     }
 }
 
+void* array_pop(void* arrayp)
+{
+    struct array* array = arrayp;
+
+    assert(array->count > 0);
+    return array->item[array->count--];
+}
+
 /* vim: set sw=4 ts=4 expandtab : */
 
index 63951ff..8762d7e 100644 (file)
@@ -22,6 +22,10 @@ extern bool array_appendu(void* array, void* value);
 extern void array_insert(void* array, void* value, int before);
 extern void array_remove(void* array, void* value);
 extern bool array_contains(void* array, void* value);
+extern int array_indexof(void* array, void* value);
+
+#define array_push(a, v) array_append(a, v)
+extern void* array_pop(void* array);
 
 #endif