]> gitweb.factorcode.org Git - factor.git/blob - extra/ip-parser/ip-parser.factor
change ERROR: words from throw-foo back to foo.
[factor.git] / extra / ip-parser / ip-parser.factor
1 ! Copyright (C) 2012-2014 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
3 USING: combinators combinators.short-circuit kernel math
4 math.bitwise math.parser math.vectors sequences splitting ;
5
6 IN: ip-parser
7
8 ERROR: invalid-ipv4 str ;
9
10 <PRIVATE
11
12 : cleanup-octal ( str -- str )
13     dup { [ "0" = not ] [ "0" head? ] [ "0x" head? not ] } 1&&
14     [ rest "0o" prepend ] when ;
15
16 : split-components ( str -- array )
17     "." split [ cleanup-octal string>number ] map ;
18
19 : bubble ( array -- newarray )
20     reverse 0 swap [ + 256 /mod ] map reverse nip ;
21
22 : join-components ( array -- str )
23     [ number>string ] map "." join ;
24
25 : (parse-ipv4) ( str -- array )
26     dup split-components dup length {
27         { 1 [ { 0 0 0 } prepend ] }
28         { 2 [ 1 cut { 0 0 } glue ] }
29         { 3 [ 2 cut { 0 } glue ] }
30         { 4 [ ] }
31         [ drop invalid-ipv4 ]
32     } case bubble nip ; inline
33
34 PRIVATE>
35
36 : parse-ipv4 ( str -- ip )
37     (parse-ipv4) join-components ;
38
39 : ipv4-ntoa ( integer -- ip )
40     { -24 -16 -8 0 } [ 8 shift-mod ] with map join-components ;
41
42 : ipv4-aton ( ip -- integer )
43     (parse-ipv4) { 24 16 8 0 } [ shift ] [ + ] 2map-reduce ;