4 * Copyright Metaparadigm Pte. Ltd. 2004.
5 * Michael Clark <michael@metaparadigm.com>
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public (LGPL)
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details: http://www.gnu.org/
24 #include "arraylist.h"
28 array_list_new(array_list_free_fn *free_fn)
30 struct array_list *this;
32 if(!(this = calloc(1, sizeof(struct array_list)))) return NULL;
33 this->size = ARRAY_LIST_DEFAULT_SIZE;
35 this->free_fn = free_fn;
36 if(!(this->array = calloc(sizeof(void*), this->size))) {
44 array_list_free(struct array_list *this)
47 for(i = 0; i < this->length; i++)
48 if(this->array[i]) this->free_fn(this->array[i]);
54 array_list_get_idx(struct array_list *this, int i)
56 if(i >= this->length) return NULL;
57 return this->array[i];
60 static int array_list_expand_internal(struct array_list *this, int max)
65 if(max < this->size) return 0;
66 new_size = max(this->size << 1, max);
67 if(!(t = realloc(this->array, new_size*sizeof(void*)))) return -1;
69 bzero(this->array + this->size, (new_size-this->size)*sizeof(void*));
70 this->size = new_size;
75 array_list_put_idx(struct array_list *this, int idx, void *data)
77 if(array_list_expand_internal(this, idx)) return -1;
78 if(this->array[idx]) this->free_fn(this->array[idx]);
79 this->array[idx] = data;
80 if(this->length <= idx) this->length = idx + 1;
85 array_list_add(struct array_list *this, void *data)
87 return array_list_put_idx(this, this->length, data);
91 array_list_length(struct array_list *this)