shithub: mc

ref: 19d7fac9e6210af527ee1e72de4878d3951c41f6
dir: /lib/std/slurp.myr/

View raw version
use "alloc.use"
use "die.use"
use "result.use"
use "extremum.use"
use "syswrap.use"
use "types.use"

pkg std =
	const slurp : (path : byte[:] -> result(byte[:], byte[:]))
	const fslurp : (path : fd -> result(byte[:], byte[:]))
;;

const Bufstart = 4096

const slurp = {path
	var fd
	fd = open(path, Ordonly)
	if fd < 0
		-> `Fail "Could not open file"
	;;
	-> fslurp(fd)
}

const fslurp = {fd
	var len, bufsz
	var buf
	var n

	len = 0
	bufsz = Bufstart
	buf = slalloc(bufsz)
	while true
		n = read(fd, buf[len:])
		if n <= 0
			goto done
		;;
		len += n
		bufsz *= 2
		buf = slgrow(buf, bufsz)
	;;
:done
	-> `Ok buf[:len]
}