From 716a6447f98ee7baea8eb53bf41ffce390fbc309 Mon Sep 17 00:00:00 2001 From: JeffBezanson Date: Fri, 5 Mar 2010 18:08:31 +0000 Subject: [PATCH] adding arraylist to LLT --- llt/Makefile | 2 +- llt/arraylist.c | 69 +++++++++++++++++++++++++++++++++++++++++++++++++ llt/arraylist.h | 19 ++++++++++++++ 3 files changed, 89 insertions(+), 1 deletion(-) create mode 100644 llt/arraylist.c create mode 100644 llt/arraylist.h diff --git a/llt/Makefile b/llt/Makefile index bae07e9..49aabbe 100644 --- a/llt/Makefile +++ b/llt/Makefile @@ -3,7 +3,7 @@ CC = gcc SRCS = bitvector.c hashing.c socket.c timefuncs.c dblprint.c ptrhash.c \ utf8.c ios.c operators.c cplxprint.c dirpath.c htable.c \ bitvector-ops.c fp.c int2str.c dump.c random.c bswap.c memalign.c \ - swapreverse.c lltinit.c + swapreverse.c lltinit.c arraylist.c OBJS = $(SRCS:%.c=%.o) DOBJS = $(SRCS:%.c=%.do) TARGET = libllt.a diff --git a/llt/arraylist.c b/llt/arraylist.c new file mode 100644 index 0000000..253870d --- /dev/null +++ b/llt/arraylist.c @@ -0,0 +1,69 @@ +#include +#include +#include +#include +#include + +#include "dtypes.h" +#include "arraylist.h" + +arraylist_t *arraylist_new(arraylist_t *a, size_t size) +{ + a->len = 0; + if (size <= AL_N_INLINE) { + a->items = &a->_space[0]; + a->max = AL_N_INLINE; + } + else { + a->items = (void**)LLT_ALLOC(size*sizeof(void*)); + a->max = size; + } + if (a->items == NULL) return NULL; + return a; +} + +void arraylist_free(arraylist_t *a) +{ + if (a->items != &a->_space[0]) + LLT_FREE(a->items); + a->len = 0; + a->max = AL_N_INLINE; + a->items = &a->_space[0]; +} + +static void al_grow(arraylist_t *a, size_t n) +{ + if (a->len+n > a->max) { + if (a->items == &a->_space[0]) { + void **p = LLT_ALLOC((a->len+n)*sizeof(void*)); + if (p == NULL) return; + memcpy(p, a->items, a->len*sizeof(void*)); + a->items = p; + a->max = a->len+n; + } + else { + size_t nm = a->max*2; + if (nm == 0) nm = 1; + while (a->len+n > nm) nm*=2; + void **p = LLT_REALLOC(a->items, nm); + if (p == NULL) return; + a->items = p; + a->max = nm; + } + } + a->len += n; +} + +void arraylist_push(arraylist_t *a, void *elt) +{ + al_grow(a, 1); + a->items[a->len-1] = elt; +} + +void *arraylist_pop(arraylist_t *a) +{ + if (a->len == 0) return NULL; + void *p = a->items[--a->len]; + a->items[a->len] = NULL; + return p; +} diff --git a/llt/arraylist.h b/llt/arraylist.h new file mode 100644 index 0000000..b8f4270 --- /dev/null +++ b/llt/arraylist.h @@ -0,0 +1,19 @@ +#ifndef __ARRAYLIST_H_ +#define __ARRAYLIST_H_ + +#define AL_N_INLINE 29 + +typedef struct { + size_t len; + size_t max; + void **items; + void *_space[AL_N_INLINE]; +} arraylist_t; + +arraylist_t *arraylist_new(arraylist_t *a, size_t size); +void arraylist_free(arraylist_t *a); + +void arraylist_push(arraylist_t *a, void *elt); +void *arraylist_pop(arraylist_t *a); + +#endif