shithub: mc

ref: 3c7cf598f83d27ac3b98e0061075052f9f9baaf1
dir: /lib/std/strjoin.myr/

View raw version
use "alloc"
use "die"
use "slcp"

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 s

	len = 0
	for var 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 var 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
}