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 */
19 #if defined(HAVE_STRINGS_H) && !defined(_STRING_H) && !defined(__USE_BSD)
21 #endif /* HAVE_STRINGS_H */
24 #include "arraylist.h"
27 array_list_new(array_list_free_fn
*free_fn
)
29 struct array_list
*arr
;
31 arr
= (struct array_list
*)calloc(1, sizeof(struct array_list
));
33 arr
->size
= ARRAY_LIST_DEFAULT_SIZE
;
35 arr
->free_fn
= free_fn
;
36 if(!(arr
->array
= (void**)calloc(sizeof(void*), arr
->size
))) {
44 array_list_free(struct array_list
*arr
)
47 for(i
= 0; i
< arr
->length
; i
++)
48 if(arr
->array
[i
]) arr
->free_fn(arr
->array
[i
]);
54 array_list_get_idx(struct array_list
*arr
, int i
)
56 if(i
>= arr
->length
) return NULL
;
60 static int array_list_expand_internal(struct array_list
*arr
, int max
)
65 if(max
< arr
->size
) return 0;
66 new_size
= json_max(arr
->size
<< 1, max
);
67 if(!(t
= realloc(arr
->array
, new_size
*sizeof(void*)))) return -1;
68 arr
->array
= (void**)t
;
69 (void)memset(arr
->array
+ arr
->size
, 0, (new_size
-arr
->size
)*sizeof(void*));
75 array_list_put_idx(struct array_list
*arr
, int idx
, void *data
)
77 if(array_list_expand_internal(arr
, idx
+1)) return -1;
78 if(arr
->array
[idx
]) arr
->free_fn(arr
->array
[idx
]);
79 arr
->array
[idx
] = data
;
80 if(arr
->length
<= idx
) arr
->length
= idx
+ 1;
85 array_list_add(struct array_list
*arr
, void *data
)
87 return array_list_put_idx(arr
, arr
->length
, data
);
91 array_list_sort(struct array_list
*arr
, int(*sort_fn
)(const void *, const void *))
93 qsort(arr
->array
, arr
->length
, sizeof(arr
->array
[0]),
94 (int (*)(const void *, const void *))sort_fn
);
98 array_list_length(struct array_list
*arr
)