summaryrefslogtreecommitdiff
path: root/libstd/slurp.myr
blob: b244ad62ea2fb3b35c804d0ea33db9e3048613a0 (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
use "alloc.use"
use "die.use"
use "result.use"
use "extremum.use"
use "fmt.use"
use "syswrap.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]
}