summaryrefslogtreecommitdiff
path: root/lib/bio/mem.myr
blob: bf8991275120628b3625e335771a98efe0680cae (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
45
46
47
48
49
50
51
use std
use "bio"

pkg bio =
	const mkmem	: (buf : byte[:] -> file#)
;;

type mem = struct
	buf	: byte[:]
	off	: std.size
;;

const mkmem = {buf
	var mem : mem#

	mem = std.mk([
		.buf = buf,
		.off = 0
	])

	-> mk(Rd, [
		.read = {buf; -> memread(mem, buf)},
		.write = {buf; -> memwrite(mem, buf)},
		.seek = {off; -> memseek(mem, off)},
		.close = {; std.free(mem)},
	])
}

const memread = {mem, dst
	var n

	n = std.min(mem.buf.len - mem.off, dst.len)
	std.slcp(dst[:n], mem.buf[mem.off:mem.off+n])
	mem.off += n
	-> `std.Ok n
}

const memwrite = {mem, src
	var n

	n = std.min(mem.buf.len - mem.off, src.len)
	std.slcp(mem.buf[mem.off:mem.off+n], src[:n])
	mem.off += n
	-> `std.Ok n
}

const memseek = {mem, off : std.off
	off = std.clamp(off, 0, mem.buf.len)
	mem.off = (off : std.size)
	-> `std.Ok off
}