]> gitweb.factorcode.org Git - factor.git/commitdiff
ip-parser: adding ipv6-aton and ipv6-ntoa
authorJohn Benediktsson <mrjbq7@gmail.com>
Tue, 7 Feb 2023 17:11:32 +0000 (09:11 -0800)
committerJohn Benediktsson <mrjbq7@gmail.com>
Tue, 7 Feb 2023 17:11:32 +0000 (09:11 -0800)
basis/ip-parser/ip-parser-tests.factor
basis/ip-parser/ip-parser.factor

index cf12220fa8ec28614dbbfbcbf0db8d0c020b6f9c..4944df289d7137a1737568422d6ed438b154d854 100644 (file)
@@ -32,3 +32,10 @@ USING: ip-parser kernel sequences tools.test ;
         "2001:db8::ff00:42:8329"
     } [ parse-ipv6 { 8193 3512 0 0 0 65280 66 33577 } = ] all?
 ] unit-test
+
+{ 1 } [ "::1" ipv6-aton ] unit-test
+{ "::1" } [ 1 ipv6-ntoa ] unit-test
+{ 0x10000000000000000000000000000 } [ "1::" ipv6-aton ] unit-test
+{ "1::" } [ 0x10000000000000000000000000000 ipv6-ntoa ] unit-test
+{ 0x10002000000000000000000030004 } [ "1:2::3:4" ipv6-aton ] unit-test
+{ "1:2::3:4" } [ 0x10002000000000000000000030004 ipv6-ntoa ] unit-test
index d7d8e68ef58a3f01bb3bcebaf46783ee3b456775..5e6398d0ac4f675aa9fda0d926bbbf3443d7e03b 100644 (file)
@@ -1,12 +1,16 @@
 ! Copyright (C) 2012-2014 John Benediktsson
 ! See https://factorcode.org/license.txt for BSD license
-USING: byte-arrays combinators combinators.short-circuit kernel
-math math.bitwise math.parser sequences splitting ;
+
+USING: arrays byte-arrays combinators combinators.short-circuit
+endian grouping kernel math math.bitwise math.parser regexp
+sequences splitting ;
 
 IN: ip-parser
 
 ERROR: malformed-ipv4 string ;
 
+ERROR: malformed-ipv6 string ;
+
 ERROR: bad-ipv4-component string ;
 
 <PRIVATE
@@ -75,3 +79,11 @@ PRIVATE>
 
 : parse-ipv6 ( string -- seq )
     "::" split1 [ [ f ] [ split-ipv6 ] if-empty ] bi@ pad-ipv6 ;
+
+: ipv6-ntoa ( integer -- ip )
+    16 >be bytes>hex-string 4 <groups>
+    [ [ CHAR: 0 = ] trim-head ] map ":" join
+    R/ [:][:]+/ "::" re-replace ;
+
+: ipv6-aton ( ip -- integer )
+    parse-ipv6 0 [ [ 16 shift ] [ + ] bi* ] reduce ;