1 : /*
2 : * $Id: arraylist.c,v 1.4 2006/01/26 02:16:28 mclark Exp $
3 : *
4 : * Copyright (c) 2004, 2005 Metaparadigm Pte. Ltd.
5 : * Michael Clark <michael@metaparadigm.com>
6 : *
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.
9 : *
10 : */
11 :
12 : #include "config.h"
13 :
14 : #if STDC_HEADERS
15 : # include <stdlib.h>
16 : # include <string.h>
17 : #endif /* STDC_HEADERS */
18 :
19 : #if defined HAVE_STRINGS_H && !defined _STRING_H && !defined __USE_BSD
20 : # include <strings.h>
21 : #endif /* HAVE_STRINGS_H */
22 :
23 : #include "bits.h"
24 : #include "arraylist.h"
25 :
26 : struct array_list*
27 5253 : array_list_new(array_list_free_fn *free_fn)
28 : {
29 : struct array_list *arr;
30 :
31 5253 : arr = (struct array_list*)calloc(1, sizeof(struct array_list));
32 5253 : if(!arr) return NULL;
33 5253 : arr->size = ARRAY_LIST_DEFAULT_SIZE;
34 5253 : arr->length = 0;
35 5253 : arr->free_fn = free_fn;
36 5253 : if((arr->array = (void**)calloc(sizeof(void*), arr->size)) == NULL) {
37 0 : free(arr);
38 0 : return NULL;
39 : }
40 5253 : return arr;
41 : }
42 :
43 : extern void
44 5253 : array_list_free(struct array_list *arr)
45 : {
46 : int i;
47 20271 : for(i = 0; i < arr->length; i++)
48 15018 : if(arr->array[i]) arr->free_fn(arr->array[i]);
49 5253 : free(arr->array);
50 5253 : free(arr);
51 5253 : }
52 :
53 : void*
54 6915 : array_list_get_idx(struct array_list *arr, int i)
55 : {
56 6915 : if(i >= arr->length) return NULL;
57 6915 : return arr->array[i];
58 : }
59 :
60 15018 : static int array_list_expand_internal(struct array_list *arr, int max)
61 : {
62 : void *t;
63 : int new_size;
64 :
65 15018 : if(max < arr->size) return 0;
66 22 : new_size = json_max(arr->size << 1, max);
67 22 : if((t = realloc(arr->array, new_size*sizeof(void*))) == NULL) return -1;
68 22 : arr->array = (void**)t;
69 22 : (void)memset(arr->array + arr->size, 0, (new_size-arr->size)*sizeof(void*));
70 22 : arr->size = new_size;
71 22 : return 0;
72 : }
73 :
74 : int
75 15018 : array_list_put_idx(struct array_list *arr, int idx, void *data)
76 : {
77 15018 : if(array_list_expand_internal(arr, idx)) return -1;
78 15018 : if(arr->array[idx]) arr->free_fn(arr->array[idx]);
79 15018 : arr->array[idx] = data;
80 15018 : if(arr->length <= idx) arr->length = idx + 1;
81 15018 : return 0;
82 : }
83 :
84 : int
85 15018 : array_list_add(struct array_list *arr, void *data)
86 : {
87 15018 : return array_list_put_idx(arr, arr->length, data);
88 : }
89 :
90 : int
91 2804 : array_list_length(struct array_list *arr)
92 : {
93 2804 : return arr->length;
94 : }
|