aboutsummaryrefslogtreecommitdiff
path: root/09-september/tomcat/util/array.c
diff options
context:
space:
mode:
Diffstat (limited to '09-september/tomcat/util/array.c')
-rw-r--r--09-september/tomcat/util/array.c102
1 files changed, 102 insertions, 0 deletions
diff --git a/09-september/tomcat/util/array.c b/09-september/tomcat/util/array.c
new file mode 100644
index 0000000..13660e0
--- /dev/null
+++ b/09-september/tomcat/util/array.c
@@ -0,0 +1,102 @@
+#include "array.h"
+
+#include <stdlib.h>
+#include <string.h>
+
+#define ARRAY_GROWTH_FACTOR 2
+#define MAX(x, y) ( (x > y) ? x : y )
+
+typedef struct _RealArray
+{
+ char *data;
+ unsigned int length; /* Number of elements */
+
+ unsigned int type_size;
+ unsigned int capacity; /* Array capacity in elements number */
+ bool clear;
+} RealArray;
+
+static void array_check_for_expand(RealArray *arr, unsigned int length);
+
+Array *array_create(unsigned int type_size)
+{
+ return array_create_by_size(type_size, 0);
+}
+
+Array *array_create_by_size(unsigned int type_size, unsigned int reserved_size)
+{
+ RealArray *arr = malloc( sizeof(RealArray) );
+ arr->capacity = 0;
+ arr->data = NULL;
+ arr->length = 0;
+ arr->type_size = type_size;
+
+ if(reserved_size != 0)
+ {
+ array_check_for_expand(arr, reserved_size);
+ }
+
+ return (Array *)arr;
+}
+
+void array_append(Array *arr, void *data)
+{
+ RealArray *r_arr = (RealArray *)arr;
+ array_check_for_expand(r_arr, 1);
+
+ memcpy(r_arr->data + r_arr->length * r_arr->type_size, data, r_arr->type_size);
+ r_arr->length += 1;
+}
+
+void array_insert(Array *arr, int index, void *data)
+{
+ RealArray *r_arr = (RealArray *)arr;
+ array_check_for_expand(r_arr, 1);
+
+ /* Shift everything one place */
+ memmove(r_arr->data + (index + 1) * r_arr->type_size,
+ r_arr->data + index * r_arr->type_size,
+ r_arr->length * r_arr->type_size - index * r_arr->type_size);
+
+ /* Insert the new data */
+ memcpy(r_arr->data + index * r_arr->type_size, data, r_arr->type_size);
+
+ r_arr->length += 1;
+}
+
+void array_remove(Array *arr, int index)
+{
+
+}
+
+void array_reserve(Array *arr, unsigned int length)
+{
+
+}
+
+unsigned int array_get_type_size(Array *arr)
+{
+ RealArray *r_arr = (RealArray *)arr;
+ return r_arr->type_size;
+}
+
+void array_free(Array *arr)
+{
+ RealArray *r_arr = (RealArray *)arr;
+
+ free(r_arr->data);
+ free(r_arr);
+}
+
+static void array_check_for_expand(RealArray *arr, unsigned int length)
+{
+ RealArray *r_arr = (RealArray *)arr;
+
+ unsigned int expected_size = r_arr->length + length;
+
+ if(r_arr->capacity < expected_size)
+ {
+ r_arr->capacity = MAX(ARRAY_GROWTH_FACTOR * r_arr->capacity, expected_size);
+ r_arr->data = realloc(r_arr->data, r_arr->capacity * r_arr->type_size);
+ }
+}