summary refs log tree commit diff
path: root/str.c
blob: 8d1806e2bf9c2606e319d3b7aaf48944c271dc58 (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include "str.h"
#include "err.h"

/* strings */

void str_init(str_t *b, size_t n) {
	b->buf = calloc(1, n);
	if (!b->buf) {
		efatal("str_init");
	}
	b->cap = n;
	b->sz = 0;
}

/* does NOT change sz! just makes room */
void str_grow(str_t *b, size_t n) {
	size_t sz = b->sz + n;
	size_t c = b->cap;
	if (sz > c) {
		while (sz > c) c <<= 1;
		char *p = realloc(b->buf, c);
		if (!p) efatal("str_grow");
		b->buf = p;
		b->cap = c;
	}
}

void str_cat(str_t *b, strv_t s) {
	str_grow(b, s.n);
	memcpy(&b->buf[b->sz], s.s, s.n);
	b->sz += s.n;
}

void str_catc(str_t *b, char c) {
	str_grow(b, 1);
	b->buf[b->sz++] = c;
}

void str_free(str_t *b) {
	free(b->buf);
}

/* string views */

strv_t strv(const char *s) {
	return (strv_t) { s, strlen(s) };
}

int strv_split(strv_t *src, int chr, strv_t *dest) {
	char *c = memchr(src->s, chr, src->n);
	*dest = (strv_t) {
		src->s,
		c ? c - src->s : src->n 
	};
	src->s = c ? c + 1 : &src->s[src->n];
	src->n -= dest->n + !!c;
	return (src->n + dest->n) > 0;
}

char strv_next(strv_t *s) {
	if (s->n > 0) {
		s->n--;
		return *(s->s++);
	} else {
		return 0;
	}
}

void str_fmt(str_t *b, const char *fmt, ...) {
	va_list ap;
	char c;
	b->sz = 0;
	va_start(ap, fmt);
	while ((c = *fmt++)) {
		if (c == '%' && *fmt) {
			switch ((c = *fmt++)) {
			case 'c':
				str_catc(b, va_arg(ap, int));
				break;
			case 's':
				str_cat(b, va_arg(ap, strv_t));
				break;
			default:
				str_catc(b, c);
			}
		} else {
			str_catc(b, c);
		}
	}
	va_end(ap);
}