diff options
Diffstat (limited to 'src/bytearray.c')
| -rw-r--r-- | src/bytearray.c | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/src/bytearray.c b/src/bytearray.c new file mode 100644 index 0000000..0abfe49 --- /dev/null +++ b/src/bytearray.c | |||
| @@ -0,0 +1,52 @@ | |||
| 1 | /* | ||
| 2 | * bytearray.c | ||
| 3 | * simple byte 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 <string.h> | ||
| 22 | #include "bytearray.h" | ||
| 23 | |||
| 24 | bytearray_t *byte_array_new() | ||
| 25 | { | ||
| 26 | bytearray_t *a = (bytearray_t*)malloc(sizeof(bytearray_t)); | ||
| 27 | a->data = malloc(256); | ||
| 28 | a->len = 0; | ||
| 29 | a->capacity = 256; | ||
| 30 | return a; | ||
| 31 | } | ||
| 32 | |||
| 33 | void byte_array_free(bytearray_t *ba) | ||
| 34 | { | ||
| 35 | if (!ba) return; | ||
| 36 | if (ba->data) { | ||
| 37 | free(ba->data); | ||
| 38 | } | ||
| 39 | free(ba); | ||
| 40 | } | ||
| 41 | |||
| 42 | void byte_array_append(bytearray_t *ba, void *buf, size_t len) | ||
| 43 | { | ||
| 44 | if (!ba || !ba->data || (len <= 0)) return; | ||
| 45 | size_t remaining = ba->capacity-ba->len; | ||
| 46 | if (len > remaining) { | ||
| 47 | ba->data = realloc(ba->data, ba->capacity + (len - remaining)); | ||
| 48 | ba->capacity += (len - remaining); | ||
| 49 | } | ||
| 50 | memcpy(ba->data+ba->len, buf, len); | ||
| 51 | ba->len += len; | ||
| 52 | } | ||
