summaryrefslogtreecommitdiff
path: root/lib/std/slurp.myr
blob: ac90b2348bb0d9fca5547f782cd37ceb2880ad97 (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
43
44
use "alloc.use"
use "die.use"
use "result.use"
use "extremum.use"
use "syswrap.use"
use "errno.use"
use "types.use"

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

const Bufstart = 4096

const slurp = {path
	match open(path, Ordonly)
	| `Ok fd:	-> fslurp(fd)
	| `Fail e:	-> `Fail e
	;;
}

const fslurp = {fd
	var len, bufsz
	var buf

	len = 0
	bufsz = Bufstart
	buf = slalloc(bufsz)
	while true
		match read(fd, buf[len:])
		| `Ok n:
			if n == 0
				-> `Ok buf[:len]
			;;
			len += n
			bufsz *= 2
			buf = slgrow(buf, bufsz)
		| `Fail e:
			-> `Fail e
		;;
	;;
	die("unreachable")
}