aboutsummaryrefslogtreecommitdiff
path: root/teensy/teensy_list.h
blob: 6265e6a2cf520b14464205ac475a032f3d3069f0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#ifndef TEENSY_LIST_H_
#define TEENSY_LIST_H_

#include "teensy_common.h"
#include "teensy_mem.h"

typedef struct {
    size_t cap;
    size_t len;
} ty_List_Header;

#define TY_LIST_MIN_CAP 8
#define TY_LIST_GROW_RATE 2

#define ty_list_get_header(arr) ((ty_List_Header*)arr - 1)
#define ty_list_cap(arr) (ty_list_get_header(arr)->cap)
#define ty_list_len(arr) (ty_list_get_header(arr)->len)

#define ty_list_reserve(arr, amt)                                \
    do {                                                         \
        ty_List_Header *header = ty_list_get_header(arr); \
        if (amt > header->cap) {                                 \
            header->cap = header->cap < TY_LIST_MIN_CAP          \
                ? TY_LIST_MIN_CAP                                \
                : header->cap * TY_LIST_GROW_RATE;               \
            header = ty_realloc(                                 \
                header,                                          \
                (sizeof(*(arr)) * amt) + sizeof(ty_List_Header)  \
            );                                                   \
            (arr) = (void*)(header + 1);                         \
        }                                                        \
    } while (0)

#define ty_list_append(arr, elem)                                \
    do {                                                         \
        ty_List_Header *header = ty_list_get_header(arr); \
        ty_list_reserve(arr, header->len + 1);                   \
        (arr)[header->len++] = (elem);                           \
    } while (0)

#define ty_list_clear(arr) \
    (ty_list_get_header(arr)->len = 0)

#define ty_list_free(arr) (ty_free(ty_list_get_header(arr)))

void *ty_list_create(void);

#endif // TEENSY_LIST_H_