mirror of
https://github.com/sigmasternchen/macrofuck
synced 2025-03-15 07:08:56 +00:00
feat: Add dynamic list module
This commit is contained in:
parent
80e12144b0
commit
3c7fa8e351
2 changed files with 68 additions and 0 deletions
37
src/list.c
Normal file
37
src/list.c
Normal file
|
@ -0,0 +1,37 @@
|
|||
#include <stdlib.h>
|
||||
|
||||
#include "list.h"
|
||||
#include "alloc.h"
|
||||
|
||||
void* list_allocate(size_t element_size, size_t initial_capacity) {
|
||||
struct list_header* header = safe_alloc(sizeof(struct list_header) + initial_capacity * element_size);
|
||||
|
||||
header->capacity = initial_capacity;
|
||||
header->length = 0;
|
||||
|
||||
return header + 1;
|
||||
}
|
||||
|
||||
struct list_header* list_header(void* ptr) {
|
||||
struct list_header* header = ptr;
|
||||
return header - 1;
|
||||
}
|
||||
|
||||
size_t list_size(void* ptr) {
|
||||
return list_header(ptr)->length;
|
||||
}
|
||||
|
||||
void* list_ensure_space(void* ptr, size_t element_size, size_t additional) {
|
||||
struct list_header* header = list_header(ptr);
|
||||
|
||||
if (header->capacity - header->length < additional) {
|
||||
header->capacity = header->length + additional;
|
||||
header = safe_realloc(header, sizeof(struct list_header) + element_size * header->capacity);
|
||||
}
|
||||
|
||||
return header + 1;
|
||||
}
|
||||
|
||||
void list_free(void* ptr) {
|
||||
free(list_header(ptr));
|
||||
}
|
31
src/list.h
Normal file
31
src/list.h
Normal file
|
@ -0,0 +1,31 @@
|
|||
#ifndef LIST_H
|
||||
#define LIST_H
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdalign.h>
|
||||
|
||||
struct list_header {
|
||||
size_t capacity;
|
||||
alignas(16) size_t length;
|
||||
}
|
||||
|
||||
#define LIST_INITIAL_CAPACITY (16)
|
||||
|
||||
#define list_new(T) allocate_list(sizeof(T), LIST_INITIAL_CAPACITY)
|
||||
|
||||
void* list_allocate(size_t, size_t);
|
||||
size_t list_size(void*);
|
||||
|
||||
struct list_header* list_header(void*);
|
||||
|
||||
void* list_ensure_space(void*, size_t, size_t);
|
||||
|
||||
#define list_add(l, e) (\
|
||||
(l) = list_ensure_space(l, sizeof(e), 1);\
|
||||
(l)[list_size(l)] = e;\
|
||||
list_header(l)->length++;\
|
||||
)
|
||||
|
||||
void list_free(void*);
|
||||
|
||||
#endif
|
Loading…
Reference in a new issue