dos3d

diff src/cvec.c @ 16:cb676ff89e69

added missing cvec and scene files
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 29 Nov 2011 07:23:57 +0200
parents
children
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/cvec.c	Tue Nov 29 07:23:57 2011 +0200
     1.3 @@ -0,0 +1,68 @@
     1.4 +#include <stdlib.h>
     1.5 +#include <string.h>
     1.6 +#include <stddef.h>
     1.7 +#include "cvec.h"
     1.8 +
     1.9 +struct vector {
    1.10 +	int elem_sz;
    1.11 +	int size, used;
    1.12 +	char data[1];
    1.13 +};
    1.14 +
    1.15 +#define HDRSZ		offsetof(struct vector, data)
    1.16 +#define VECTOR(p)	((struct vector*)((char*)(p) - HDRSZ))
    1.17 +
    1.18 +void *cvec_alloc(int cnt, int esz)
    1.19 +{
    1.20 +	struct vector *vec;
    1.21 +
    1.22 +	if(!(vec = malloc(HDRSZ + esz * cnt))) {
    1.23 +		return 0;
    1.24 +	}
    1.25 +	vec->elem_sz = esz;
    1.26 +	vec->size = cnt;
    1.27 +	vec->used = cnt;
    1.28 +	return vec->data;
    1.29 +}
    1.30 +
    1.31 +void cvec_free(void *cvec)
    1.32 +{
    1.33 +	free(VECTOR(cvec));
    1.34 +}
    1.35 +
    1.36 +void *cvec_resize(void *cvec, int newsz)
    1.37 +{
    1.38 +	struct vector *newvec, *vec = VECTOR(cvec);
    1.39 +
    1.40 +	if(!(newvec = realloc(vec, newsz * vec->elem_sz + HDRSZ))) {
    1.41 +		return 0;
    1.42 +	}
    1.43 +	newvec->size = newvec->used = newsz;
    1.44 +	return newvec->data;
    1.45 +}
    1.46 +
    1.47 +void *cvec_append(void *cvec, void *data)
    1.48 +{
    1.49 +	struct vector *vec = VECTOR(cvec);
    1.50 +
    1.51 +	if(vec->used >= vec->size) {
    1.52 +		int used = vec->used;
    1.53 +		void *tmp;
    1.54 +
    1.55 +		if(!(tmp = cvec_resize(cvec, vec->size ? vec->size * 2 : 1))) {
    1.56 +			return cvec;
    1.57 +		}
    1.58 +		cvec = tmp;
    1.59 +		vec = VECTOR(tmp);
    1.60 +		vec->used = used;
    1.61 +	}
    1.62 +
    1.63 +	memcpy(vec->data + vec->used * vec->elem_sz, data, vec->elem_sz);
    1.64 +	vec->used++;
    1.65 +	return cvec;
    1.66 +}
    1.67 +
    1.68 +int cvec_size(void *cvec)
    1.69 +{
    1.70 +	return VECTOR(cvec)->used;
    1.71 +}