]> git.evergreen-ils.org Git - working/Evergreen.git/blob - OpenSRF/src/libjson/arraylist.c
6b42046df310e742f45be7675c65e68e32e6a317
[working/Evergreen.git] / OpenSRF / src / libjson / arraylist.c
1 /*
2  * $Id$
3  *
4  * Copyright Metaparadigm Pte. Ltd. 2004.
5  * Michael Clark <michael@metaparadigm.com>
6  *
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.
11  *
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/
16  *
17  */
18
19 #include <stdlib.h>
20 #include <string.h>
21 #include <strings.h>
22
23 #include "bits.h"
24 #include "arraylist.h"
25
26
27 struct array_list*
28 array_list_new(array_list_free_fn *free_fn)
29 {
30   struct array_list *this;
31
32   if(!(this = calloc(1, sizeof(struct array_list)))) return NULL;
33   this->size = ARRAY_LIST_DEFAULT_SIZE;
34   this->length = 0;
35   this->free_fn = free_fn;
36   if(!(this->array = calloc(sizeof(void*), this->size))) {
37     free(this);
38     return NULL;
39   }
40   return this;
41 }
42
43 extern void
44 array_list_free(struct array_list *this)
45 {
46   int i;
47   for(i = 0; i < this->length; i++)
48     if(this->array[i]) this->free_fn(this->array[i]);
49   free(this->array);
50   free(this);
51 }
52
53 void*
54 array_list_get_idx(struct array_list *this, int i)
55 {
56   if(i >= this->length) return NULL;
57   return this->array[i];
58 }
59
60 static int array_list_expand_internal(struct array_list *this, int max)
61 {
62   void *t;
63   int new_size;
64
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;
68   this->array = t;
69   bzero(this->array + this->size, (new_size-this->size)*sizeof(void*));
70   this->size = new_size;
71   return 0;
72 }
73
74 int
75 array_list_put_idx(struct array_list *this, int idx, void *data)
76 {
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;
81   return 0;
82 }
83
84 int
85 array_list_add(struct array_list *this, void *data)
86 {
87   return array_list_put_idx(this, this->length, data);
88 }
89
90 int
91 array_list_length(struct array_list *this)
92 {
93   return this->length;
94 }