Debian Codegraph @

src/utils/vector.c

raw
1 #include "utils/vector.h"
2 #include "main.h"
3 #include "utils/logger.h"
4 #include <errno.h>
5 #include <stddef.h>
6 #include <stdint.h>
7 #include <stdlib.h>
8 #include <string.h>
9
10 void *
11 reallocate (void *p, size_t new_size)
12 {
13 if (new_size == 0)
14 {
15 free (p);
16 return NULL;
17 }
18
19 p = realloc (p, new_size);
20 if (p == NULL)
21 error ("realloc: %s", strerror (errno));
22
23 return p;
24 }
25
26 #define UPDATE_VECTOR \
27 v->data = reallocate (v->data, v->capacity * v->elem_size);
28
29 void
30 init_vector (vector_t *v, size_t elem_size, size_t initial_capacity)
31 {
32 v->count = 0;
33 v->capacity = initial_capacity ? initial_capacity : 0x10;
34 v->elem_size = elem_size;
35 v->data = NULL;
36 UPDATE_VECTOR;
37 }
38
39 void
40 free_vector (vector_t *v)
41 {
42 v->count = 0;
43 v->capacity = 0;
44 v->elem_size = 0;
45 UPDATE_VECTOR;
46 }
47
48 void *
49 push_vector (vector_t *v, void *elem)
50 {
51 if (UNLIKELY (v->count >= v->capacity))
52 {
53 v->capacity *= 2;
54 UPDATE_VECTOR;
55 }
56
57 void *dst = (uint8_t *)v->data + v->count * v->elem_size;
58 memcpy (dst, elem, v->elem_size);
59 v->count++;
60 return dst;
61 }
62
63 void *
64 get_vector (vector_t *v, uint32_t idx)
65 {
66 return (uint8_t *)v->data + idx * v->elem_size;
67 }