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.
19 #endif /* STDC_HEADERS */
21 #if defined(HAVE_STRINGS_H) && !defined(_STRING_H) && !defined(__USE_BSD)
23 #endif /* HAVE_STRINGS_H */
26 #if SIZEOF_SIZE_T == SIZEOF_INT
27 #define SIZE_T_MAX UINT_MAX
28 #elif SIZEOF_SIZE_T == SIZEOF_LONG
29 #define SIZE_T_MAX ULONG_MAX
30 #elif SIZEOF_SIZE_T == SIZEOF_LONG_LONG
31 #define SIZE_T_MAX ULLONG_MAX
33 #error Unable to determine size of size_t
37 #include "arraylist.h"
40 array_list_new(array_list_free_fn *free_fn)
42 struct array_list *arr;
44 arr = (struct array_list*)calloc(1, sizeof(struct array_list));
46 arr->size = ARRAY_LIST_DEFAULT_SIZE;
48 arr->free_fn = free_fn;
49 if(!(arr->array = (void**)calloc(sizeof(void*), arr->size))) {
57 array_list_free(struct array_list *arr)
60 for(i = 0; i < arr->length; i++)
61 if(arr->array[i]) arr->free_fn(arr->array[i]);
67 array_list_get_idx(struct array_list *arr, size_t i)
69 if(i >= arr->length) return NULL;
73 static int array_list_expand_internal(struct array_list *arr, size_t max)
78 if(max < arr->size) return 0;
79 /* Avoid undefined behaviour on size_t overflow */
80 if( arr->size >= SIZE_T_MAX / 2 )
84 new_size = arr->size << 1;
88 if (new_size > (~((size_t)0)) / sizeof(void*)) return -1;
89 if (!(t = realloc(arr->array, new_size*sizeof(void*)))) return -1;
90 arr->array = (void**)t;
91 (void)memset(arr->array + arr->size, 0, (new_size-arr->size)*sizeof(void*));
97 array_list_put_idx(struct array_list *arr, size_t idx, void *data)
99 if (idx > SIZE_T_MAX - 1 ) return -1;
100 if(array_list_expand_internal(arr, idx+1)) return -1;
101 if(idx < arr->length && arr->array[idx])
102 arr->free_fn(arr->array[idx]);
103 arr->array[idx] = data;
104 if(arr->length <= idx) arr->length = idx + 1;
109 array_list_add(struct array_list *arr, void *data)
111 return array_list_put_idx(arr, arr->length, data);
115 array_list_sort(struct array_list *arr, int(*sort_fn)(const void *, const void *))
117 qsort(arr->array, arr->length, sizeof(arr->array[0]), sort_fn);
120 void* array_list_bsearch(const void **key, struct array_list *arr,
121 int (*sort_fn)(const void *, const void *))
123 return bsearch(key, arr->array, arr->length, sizeof(arr->array[0]),
128 array_list_length(struct array_list *arr)
134 array_list_del_idx( struct array_list *arr, size_t idx, size_t count )
139 if ( idx >= arr->length || stop > arr->length ) return -1;
140 for ( i = idx; i < stop; ++i ) {
141 if ( arr->array[i] ) arr->free_fn( arr->array[i] );
143 memmove( arr->array + idx, arr->array + stop, (arr->length - stop) * sizeof(void*) );
144 arr->length -= count;