summaryrefslogtreecommitdiff
path: root/libstd/strbuf.myr
blob: 88e24ec6c95978c1644d8d5b9ddd1bd7616097f8 (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
use "alloc.use"
use "die.use"
use "extremum.use"
use "slcp.use"
use "types.use"
use "utf.use"
use "fmt.use"

pkg std =
	type strbuf = struct
		buf	: byte[:]
		len	: size
		fixed	: bool
	;;

	const mksb	: (-> strbuf#)
	const sbfin	: (sb : strbuf# -> byte[:])
	const sbfree	: (sb : strbuf# -> void)
	const sbpeek	: (sb : strbuf# -> byte[:])

	const sbputc	: (sb : strbuf#, v : char -> bool)
	const sbputs	: (sb : strbuf#, v : byte[:] -> bool)
	const sbputb	: (sb : strbuf#, v : byte -> bool)
	const sbtrim	: (sb : strbuf#, len : std.size -> void)
;;

const mksb	= {
	var sb
	sb = std.zalloc()
	sb.buf = std.slalloc(1)
	-> sb
}

const sbfin = {sb : strbuf#
	var sl

	sl = sb.buf[:sb.len]
	std.free(sb)
	-> sl
}

const sbpeek = {sb : strbuf#
	-> sb.buf[:sb.len]
}

const sbputc = {sb, v
	if !ensure(sb, charlen(v))
		-> false
	;;
	sb.len += encode(sb.buf[sb.len:], v)
	-> true
}
const sbputs = {sb, v
	if !ensure(sb, v.len)
		-> false
	;;
	std.slcp(sb.buf[sb.len:sb.len + v.len], v)
	sb.len += v.len
	-> true
}
const sbputb = {sb, v
	if !ensure(sb, 1)
		-> false
	;;
	sb.buf[sb.len++] = v
	-> true
}

const sbtrim = {sb, len
	std.assert(std.abs(len) <= sb.len, "trim out of range\n")
	if len < 0
		sb.len -= std.abs(len)
	else
		sb.len = len
	;;
}

const ensure = {sb, len
	if sb.fixed && sb.len + len >= sb.buf.len
		-> false
	;;
	while sb.buf.len < sb.len + len
		sb.buf = slgrow(sb.buf, 2*sb.buf.len)
	;;
	-> true
}