4 * Copyright (c) 2011-2012 David Herrmann <dh.herrmann@googlemail.com>
5 * Copyright (c) 2011 University of Tuebingen
7 * Permission is hereby granted, free of charge, to any person obtaining
8 * a copy of this software and associated documentation files
9 * (the "Software"), to deal in the Software without restriction, including
10 * without limitation the rights to use, copy, modify, merge, publish,
11 * distribute, sublicense, and/or sell copies of the Software, and to
12 * permit persons to whom the Software is furnished to do so, subject to
13 * the following conditions:
15 * The above copyright notice and this permission notice shall be included
16 * in all copies or substantial portions of the Software.
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
19 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
20 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
21 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
23 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
24 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 * A dynamic array implementation
47 #define SHL_ARRAY_AT(_arr, _type, _pos) \
48 (&((_type*)shl_array_get_array(_arr))[(_pos)])
50 static inline int shl_array_new(struct shl_array **out, size_t element_size,
53 struct shl_array *arr;
55 if (!out || !element_size)
61 arr = malloc(sizeof(*arr));
64 memset(arr, 0, sizeof(*arr));
65 arr->element_size = element_size;
67 arr->size = initial_size;
69 arr->data = malloc(arr->element_size * arr->size);
79 static inline void shl_array_free(struct shl_array *arr)
88 /* resize to length=size and zero out new array entries */
89 static inline int shl_array_zresize(struct shl_array *arr, size_t size)
97 if (size > arr->size) {
98 newsize = shl_next_pow2(size);
99 tmp = realloc(arr->data, arr->element_size * newsize);
106 memset(((uint8_t*)arr->data) + arr->element_size * arr->length,
107 0, arr->element_size * (size - arr->length));
114 static inline int shl_array_push(struct shl_array *arr, const void *data)
122 if (arr->length >= arr->size) {
123 newsize = arr->size * 2;
124 tmp = realloc(arr->data, arr->element_size * newsize);
132 memcpy(((uint8_t*)arr->data) + arr->element_size * arr->length,
133 data, arr->element_size);
139 static inline void shl_array_pop(struct shl_array *arr)
141 if (!arr || !arr->length)
147 static inline void *shl_array_get_array(struct shl_array *arr)
155 static inline size_t shl_array_get_length(struct shl_array *arr)
163 static inline size_t shl_array_get_bsize(struct shl_array *arr)
168 return arr->length * arr->element_size;
171 static inline size_t shl_array_get_element_size(struct shl_array *arr)
176 return arr->element_size;
179 #endif /* SHL_ARRAY_H */