ref: 309ff4672b7f5cba9bca1ce8657f767b51f32220 scdoc/src/string.c -rw-r--r-- 800 bytes View raw
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <stdlib.h>
#include <stdint.h>
#include "str.h"
#include "unicode.h"

static int ensure_capacity(str_t *str, size_t len) {
	if (len + 1 >= str->size) {
		char *new = realloc(str->str, str->size * 2);
		if (!new) {
			return 0;
		}
		str->str = new;
		str->size *= 2;
	}
	return 1;
}

str_t *str_create() {
	str_t *str = calloc(sizeof(str_t), 1);
	str->str = malloc(16);
	str->size = 16;
	str->len = 0;
	str->str[0] = '\0';
	return str;
}

void str_free(str_t *str) {
	if (!str) return;
	free(str->str);
	free(str);
}

int str_append_ch(str_t *str, uint32_t ch) {
	int size = utf8_chsize(ch);
	if (size <= 0) {
		return -1;
	}
	if (!ensure_capacity(str, str->len + size)) {
		return -1;
	}
	utf8_encode(&str->str[str->len], ch);
	str->len += size;
	str->str[str->len] = '\0';
	return size;
}