ip-parser: faster ntoa and aton.

db4
John Benediktsson 2014-02-09 15:45:28 -08:00
parent ebbfa17b47
commit c69005a324
2 changed files with 25 additions and 20 deletions

View File

@ -22,5 +22,5 @@ IN: ip-parser
} [ parse-ipv4 "74.125.226.4" = ] all? } [ parse-ipv4 "74.125.226.4" = ] all?
] unit-test ] unit-test
{ "174.36.207.186" } [ 2921648058 ipv4-ntoa ] unit-test { "74.125.226.4" } [ 1249763844 ipv4-ntoa ] unit-test
{ 2921648058 } [ "174.36.207.186" ipv4-aton ] unit-test { 1249763844 } [ "74.125.226.4" ipv4-aton ] unit-test

View File

@ -1,9 +1,8 @@
! Copyright (C) 2012 John Benediktsson ! Copyright (C) 2012 John Benediktsson
! See http://factorcode.org/license.txt for BSD license ! See http://factorcode.org/license.txt for BSD license
USING: arrays combinators combinators.short-circuit
USING: combinators combinators.short-circuit formatting kernel generalizations kernel literals locals math math.bitwise
literals locals math math.bitwise math.parser sequences math.parser sequences sequences.private splitting ;
splitting ;
IN: ip-parser IN: ip-parser
@ -16,22 +15,28 @@ ERROR: invalid-ipv4 str ;
[ rest "0o" prepend ] when ; [ rest "0o" prepend ] when ;
: split-components ( str -- array ) : split-components ( str -- array )
"." split [ cleanup-octal string>number ] map ; "." split [ cleanup-octal string>number ] map! ;
: bubble ( array -- array' ) : byte>string ( byte -- str )
reverse 0 swap [ + 256 /mod ] map reverse nip ; $[ 256 iota [ number>string ] map ] nth-unsafe ; inline
: join-components ( array -- str ) : bubble1 ( m n -- x y )
[ number>string ] map "." join ; [ -8 shift + ] [ 8 bits ] bi ; inline
: (parse-ipv4) ( str -- array ) : bubble ( a b c d -- w x y z )
bubble1 [ bubble1 ] dip [ bubble1 ] 2dip [ 8 bits ] 3dip ; inline
: join-components ( a b c d -- str )
[ byte>string ] 4 napply 4array "." join ; inline
: (parse-ipv4) ( str -- a b c d )
dup split-components dup length { dup split-components dup length {
{ 1 [ { 0 0 0 } prepend ] } { 1 [ nip first-unsafe [ 0 0 0 ] dip ] }
{ 2 [ first2 [| A D | { A 0 0 D } ] call ] } { 2 [ nip first2-unsafe [ 0 0 ] dip ] }
{ 3 [ first3 [| A B D | { A B 0 D } ] call ] } { 3 [ nip first3-unsafe [ 0 ] dip ] }
{ 4 [ ] } { 4 [ nip first4-unsafe ] }
[ drop invalid-ipv4 ] [ drop invalid-ipv4 ]
} case bubble nip ; } case bubble ; inline
PRIVATE> PRIVATE>
@ -39,8 +44,8 @@ PRIVATE>
(parse-ipv4) join-components ; (parse-ipv4) join-components ;
: ipv4-ntoa ( integer -- ip ) : ipv4-ntoa ( integer -- ip )
$[ { -24 -16 -8 0 } [ [ shift 8 bits ] curry ] map ] $[ { -24 -16 -8 0 } [ [ 8 shift-mod ] curry ] map ] cleave
cleave "%s.%s.%s.%s" sprintf ; join-components ;
: ipv4-aton ( ip -- integer ) : ipv4-aton ( ip -- integer )
(parse-ipv4) B{ 24 16 8 0 } [ shift ] [ + ] 2map-reduce ; (parse-ipv4) [ 24 16 8 [ shift ] tri-curry@ tri* ] dip + + + ;