Mercurial > libedl
comparison src/str.c @ 4:c2408abb258a
*: add dumping to string, rename EDL_file to EDL
| author | Paper <mrpapersonic@gmail.com> |
|---|---|
| date | Mon, 25 Dec 2023 16:24:16 -0500 |
| parents | |
| children | a6ab6d9c0dac |
comparison
equal
deleted
inserted
replaced
| 3:bd99b6549eb4 | 4:c2408abb258a |
|---|---|
| 1 #include <stdlib.h> | |
| 2 #include <string.h> | |
| 3 #include "str.h" | |
| 4 | |
| 5 int EDL_internal_string_init(EDL_internal_string* str) { | |
| 6 if (!str) | |
| 7 return 0; | |
| 8 | |
| 9 str->size = 0; | |
| 10 str->capacity = 0; | |
| 11 str->data = NULL; | |
| 12 return 1; | |
| 13 } | |
| 14 | |
| 15 int EDL_internal_string_allocate(EDL_internal_string* str, size_t new_capacity) { | |
| 16 if (new_capacity == str->capacity) | |
| 17 return 1; // nothing to do | |
| 18 | |
| 19 str->data = realloc(str->data, new_capacity * sizeof(char)); | |
| 20 if (!str->data) | |
| 21 return 0; | |
| 22 | |
| 23 if (new_capacity > str->capacity) | |
| 24 memset(&str->data[str->capacity], 0, (new_capacity - str->capacity) * sizeof(char)); | |
| 25 | |
| 26 str->capacity = new_capacity; | |
| 27 | |
| 28 return 1; | |
| 29 } | |
| 30 | |
| 31 int EDL_internal_string_append(EDL_internal_string* str, const char* data, const size_t length) { | |
| 32 /* this sucks, but I'm too lazy to write anything smarter. */ | |
| 33 { | |
| 34 size_t capacity = 1; | |
| 35 while (capacity < (str->size + length + 1)) | |
| 36 capacity *= 2; | |
| 37 | |
| 38 if (capacity < str->capacity || !EDL_internal_string_allocate(str, capacity)) | |
| 39 return 0; | |
| 40 } | |
| 41 | |
| 42 strncat(str->data, data, length); | |
| 43 str->size += length; | |
| 44 | |
| 45 return 1; | |
| 46 } | |
| 47 | |
| 48 void EDL_internal_string_free(EDL_internal_string* str) { | |
| 49 if (str->data) | |
| 50 free(str->data); | |
| 51 } |
