factor/extra/base85/base85.factor

79 lines
2.0 KiB
Factor
Raw Normal View History

! Copyright (C) 2013 John Benediktsson.
! See http://factorcode.org/license.txt for BSD license.
2019-04-05 16:03:19 -04:00
USING: base64.private byte-arrays combinators io io.binary
io.encodings.binary io.streams.byte-array kernel kernel.private
literals math namespaces sequences ;
IN: base85
ERROR: malformed-base85 ;
<PRIVATE
2015-07-15 23:04:19 -04:00
<<
2019-04-05 16:03:19 -04:00
CONSTANT: alphabet $[
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"
2019-04-05 16:03:19 -04:00
>byte-array
]
2015-07-15 23:04:19 -04:00
>>
2019-04-05 16:03:19 -04:00
: ch>base85 ( ch -- ch )
alphabet nth ; inline
: base85>ch ( ch -- ch )
$[ alphabet alphabet-inverse ] nth
[ malformed-base85 ] unless* { fixnum } declare ; inline
2015-07-16 01:34:15 -04:00
: encode4 ( seq -- seq' )
be> 5 [ 85 /mod ch>base85 ] B{ } replicate-as reverse! nip ; inline
2015-07-16 10:31:09 -04:00
: (encode-base85) ( stream column -- )
2015-07-16 01:34:15 -04:00
4 pick stream-read dup length {
2015-07-16 10:31:09 -04:00
{ 0 [ 3drop ] }
2015-07-16 01:34:15 -04:00
{ 4 [ encode4 write-lines (encode-base85) ] }
[
drop
[ 4 0 pad-tail encode4 ]
2019-01-26 10:14:09 -05:00
[ length 4 swap - head-slice* write-lines ] bi
(encode-base85)
]
} case ;
PRIVATE>
: encode-base85 ( -- )
2015-07-16 10:31:09 -04:00
input-stream get f (encode-base85) ;
: encode-base85-lines ( -- )
2015-07-16 10:31:09 -04:00
input-stream get 0 (encode-base85) ;
<PRIVATE
: decode5 ( seq -- seq' )
0 [ [ 85 * ] [ base85>ch ] bi* + ] reduce 4 >be ; inline
: (decode-base85) ( stream -- )
5 "\n\r" pick read-ignoring dup length {
{ 0 [ 2drop ] }
{ 5 [ decode5 write (decode-base85) ] }
[
drop
[ 5 CHAR: ~ pad-tail decode5 ]
2019-01-26 10:14:09 -05:00
[ length 5 swap - head-slice* write ] bi
(decode-base85)
]
} case ;
PRIVATE>
: decode-base85 ( -- )
input-stream get (decode-base85) ;
: >base85 ( seq -- base85 )
binary [ binary [ encode-base85 ] with-byte-reader ] with-byte-writer ;
: base85> ( base85 -- seq )
binary [ binary [ decode-base85 ] with-byte-reader ] with-byte-writer ;
: >base85-lines ( seq -- base85 )
binary [ binary [ encode-base85-lines ] with-byte-reader ] with-byte-writer ;