-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvec.c
106 lines (79 loc) · 1.95 KB
/
svec.c
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <assert.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#include "mem.h"
#include "svec.h"
SVec svec_init(const size_t esize,
const size_t chunk,
SVecCB dtor) {
assert(esize > 0);
assert(chunk > 0);
SVec self;
(void) memset(&self, 0, sizeof(SVec));
self.ptr = NULL;
self.len = 0;
self.chunk = chunk;
self.esize = esize;
self.dtor = dtor;
return (self);
}
void svec_free(SVec *const self) {
assert(self != NULL);
if (self->dtor != NULL)
svec_iter(self, self->dtor);
if (self->ptr == NULL) {
assert(self->len == 0);
} else {
const size_t chunks = self->len / self->chunk;
for (size_t i = 0; i < chunks; i++) {
uint8_t *p = self->ptr[i];
free(p);
}
free(self->ptr);
self->ptr = NULL;
self->len = 0;
self->dtor = NULL;
}
}
void *svec_add(SVec *const self) {
assert(self != NULL);
const size_t chunks = self->len / self->chunk;
void **new_ptr = NULL;
if (self->len == SIZE_MAX) {
errno = EOVERFLOW;
return (NULL);
}
if (self->len % self->chunk == 0) {
void *chunk_ptr = NULL;
new_ptr = xrealloc((void **) &self->ptr,
chunks + 1,
sizeof(void **));
if (new_ptr == NULL)
return (NULL);
self->ptr = new_ptr;
chunk_ptr = xrealloc(&chunk_ptr,
self->chunk,
self->esize);
if (chunk_ptr == NULL)
return (NULL);
self->ptr[chunks] = chunk_ptr;
}
self->len++;
return ((uint8_t *) self->ptr[chunks] +
(self->len -
chunks * self->chunk) *
self->esize);
}
void svec_iter(SVec *const self, SVecCB iter) {
assert(self != NULL);
assert(iter != NULL);
const size_t chunks = self->len / self->chunk;
for (size_t i = 0; i < chunks; i++) {
uint8_t *p = self->ptr[i];
for (size_t j = 0; j < self->chunk; j++) {
iter(p);
p += self->esize;
}
}
}