deepstone
view src/cvec.c @ 32:7c8402e27b7c
renamed Makefile.dos to Makefile
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Sun, 22 Sep 2013 18:37:46 +0300 |
parents | |
children |
line source
1 #include <stdlib.h>
2 #include <string.h>
3 #include <stddef.h>
4 #include "cvec.h"
6 struct vector {
7 int elem_sz;
8 int size, used;
9 char data[1];
10 };
12 #define HDRSZ offsetof(struct vector, data)
13 #define VECTOR(p) ((struct vector*)((char*)(p) - HDRSZ))
15 void *cvec_alloc(int cnt, int esz)
16 {
17 struct vector *vec;
19 if(!(vec = malloc(HDRSZ + esz * cnt))) {
20 return 0;
21 }
22 vec->elem_sz = esz;
23 vec->size = cnt;
24 vec->used = cnt;
25 return vec->data;
26 }
28 void cvec_free(void *cvec)
29 {
30 free(VECTOR(cvec));
31 }
33 void *cvec_resize(void *cvec, int newsz)
34 {
35 struct vector *newvec, *vec = VECTOR(cvec);
37 if(!(newvec = realloc(vec, newsz * vec->elem_sz + HDRSZ))) {
38 return 0;
39 }
40 newvec->size = newvec->used = newsz;
41 return newvec->data;
42 }
44 void *cvec_append(void *cvec, void *data)
45 {
46 struct vector *vec = VECTOR(cvec);
48 if(vec->used >= vec->size) {
49 int used = vec->used;
50 void *tmp;
52 if(!(tmp = cvec_resize(cvec, vec->size ? vec->size * 2 : 1))) {
53 return cvec;
54 }
55 cvec = tmp;
56 vec = VECTOR(tmp);
57 vec->used = used;
58 }
60 memcpy(vec->data + vec->used * vec->elem_sz, data, vec->elem_sz);
61 vec->used++;
62 return cvec;
63 }
65 int cvec_size(void *cvec)
66 {
67 return VECTOR(cvec)->used;
68 }