deepstone

annotate src/cvec.c @ 41:482f30e63462

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