aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRaghuram Subramani <raghus2247@gmail.com>2025-06-19 16:54:34 +0530
committerRaghuram Subramani <raghus2247@gmail.com>2025-06-19 16:54:34 +0530
commite4c5d83e418f1a045758339779fb49b635db2bdb (patch)
tree8fdf2fda83f88a12ab971968eee81a7edf8b48d5
parent2ab610ffa95df79dcb3bcea2328b49234c65e372 (diff)
(list): add lists
-rw-r--r--include/list.h22
-rw-r--r--src/list.c57
2 files changed, 79 insertions, 0 deletions
diff --git a/include/list.h b/include/list.h
new file mode 100644
index 0000000..e8df51c
--- /dev/null
+++ b/include/list.h
@@ -0,0 +1,22 @@
+#ifndef __LIST_H
+#define __LIST_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+#define START_SIZE 100
+#define INCREMENT_BY 25
+
+typedef struct {
+ size_t element_size;
+ size_t max;
+ size_t size;
+ uint8_t *elements;
+} list_t;
+
+list_t *list_create(size_t element_size);
+void list_add(list_t *list, void *element);
+void *list_get(list_t *list, size_t i);
+void list_delete(list_t *list);
+
+#endif
diff --git a/src/list.c b/src/list.c
new file mode 100644
index 0000000..1d0549b
--- /dev/null
+++ b/src/list.c
@@ -0,0 +1,57 @@
+#include <list.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+list_t *
+list_create(size_t element_size)
+{
+ list_t *list = malloc(sizeof(list_t));
+ if (list == NULL)
+ return NULL;
+
+ list->element_size = element_size;
+ list->size = 0;
+ list->max = START_SIZE;
+ list->elements = (uint8_t *) calloc(list->max, element_size);
+
+ return list;
+}
+
+void
+list_add(list_t *list, void *element)
+{
+ if (list->size == list->max) {
+ list->max += INCREMENT_BY;
+ list->elements
+ = (uint8_t *) realloc(list->elements, list->element_size * list->max);
+ if (list->elements == NULL) {
+ /* TODO: Handle error */
+ printf("Failed to reallocate array\n");
+ return;
+ }
+ }
+
+ void *new_element = list->elements + list->element_size * list->size;
+ new_element = memcpy(new_element, element, list->element_size);
+
+ if (new_element == NULL)
+ printf("Failed to add a new element\n");
+
+ list->size++;
+}
+
+void *
+list_get(list_t *list, size_t i)
+{
+ return list->elements + (i * list->element_size);
+}
+
+void
+list_delete(list_t *list)
+{
+ free(list->elements);
+ free(list);
+}