pack: support numbered format strings.

db4
John Benediktsson 2014-02-24 11:23:13 -08:00
parent 1456e14a09
commit 77c122941d
2 changed files with 14 additions and 6 deletions

View File

@ -36,6 +36,9 @@ IN: pack.tests
"cstiq" [ pack-native ] keep unpack-native
] unit-test
{ B{ 1 2 3 4 5 0 0 0 } } [ { 1 2 3 4 5 } "4ci" pack-le ] unit-test
{ { 1 2 3 4 5 } } [ B{ 1 2 3 4 5 0 0 0 } "4ci" unpack-le ] unit-test
[ 9 ] [ "iic" packed-length ] unit-test
[ "iii" read-packed-le ] must-infer
[ "iii" read-packed-be ] must-infer

View File

@ -1,11 +1,7 @@
! Copyright (C) 2009 Doug Coleman.
! See http://factorcode.org/license.txt for BSD license.
USING: alien alien.c-types arrays assocs byte-arrays io
io.binary io.streams.string kernel math math.parser namespaces
make parser quotations sequences strings vectors
words macros math.functions math.bitwise fry generalizations
combinators.smart io.streams.byte-array io.encodings.binary
math.vectors combinators multiline endian ;
USING: alien.c-types ascii assocs combinators combinators.smart
endian fry io kernel macros math math.vectors sequences strings ;
IN: pack
GENERIC: >n-byte-array ( obj n -- byte-array )
@ -33,6 +29,13 @@ M: string >n-byte-array ( n string -- byte-array ) heap-size >n-byte-array ;
<PRIVATE
: expand-pack-format ( str -- str' )
f swap [
dup digit?
[ [ 0 or 10 * ] [ CHAR: 0 - ] bi* + f ]
[ [ 1 or ] [ <string> ] bi* f swap ] if
] { } map-as "" concat-as nip ; foldable
CONSTANT: pack-table
H{
{ CHAR: c s8>byte-array }
@ -90,6 +93,7 @@ CONSTANT: packed-length-table
PRIVATE>
MACRO: pack ( str -- quot )
expand-pack-format
[ pack-table at '[ _ execute ] ] { } map-as
'[ [ [ _ spread ] input<sequence ] B{ } append-outputs-as ] ;
@ -116,6 +120,7 @@ MACRO: pack ( str -- quot )
PRIVATE>
MACRO: unpack ( str -- quot )
expand-pack-format
[ [ ch>packed-length ] { } map-as start/end ]
[ [ unpack-table at '[ @ ] ] { } map-as ] bi
[ '[ [ _ _ ] dip <slice> @ ] ] 3map