summaryrefslogtreecommitdiff
path: root/lib/std/strjoin.myr
blob: 518a4dcb85c9e6a310d84c4e506ae147a93744df (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
use "alloc.use"
use "die.use"
use "slcp.use"

pkg std =
	const strcat	: (a : byte[:], b : byte[:] -> byte[:])
	const strjoin	: (strings : byte[:][:], delim : byte[:] -> byte[:])
;;

const strcat = {a, b
	-> strjoin([a, b][:], "")
}

const strjoin = {strings, delim
	var len, off
	var i
	var s

	len = 0
	for i = 0; i < strings.len; i++
		len += strings[i].len
	;;
	if strings.len > 0
		len += (strings.len - 1)*delim.len
	;;

	s = slalloc(len)
	off = 0
	for i = 0; i < strings.len; i++
		slcp(s[off:off + strings[i].len], strings[i])
		off += strings[i].len
		/* we don't want to terminate the last string with delim */
		if i != strings.len - 1
			slcp(s[off:off + delim.len], delim)
			off += delim.len
		;;
	;;
	-> s
}