comparison src/str.c @ 8:0c98b46eaf73 v2.0

*: update API to 2.0, big changes all APIs now use pointers to an EDL object. it is up to the user to make sure that the pointer is valid. additionally, many things have been separated into new files to make it easier to digest
author Paper <paper@paper.us.eu.org>
date Sun, 03 Mar 2024 17:56:58 -0500
parents a6ab6d9c0dac
children 0cc2555db371
comparison
equal deleted inserted replaced
7:fee08fa622e1 8:0c98b46eaf73
1 #include "str.h"
2
1 #include <stdlib.h> 3 #include <stdlib.h>
2 #include <string.h> 4 #include <string.h>
3 #include "str.h" 5
6 /* rudimentary string functions so the code in edl.c isn't
7 * as painful to read
8 */
4 9
5 int EDL_internal_string_init(EDL_internal_string* str) { 10 int EDL_internal_string_init(EDL_internal_string* str) {
6 if (!str) 11 if (!str)
7 return 0; 12 return 0;
8 13
12 return 1; 17 return 1;
13 } 18 }
14 19
15 int EDL_internal_string_allocate(EDL_internal_string* str, size_t new_capacity) { 20 int EDL_internal_string_allocate(EDL_internal_string* str, size_t new_capacity) {
16 if (new_capacity == str->capacity) 21 if (new_capacity == str->capacity)
17 return 1; // nothing to do 22 return 1; /* nothing to do */
18 23
19 str->data = realloc(str->data, new_capacity * sizeof(char)); 24 str->data = realloc(str->data, new_capacity * sizeof(char));
20 if (!str->data) 25 if (!str->data)
21 return 0; 26 return 0;
22 27
23 if (new_capacity > str->capacity) 28 //if (new_capacity > str->capacity)
24 memset(&str->data[str->capacity], 0, (new_capacity - str->capacity) * sizeof(char)); 29 // memset(&str->data[str->capacity], 0, (new_capacity - str->capacity) * sizeof(char));
25 30
26 str->capacity = new_capacity; 31 str->capacity = new_capacity;
27 32
28 return 1; 33 return 1;
29 } 34 }
30 35
31 int EDL_internal_string_append(EDL_internal_string* str, const char* data, const size_t length) { 36 int EDL_internal_string_append(EDL_internal_string* str, const char* data, const size_t length) {
32 { 37 if (str->capacity == 0)
38 if (!EDL_internal_string_allocate(str, 1))
39 return 0;
40
41 if (str->size + length + 1 >= str->capacity) {
33 size_t capacity = 1; 42 size_t capacity = 1;
34 while (capacity < (str->size + length + 1)) 43 while (capacity < (str->size + length + 1))
35 capacity *= 2; 44 capacity *= 2;
36 45
37 if (capacity < str->capacity || !EDL_internal_string_allocate(str, capacity)) 46 if (!EDL_internal_string_allocate(str, capacity))
38 return 0; 47 return 0;
39 } 48 }
40 49
41 strncat(str->data, data, length); 50 strncat(str->data, data, length);
42 str->size += length; 51 str->size += length;
43 52
44 return 1; 53 return length;
45 } 54 }
46 55
47 void EDL_internal_string_free(EDL_internal_string* str) { 56 void EDL_internal_string_free(EDL_internal_string* str) {
48 if (str->data) 57 if (str->data)
49 free(str->data); 58 free(str->data);