tizen 2.3 release
[external/buxton.git] / src / shared / buxtonarray.c
1 /*
2  * This file is part of buxton.
3  *
4  * Copyright (C) 2013 Intel Corporation
5  *
6  * buxton is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU Lesser General Public License as
8  * published by the Free Software Foundation; either version 2.1
9  * of the License, or (at your option) any later version.
10  */
11
12 #include <stdlib.h>
13 #include <string.h>
14
15 #include "buxtonarray.h"
16 #include "util.h"
17
18 BuxtonArray *buxton_array_new(void)
19 {
20         BuxtonArray *ret = NULL;
21         /* If this fails, we simply return NULL and allow the user
22          * to deal with the error */
23         ret = calloc(1, sizeof(BuxtonArray));
24         return ret;
25 }
26
27 bool buxton_array_add(BuxtonArray *array,
28                       void *data)
29 {
30         uint new_len;
31         size_t curr, new_size;
32
33         if (!array || !data) {
34                 return false;
35         }
36         if (!array->data) {
37                 array->data = calloc(1, sizeof(void*));
38                 if (!array->data) {
39                         return false;
40                 }
41         }
42
43         new_len = array->len += 1;
44         curr = (size_t)(array->len*sizeof(void*));
45         new_size = curr + sizeof(void*);
46         if (new_len >= array->len) {
47                 /* Resize the array to hold one more pointer */
48                 array->data = greedy_realloc((void**)&array->data, &curr, new_size);
49                 if (!array->data) {
50                         return false;
51                 }
52         }
53         /* Store the pointer at the end of the array */
54         array->len = new_len;
55         array->data[array->len-1] = data;
56         return true;
57 }
58
59 void *buxton_array_get(BuxtonArray *array, uint16_t index)
60 {
61         if (!array) {
62                 return NULL;
63         }
64         if (index > array->len) {
65                 return NULL;
66         }
67         return array->data[index];
68 }
69
70
71 void buxton_array_free(BuxtonArray **array,
72                        buxton_free_func free_method)
73 {
74         int i;
75         if (!array || !*array) {
76                 return;
77         }
78
79         if (free_method) {
80                 /* Call the free_method on all members */
81                 for (i = 0; i < (*array)->len; i++)
82                         free_method((*array)->data[i]);
83         }
84         /* Ensure this array is indeed gone. */
85         free((*array)->data);
86         free(*array);
87         *array = NULL;
88 }
89
90 /*
91  * Editor modelines  -  http://www.wireshark.org/tools/modelines.html
92  *
93  * Local variables:
94  * c-basic-offset: 8
95  * tab-width: 8
96  * indent-tabs-mode: t
97  * End:
98  *
99  * vi: set shiftwidth=8 tabstop=8 noexpandtab:
100  * :indentSize=8:tabSize=8:noTabs=false:
101  */