diff options
author | 2023-05-10 16:31:53 +0200 | |
---|---|---|
committer | 2023-05-10 16:31:53 +0200 | |
commit | b6f8c43dabd4725b3a74795b85364c1a685ec6eb (patch) | |
tree | b23f6795c6f8b7e4d6b2b9a12cf33e4634c08af4 | |
parent | ba96d5e14017bd853f929e6bb9799d3a6ad9e813 (diff) | |
download | utils-b6f8c43dabd4725b3a74795b85364c1a685ec6eb.tar.gz utils-b6f8c43dabd4725b3a74795b85364c1a685ec6eb.zip |
Add data size when adding new items to the list
When adding new data to the list, we need exactly how long is the data. So, it's
programer responsibility to calculate the exact size of data to store.
-rw-r--r-- | src/list.c | 26 | ||||
-rw-r--r-- | src/utils.h | 4 |
2 files changed, 24 insertions, 6 deletions
@@ -18,13 +18,15 @@ clist_create() void clist_add(list_t *list, - void *data) + void *data, + size_t data_s) { - struct list_item_t *item = malloc(sizeof(struct list_item_t)); + struct list_item_t *item = malloc(sizeof(struct list_item_t)); - void *dest = malloc(sizeof(data)); /* allocates memory like data parameter */ - memcpy(dest, data, sizeof(data)); /* copies data inside dest */ + void *dest = malloc(data_s); /* allocates memory like data parameter */ + memcpy(dest, data, data_s); /* copies data inside dest */ item->data = dest; + item->data_s = data_s; item->next = NULL; if (list->first == NULL) @@ -45,7 +47,8 @@ void clist_add_all(list_t *dest, iterator_t i = clist_iterator(other); while (clist_iterator_has_next(i)) { - clist_add(dest, clist_iterator_next(&i)); + list_item_t *item = clist_iterator_next_item(&i); + clist_add(dest, item->data, item->data_s); } } @@ -98,3 +101,16 @@ clist_iterator_next(iterator_t *i) return data; } + +list_item_t * +clist_iterator_next_item(iterator_t *i) +{ + if (i == NULL || i->current == NULL) + return NULL; + + list_item_t *item = i->current; + /* `next` can be NULL */ + i->current = i->current->next; + + return item; +} diff --git a/src/utils.h b/src/utils.h index e21dd2e..6c5db92 100644 --- a/src/utils.h +++ b/src/utils.h @@ -5,6 +5,7 @@ typedef struct list_item_t { void *data; + size_t data_s; struct list_item_t *next; } list_item_t; @@ -19,12 +20,13 @@ typedef struct iterator_t { } iterator_t; list_t clist_create (void); -void clist_add (list_t *, void *); +void clist_add (list_t *, void *, size_t); void clist_add_all (list_t *, list_t *); void clist_remove (list_t *, list_item_t *); iterator_t clist_iterator (list_t *); int clist_iterator_has_next(iterator_t); void *clist_iterator_next (iterator_t *); +list_item_t *clist_iterator_next_item(iterator_t *); char *cutils_version(); |