| [10853] | 1 | |
|---|
| 2 | |
|---|
| 3 | |
|---|
| 4 | |
|---|
| 5 | |
|---|
| 6 | |
|---|
| 7 | |
|---|
| 8 | |
|---|
| 9 | |
|---|
| 10 | |
|---|
| 11 | |
|---|
| 12 | |
|---|
| 13 | |
|---|
| 14 | |
|---|
| 15 | |
|---|
| 16 | |
|---|
| 17 | |
|---|
| 18 | #include "lib3ds_impl.h" |
|---|
| 19 | |
|---|
| 20 | |
|---|
| 21 | void* lib3ds_util_realloc_array(void *ptr, int old_size, int new_size, int element_size) { |
|---|
| 22 | if (!ptr) |
|---|
| 23 | old_size = 0; |
|---|
| 24 | if (old_size != new_size) { |
|---|
| 25 | ptr = realloc(ptr, element_size * new_size); |
|---|
| 26 | if (old_size < new_size) { |
|---|
| 27 | memset((char*)ptr + element_size * old_size, 0, element_size * (new_size - old_size)); |
|---|
| 28 | } |
|---|
| 29 | } |
|---|
| 30 | return ptr; |
|---|
| 31 | } |
|---|
| 32 | |
|---|
| 33 | |
|---|
| 34 | void lib3ds_util_reserve_array(void ***ptr, int *n, int *size, int new_size, int force, Lib3dsFreeFunc free_func) { |
|---|
| 35 | assert(ptr && n && size); |
|---|
| 36 | if ((*size < new_size) || force) { |
|---|
| 37 | if (force && free_func) { |
|---|
| 38 | int i; |
|---|
| 39 | for (i = new_size; i < *n; ++i) { |
|---|
| 40 | free_func((*ptr)[i]); |
|---|
| 41 | (*ptr)[i] = 0; |
|---|
| 42 | } |
|---|
| 43 | } |
|---|
| 44 | *ptr = (void**)realloc(*ptr, sizeof(void*) * new_size); |
|---|
| 45 | *size = new_size; |
|---|
| 46 | if (*n > new_size) { |
|---|
| 47 | *n = new_size; |
|---|
| 48 | } |
|---|
| 49 | } |
|---|
| 50 | } |
|---|
| 51 | |
|---|
| 52 | |
|---|
| 53 | void lib3ds_util_insert_array(void ***ptr, int *n, int *size, void *element, int index) { |
|---|
| 54 | int i; |
|---|
| 55 | assert(ptr && n && size && element); |
|---|
| 56 | i = ((index >= 0) && (index < *n)) ? index : *n; |
|---|
| 57 | if (i >= *size) { |
|---|
| 58 | int new_size = 2 * (*size); |
|---|
| 59 | #ifdef _DEBUG |
|---|
| 60 | if (new_size < 1) { |
|---|
| 61 | new_size = 1; |
|---|
| 62 | } |
|---|
| 63 | #else |
|---|
| 64 | if (new_size < 32) { |
|---|
| 65 | new_size = 32; |
|---|
| 66 | } |
|---|
| 67 | #endif |
|---|
| 68 | lib3ds_util_reserve_array(ptr, n, size, new_size, FALSE, NULL); |
|---|
| 69 | } |
|---|
| 70 | assert(*ptr); |
|---|
| 71 | if (i < *n) { |
|---|
| 72 | memmove(&(*ptr)[i+1], &(*ptr)[i], sizeof(void*) * (*n - i)); |
|---|
| 73 | } |
|---|
| 74 | (*ptr)[i] = element; |
|---|
| 75 | *n = *n + 1; |
|---|
| 76 | } |
|---|
| 77 | |
|---|
| 78 | |
|---|
| 79 | void lib3ds_util_remove_array(void ***ptr, int *n, int index, Lib3dsFreeFunc free_func) { |
|---|
| 80 | assert(ptr && n); |
|---|
| 81 | if ((index >= 0) && (index < *n)) { |
|---|
| 82 | assert(*ptr); |
|---|
| 83 | free_func((*ptr)[index]); |
|---|
| 84 | if (index < *n - 1) { |
|---|
| 85 | memmove(&(*ptr)[index], &(*ptr)[index+1], sizeof(void*) * (*n - index - 1)); |
|---|
| 86 | } |
|---|
| 87 | *n = *n - 1; |
|---|
| 88 | } |
|---|
| 89 | } |
|---|