shithub: mc

Download patch

ref: dabed9c4d7c7b367b08a4b2ede1b27f2d218052b
parent: 0022c21553124df1dc02948b4fc27bd3906e4d37
author: Ori Bernstein <[email protected]>
date: Tue Nov 12 11:45:27 EST 2013

Add IPv4 address parsing.

--- a/libstd/Makefile
+++ b/libstd/Makefile
@@ -11,7 +11,7 @@
     fmt.myr \
     hashfuncs.myr \
     htab.myr \
-    ipaddr.myr \
+    ipparse.myr \
     intparse.myr \
     now.myr \
     option.myr \
--- /dev/null
+++ b/libstd/ipparse.myr
@@ -1,0 +1,45 @@
+use "types.use"
+use "intparse.use"
+use "option.use"
+
+ /* FIXME: needed for decls which should be pulled in as hidden */
+use "strcmp.use"
+use "utf.use"
+use "fmt.use"
+
+pkg std =
+	const ip4parse	: (ip : byte[:] -> option(byte[4]))
+	const ip6parse	: (ip : byte[:] -> option(byte[16]))
+;;
+
+const ip4parse = {ip
+	var addr
+	var last : size
+	var x : option(int32)
+	var val : int32 /* need int32 to check for overflow */
+	var i
+	var j : size
+
+	i = 0
+	for j = 0; j < ip.len; j++
+		if ip[j] == '.' castto(byte)
+			put("seg[%z..%z] = %s\n", last, j, ip[last:j])
+			val = intparsebase(ip[last:j], 10)
+			if val < 0 || val > 255
+				-> `None
+			;;
+			addr[i++] = val castto(byte)
+			last = j + 1
+		;;
+	;;
+			put("seg[%z..%z] = %s\n", last, j, ip[last:j])
+	val = intparsebase(ip[last:j], 10)
+	if val < 0 || val > 255
+		-> `None
+	;;
+	addr[i] = val castto(byte)
+	if j != ip.len
+		-> `None
+	;;
+	-> `Some addr
+}