libmya 0.1.0
Library to parse Mya language.
Loading...
Searching...
No Matches
dstring.c
Go to the documentation of this file.
1#include <stdlib.h>
2#include <string.h>
3
4#include "dstring.h"
5
6static void
7_dstring_ensure_size(dstring_t* string, unsigned int size);
8
9void
10dstring_init(dstring_t* string, unsigned int buffer_size)
11{
12 string->length = 0;
13 string->_buffer_size = buffer_size;
14 string->data = (buffer_size == 0) ? NULL : malloc(buffer_size);
15}
16
17void
19{
20 if (! string->data) {
21 return;
22 }
23
24 free(string->data);
25 string->data = NULL;
26}
27
28void
29dstring_putchar(dstring_t* string, int character)
30{
31 _dstring_ensure_size(string, string->length + 2);
32
33 string->data[string->length++] = character;
34 string->data[string->length] = '\0';
35}
36
37void
38dstring_concat(dstring_t* string, const char* source)
39{
40 size_t source_length = strlen(source);
41
42 _dstring_ensure_size(string, string->length + source_length + 1);
43
44 memcpy(string->data + string->length, source, source_length + 1);
45
46 string->length += source_length;
47}
48
49void
50dstring_copy(dstring_t* string, const char* source)
51{
52 size_t source_length = strlen(source);
53
54 _dstring_ensure_size(string, source_length + 1);
55
56 memcpy(string->data, source, source_length + 1);
57
58 string->length = source_length;
59}
60
64static void
65_dstring_ensure_size(dstring_t* string, unsigned int size)
66{
67 if (size < string->_buffer_size) {
68 // We will never decrease the buffer size.
69 return;
70 }
71
72 unsigned int new_size = ((size + DSTRING_CHUNK_SIZE) / DSTRING_CHUNK_SIZE) * DSTRING_CHUNK_SIZE;
73
74 string->data = realloc(string->data, new_size);
75 string->_buffer_size = new_size;
76}
void dstring_concat(dstring_t *string, const char *source)
Concatenates a string on the end of the dstring.
Definition dstring.c:38
void dstring_init(dstring_t *string, unsigned int buffer_size)
Initializes a dynamic string (dstring).
Definition dstring.c:10
void dstring_putchar(dstring_t *string, int character)
Concatenates a character on the end of the dstring.
Definition dstring.c:29
void dstring_copy(dstring_t *string, const char *source)
Copies the content of source to the dstring.
Definition dstring.c:50
void dstring_close(dstring_t *string)
Closes the dynamic string.
Definition dstring.c:18
unsigned int length
The length of the string.
Definition dstring.h:13
char * data
Pointer for the raw string content (a normal C string).
Definition dstring.h:12
struct dstring dstring_t
A dynamic string (dstring) that automatically reallocate her buffer when needed.
#define DSTRING_CHUNK_SIZE
The size of the chunk of a dynamic string.
Definition dstring.h:5