summaryrefslogtreecommitdiff
path: root/lib/std/fndup.myr
blob: 4bbed61ac3f37495ecb536dd2c36c92f5fbc756f (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
52
53
54
55
56
57
58
59
use "alloc"
use "die"
use "sldup"
use "slcp"
use "types"

pkg std =
	generic fnenvsz	: (fn : @fn::function -> size)
	generic fndup	: (fn : @fn::function -> @fn::function)
	generic fnbdup	: (fn : @fn::function, buf : byte[:] -> @fn::function)
	generic fnfree	: (fn : @fn::function -> void)
;;

generic fndup = {fn
	var sl

	sl = std.slalloc(fnenvsz(fn))
	-> fnbdup(fn, sl)
}

generic fnenvsz = {fn
	var repr : intptr[2]

	repr = (&fn : intptr[2]#)#
	-> envslice(repr[0]).len
}

extern const put : (fmt : byte[:], args : ... -> int64)

generic fnbdup = {fn, buf
	var repr : intptr[2]
	var env

	repr = (&fn : intptr[2]#)#
	env = envslice(repr[0])
	slcp(buf[:env.len], env)
	repr[0] = (buf : intptr)
	-> (&repr : @fn::function#)#
}

generic fnfree = {fn
	var repr : intptr[2]

	repr = (&fn : intptr[2]#)#
	std.slfree(envslice(repr[0]))
}

const envslice = {ep : intptr
	var env : byte#
	var szp : intptr#

	if ep == 0
		-> [][:]
	;;
	env = (ep : byte#)
	szp = (env : intptr#)
	-> env[:szp#]
}