feat: added list_with_len and list_from_type_with_len
parent
cb0858f14f
commit
253cc0cb0c
24
list.c
24
list.c
|
@ -4,32 +4,34 @@
|
|||
#include "string.h"
|
||||
#include "debug.h"
|
||||
|
||||
#ifndef LIST_DEFAULT_RESERVE
|
||||
#define LIST_DEFAULT_RESERVE 4
|
||||
#endif
|
||||
|
||||
List list_init(size_t element_size) {
|
||||
return list_with_len(element_size, 0);
|
||||
}
|
||||
|
||||
List list_with_len(size_t element_size, size_t len) {
|
||||
List self = {
|
||||
.element_size = element_size,
|
||||
.cap = LIST_DEFAULT_RESERVE,
|
||||
.cap = 0,
|
||||
.len = 0,
|
||||
.data = malloc(element_size * LIST_DEFAULT_RESERVE),
|
||||
.data = NULL,
|
||||
};
|
||||
|
||||
if(self.data == NULL) {
|
||||
LOG_ERROR("Failed to allocate list with starting capacity of %d", LIST_DEFAULT_RESERVE);
|
||||
self.cap = 0;
|
||||
if(len != 0) {
|
||||
list_set_len(&self, len);
|
||||
if (self.data == NULL) {
|
||||
LOG_ERROR("Failed to allocate list with starting capacity of %d", LIST_DEFAULT_RESERVE);
|
||||
self.cap = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return self;
|
||||
}
|
||||
|
||||
List list_copy(const List* source) {
|
||||
List self = list_init(source->element_size);
|
||||
list_reserve(&self, source->cap);
|
||||
list_set_len(&self, source->cap);
|
||||
if(self.cap > 0) {
|
||||
memcpy(self.data, source->data, source->element_size * source->len);
|
||||
self.len = source->len;
|
||||
} else {
|
||||
LOG_ERROR("Failed to reserve space");
|
||||
}
|
||||
|
|
2
list.h
2
list.h
|
@ -13,6 +13,7 @@ struct List {
|
|||
};
|
||||
|
||||
extern List list_init(size_t element_size);
|
||||
extern List list_with_len(size_t element_size, size_t len);
|
||||
extern List list_copy(const List* source);
|
||||
extern void list_empty(List* list);
|
||||
|
||||
|
@ -31,6 +32,7 @@ extern void* list_iterator_end(List* self);
|
|||
extern size_t list_contains(List* self, void* query);
|
||||
|
||||
#define list_from_type(T) list_init(sizeof(T))
|
||||
#define list_from_type_with_len(T, __len) list_with_len(sizeof(T), __len)
|
||||
#define list_foreach(T, iter, list) for(T iter = list_iterator_begin(list); iter != (T)list_iterator_end(list); ++iter)
|
||||
#define list_at_as(T, __list, __i) ((T*)(list_at(__list, __i)))
|
||||
|
||||
|
|
Loading…
Reference in New Issue