byte_array.h
| 1 | #ifndef CUTILS_BYTE_ARRAY_H |
| 2 | #define CUTILS_BYTE_ARRAY_H |
| 3 | #include <stdlib.h> |
| 4 | #include <string.h> |
| 5 | #include <errno.h> |
| 6 | #include <cutils/common.h> |
| 7 | |
| 8 | #define BYTEARRAY_DEFAULT_SIZE 4 |
| 9 | |
| 10 | typedef struct Bytearray |
| 11 | { |
| 12 | byte* items; |
| 13 | size_t capacity; |
| 14 | size_t length; |
| 15 | size_t element_size; |
| 16 | } Bytearray; |
| 17 | |
| 18 | Bytearray* bytearray_with_capacity(size_t capacity, size_t element_size); |
| 19 | void delete_bytearray(Bytearray* bytearray, void(*rmv_el) (void*)); |
| 20 | |
| 21 | HEDLEY_INLINE |
| 22 | static void* bytearray_at(const Bytearray* bytearray, size_t index) |
| 23 | { |
| 24 | return bytearray->items+(index*bytearray->element_size); |
| 25 | } |
| 26 | void* bytearray_pop_at(Bytearray* bytearray, size_t index, void* retptr); |
| 27 | |
| 28 | bool bytearray_insert(Bytearray* bytearray, size_t index, const void* item); |
| 29 | |
| 30 | HEDLEY_INLINE |
| 31 | static void bytearray_remove(Bytearray* bytearray, size_t index, void (*rmv)(void*)) |
| 32 | { |
| 33 | if(index < bytearray->length) |
| 34 | { |
| 35 | size_t length = bytearray->length; |
| 36 | size_t elsize = bytearray->element_size; |
| 37 | if(rmv) |
| 38 | rmv(&bytearray->items[index*elsize]); |
| 39 | |
| 40 | memmove(bytearray->items+index*elsize, bytearray->items+index*elsize+1*elsize, length*elsize-index*elsize-1*elsize); |
| 41 | bytearray->length--; |
| 42 | } |
| 43 | } |
| 44 | void bytearray_remove_range(Bytearray* bytearray, size_t index, size_t length, void (*rmv)(void*)); |
| 45 | |
| 46 | bool bytearray_grow(Bytearray* bytearray, size_t add); |
| 47 | bool bytearray_adjust_size(Bytearray* bytearray, size_t size); |
| 48 | bool bytearray_shrink(Bytearray* bytearray); |
| 49 | HEDLEY_NON_NULL(3) |
| 50 | size_t* bytearray_find(const Bytearray* haystack, const void* needle, int (*cmp)(const void*, const void*)); |
| 51 | |
| 52 | #define new_bytearray(element_size) bytearray_with_capacity(BYTEARRAY_DEFAULT_SIZE, element_size) |
| 53 | #define bytearray_pop(bytearray, retptr) bytearray_pop_at(bytearray, bytearray->length-1, retptr) |
| 54 | #define bytearray_push(bytearray, item) bytearray_insert(bytearray, bytearray->length, item) |
| 55 | |
| 56 | #endif /* CUTILS_BYTE_ARRAY_H */ |
| 57 | |
| 58 |