2 * $Id: arraylist.c,v 1.4 2006/01/26 02:16:28 mclark Exp $
4 * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
5 * Michael Clark <michael@metaparadigm.com>
7 * This library is free software; you can redistribute it and/or modify
8 * it under the terms of the MIT license. See COPYING for details.
17 #endif /* STDC_HEADERS */
21 #endif /* HAVE_STRINGS_H */
24 #include "arraylist.h"
27 array_list_new(array_list_free_fn *free_fn)
29 struct array_list *this;
31 if(!(this = calloc(1, sizeof(struct array_list)))) return NULL;
32 this->size = ARRAY_LIST_DEFAULT_SIZE;
34 this->free_fn = free_fn;
35 if(!(this->array = calloc(sizeof(void*), this->size))) {
43 array_list_free(struct array_list *this)
46 for(i = 0; i < this->length; i++)
47 if(this->array[i]) this->free_fn(this->array[i]);
53 array_list_get_idx(struct array_list *this, int i)
55 if(i >= this->length) return NULL;
56 return this->array[i];
59 static int array_list_expand_internal(struct array_list *this, int max)
64 if(max < this->size) return 0;
65 new_size = max(this->size << 1, max);
66 if(!(t = realloc(this->array, new_size*sizeof(void*)))) return -1;
68 (void)memset(this->array + this->size, 0, (new_size-this->size)*sizeof(void*));
69 this->size = new_size;
74 array_list_put_idx(struct array_list *this, int idx, void *data)
76 if(array_list_expand_internal(this, idx)) return -1;
77 if(this->array[idx]) this->free_fn(this->array[idx]);
78 this->array[idx] = data;
79 if(this->length <= idx) this->length = idx + 1;
84 array_list_add(struct array_list *this, void *data)
86 return array_list_put_idx(this, this->length, data);
90 array_list_length(struct array_list *this)