shithub: mc

ref: 4a95d9e52e8cb216f9ba963096097b4906aa49f0
dir: /libstd/slurp.myr/

View raw version
use "alloc.use"
use "die.use"
use "result.use"
use "extremum.use"
use "fmt.use"
use "sys.use"
use "types.use"

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

const Bufinc = 4096

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

const fslurp = {fd
	var n
	var len
	var buf

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