advent2019

Advent of Code 2019 (C99)
git clone git://bsandro.tech/advent2019
Log | Files | Refs | LICENSE

array.h (1812B)


      1 #include <stdlib.h>
      2 
      3 struct array_hdr {
      4     size_t len;
      5     size_t cap;
      6 };
      7 
      8 #define array_init(ar, capacity) do {                                                   \
      9     struct array_hdr *hdr = malloc(sizeof(struct array_hdr)+sizeof(*(ar))*(capacity));  \
     10     printf("init %p\n", (void *)hdr);                                                   \
     11     hdr->len = 0;                                                                       \
     12     hdr->cap = (capacity);                                                              \
     13     (ar) = (void *)(hdr+1);                                                             \
     14 } while(0);
     15 
     16 #define array_free(ar) do {                     \
     17     void *base = ((struct array_hdr *)(ar))-1;  \
     18     printf("free %p\n", (void *)base);          \
     19     free(base);                                 \
     20     (ar) = NULL;                                \
     21 } while(0);
     22 
     23 inline size_t array_len(void *ar) {
     24     return (((struct array_hdr *)ar)-1)->len;
     25 }
     26 
     27 inline size_t array_cap(void *ar) {
     28     return (((struct array_hdr *)ar)-1)->cap;
     29 }
     30 
     31 #define array_push(ar, val) do {                                                \
     32     struct array_hdr *hdr = ((struct array_hdr *)(ar))-1;                       \
     33     printf("push: %lu of %lu\n", hdr->len, hdr->cap);                           \
     34     if (hdr->len+1>=hdr->cap) {                                                 \
     35         hdr = realloc(hdr, sizeof(*ar)*hdr->cap*2+sizeof(struct array_hdr));    \
     36         hdr->cap*=2;                                                            \
     37         (ar) = (void *)(hdr+1);                                                 \
     38     }                                                                           \
     39     (ar)[hdr->len++] = val;                                                     \
     40 } while(0);