]> gitweb.factorcode.org Git - factor.git/commitdiff
pack: support numbered format strings.
authorJohn Benediktsson <mrjbq7@gmail.com>
Mon, 24 Feb 2014 19:23:13 +0000 (11:23 -0800)
committerJohn Benediktsson <mrjbq7@gmail.com>
Mon, 24 Feb 2014 19:23:13 +0000 (11:23 -0800)
basis/pack/pack-tests.factor
basis/pack/pack.factor

index 440d6a03693859ab620d79bd3d6b788561425ccf..b9137f77fc6f621044499c46b50adab2ca453fcc 100644 (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
index a330337c5e992b391eeb30e7233d5806714d0b1b..5f153737905b7e2f9b07b91a40fd76802ce66298 100644 (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