summaryrefslogtreecommitdiff
path: root/lib/std/fmtfuncs.myr
blob: 545506ad4e15c150b5085ef10cfaddfba3f84a71 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use "alloc"
use "bigint"
use "bitset"
use "fmt"
use "introspect"
use "strbuf"
use "varargs"
use "ipparse"

pkg std =
;;

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

	bigint = mkbigint(0)
	bitset = mkbs()
	fmtinstall(typeof(bigint), bigfmt)
	fmtinstall(typeof(bitset), bsfmt)
	fmtinstall(typeof(ipaddr), ipfmt)
	bigfree(bigint)
	bsfree(bitset)
}

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 bs, sep

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

const ipfmt = {sb, ap, opts
	var ip : netaddr
	var sep = "" 

	ip = std.vanext(ap)
	match ip
	| `Ipv4 a:
		std.put("{}.{}.{}.{}", a[0], a[1], a[2], a[3])
	| `Ipv6 a:	
		sep = ""
		for var i = 0; i < 16; i += 2
			std.put("{}{w=2,p=0,x}{w=2,p=0,x}", sep, a[i+0], a[i+1])
			sep = ":"
		;;
	;;
}