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
46 #define SHL_ARRAY_AT(_arr, _type, _pos) \
47 (&((_type*)shl_array_get_array(_arr))[(_pos)])
49 static inline int shl_array_new(struct shl_array **out, size_t element_size,
52 struct shl_array *arr;
54 if (!out || !element_size)
60 arr = malloc(sizeof(*arr));
63 memset(arr, 0, sizeof(*arr));
64 arr->element_size = element_size;
66 arr->size = initial_size;
68 arr->data = malloc(arr->element_size * arr->size);
78 static inline void shl_array_free(struct shl_array *arr)
87 static inline int shl_array_push(struct shl_array *arr, const void *data)
95 if (arr->length >= arr->size) {
96 newsize = arr->size * 2;
97 tmp = realloc(arr->data, arr->element_size * newsize);
105 memcpy(((uint8_t*)arr->data) + arr->element_size * arr->length,
106 data, arr->element_size);
112 static inline void shl_array_pop(struct shl_array *arr)
114 if (!arr || !arr->length)
120 static inline void *shl_array_get_array(struct shl_array *arr)
128 static inline size_t shl_array_get_length(struct shl_array *arr)
136 static inline size_t shl_array_get_bsize(struct shl_array *arr)
141 return arr->length * arr->element_size;
144 static inline size_t shl_array_get_element_size(struct shl_array *arr)
149 return arr->element_size;
152 #endif /* SHL_ARRAY_H */