summaryrefslogtreecommitdiff
path: root/lib/std/fmtfuncs.myr
blob: abe5e757bd1e3a85535aafc1ee848f1913339c8d (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
use "alloc.use"
use "bigint.use"
use "bitset.use"
use "fmt.use"
use "introspect.use"
use "strbuf.use"
use "varargs.use"

pkg std =
;;

const __init__ = {
	var bigint : bigint#
	var bitset : bitset#

	fmtinstall(typeof(bigint), bigfmt, [][:])
	fmtinstall(typeof(bitset), bsfmt, [][:])
}

const bigfmt = {sb, ap, opts
	var a, n, buf

	a = vanext(ap)
 	/*
	allocate a buffer guaranteed to be big enough.
	that's 
		2 + floor(nbits/(log_2(10)))
	or
		2 + a.dig.len * 32/3.32...
	or
		2 + a.dig.len * 10
	plus one for the - sign.
	*/
	buf = slalloc(3 + a.dig.len * 10)
	n = bigbfmt(buf, a, 10)
	sbputs(sb, buf[:n])
	slfree(buf)
}

const bsfmt = {sb, ap, opts
	var i, bs, sep

	bs = vanext(ap)
	sep = ""
	sbputs(sb, "bitset{")
	for i = 0; i < bsmax(bs); i++
		if bshas(bs, i)
			sbfmt(sb, sep)
			sbfmt(sb, "{}", i)
			sep = ", "
		;;
	;;
	sbputs(sb, "}")
}