diff options
Diffstat (limited to 'src/ptrarray.c')
| -rw-r--r-- | src/ptrarray.c | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/src/ptrarray.c b/src/ptrarray.c new file mode 100644 index 0000000..8567752 --- /dev/null +++ b/src/ptrarray.c | |||
| @@ -0,0 +1,61 @@ | |||
| 1 | /* | ||
| 2 | * ptrarray.c | ||
| 3 | * simple pointer array implementation | ||
| 4 | * | ||
| 5 | * Copyright (c) 2011 Nikias Bassen, All Rights Reserved. | ||
| 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 | ||
| 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. | ||
| 16 | * | ||
| 17 | * You should have received a copy of the GNU Lesser General Public | ||
| 18 | * License along with this library; if not, write to the Free Software | ||
| 19 | * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA | ||
| 20 | */ | ||
| 21 | #include "ptrarray.h" | ||
| 22 | |||
| 23 | ptrarray_t *ptr_array_new(int capacity) | ||
| 24 | { | ||
| 25 | ptrarray_t *pa = (ptrarray_t*)malloc(sizeof(ptrarray_t)); | ||
| 26 | pa->pdata = (void**)malloc(sizeof(void*) * capacity); | ||
| 27 | pa->capacity = capacity; | ||
| 28 | pa->capacity_step = (capacity > 64) ? 64 : capacity; | ||
| 29 | pa->len = 0; | ||
| 30 | return pa; | ||
| 31 | } | ||
| 32 | |||
| 33 | void ptr_array_free(ptrarray_t *pa) | ||
| 34 | { | ||
| 35 | if (!pa) return; | ||
| 36 | if (pa->pdata) { | ||
| 37 | free(pa->pdata); | ||
| 38 | } | ||
| 39 | free(pa); | ||
| 40 | } | ||
| 41 | |||
| 42 | void ptr_array_add(ptrarray_t *pa, void *data) | ||
| 43 | { | ||
| 44 | if (!pa || !pa->pdata || !data) return; | ||
| 45 | size_t remaining = pa->capacity-pa->len; | ||
| 46 | if (remaining == 0) { | ||
| 47 | pa->pdata = realloc(pa->pdata, sizeof(void*) * (pa->capacity + pa->capacity_step)); | ||
| 48 | pa->capacity += pa->capacity_step; | ||
| 49 | } | ||
| 50 | pa->pdata[pa->len] = data; | ||
| 51 | pa->len++; | ||
| 52 | } | ||
| 53 | |||
| 54 | void* ptr_array_index(ptrarray_t *pa, size_t index) | ||
| 55 | { | ||
| 56 | if (!pa) return NULL; | ||
| 57 | if (index >= pa->len) { | ||
| 58 | return NULL; | ||
| 59 | } | ||
| 60 | return pa->pdata[index]; | ||
| 61 | } | ||
