summaryrefslogtreecommitdiff
path: root/lib/std/test/ipparse.myr
blob: dfed4d6b82d5d1c972e9b785613c762c36d184df (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
use std

const main = {
	/* valid ipv4 address */
	eq("1.2.3.4", `std.Some `std.Ipv4 [1,2,3,4])

	/* invalid ipv4 address */
	eq("1.3.4", `std.None)	/* too short */
	eq("1.2.3.4.5", `std.None)	/* too long */
	eq("1.3.4.256", `std.None)	/* out of bounds 1 */
	eq("260.2.3.4", `std.None)	/* out of bounds 2 */

	/* valid ipv6 addresses */
	eq("2a03:2880:2110:df07:face:b00c:0:1", \
		`std.Some `std.Ipv6 [ \
			0x2a, 0x03, 0x28, 0x80,  \
			0x21, 0x10, 0xdf, 0x07,  \
			0xfa, 0xce, 0xb0, 0x0c,  \
			0x00, 0x00, 0x00, 0x01])
	eq("2a03:2880:2110::face:b00c:0:1", \
		`std.Some `std.Ipv6 [ \
			0x2a, 0x03, 0x28, 0x80,  \
			0x21, 0x10, 0x00, 0x00,  \
			0xfa, 0xce, 0xb0, 0x0c,  \
			0x00, 0x00, 0x00, 0x01])
	eq("2a03:2880:10::face:b00c:0:1", \
		`std.Some `std.Ipv6 [ \
			0x2a, 0x03, 0x28, 0x80,  \
			0x00, 0x10, 0x00, 0x00,  \
			0xfa, 0xce, 0xb0, 0x0c,  \
			0x00, 0x00, 0x00, 0x01])
	eq("2a03:2880:11:1f1b:face:b00c:0:25de", \
		`std.Some `std.Ipv6 [ \
			0x2a, 0x03, 0x28, 0x80, \
			0x00, 0x11, 0x1f, 0x1b, \
			0xfa, 0xce, 0xb0, 0x0c, \
			0x00, 0x00, 0x25, 0xde])
	eq("abcd::dcba", \
		`std.Some `std.Ipv6 [ \
			0xab, 0xcd, 0x00, 0x00, \
			0x00, 0x00, 0x00, 0x00, \
			0x00, 0x00, 0x00, 0x00, \
			0x00, 0x00, 0xdc, 0xba])
	eq("::abcd:dcba", \
		`std.Some `std.Ipv6 [ \
			0x00, 0x00, 0x00, 0x00, \
			0x00, 0x00, 0x00, 0x00, \
			0x00, 0x00, 0x00, 0x00, \
			0xab, 0xcd, 0xdc, 0xba])
	eq("::", `std.Some `std.Ipv6 [ \
			0x00, 0x00, 0x00, 0x00, \
			0x00, 0x00, 0x00, 0x00, \
			0x00, 0x00, 0x00, 0x00, \
			0x00, 0x00, 0x00, 0x00])

	/* invalid ipv4 addresses */
	eq("2a03:2880:2110:df07:face:b00c:0:1:abc", `std.None)	/* too long */
	eq("2a03:2880:2110:df07:face:b00c:0", `std.None)	/* too short */
	eq("2a03:2880:2110:df07:face:b00c:0:1:", `std.None)	/* trailing ':' */
}

const eq = {ip, expected
	var parsed
	var p, e

	parsed = std.ipparse(ip)
	p = ipbytes(parsed)
	e = ipbytes(expected)
	if !std.eq(p, e)
		std.fput(1, "misparsed ip {}\n", ip)
		std.put("parsed: ")
		for b : p
			std.put("{x}, ", b)
		;;
		std.put("\nexpected: ")
		for b : e
			std.put("{x}, ", b)
		;;
		std.put("\n")
		std.fatal("failed\n")
	;;
}

const ipbytes = {ipopt
	match ipopt
	| `std.Some ip:
		match ip
		| `std.Ipv4 b:	-> b[:]
		| `std.Ipv6 b:	-> b[:]
		;;
	| `std.None:	-> [][:]
	;;
	-> [][:]
}