1 ! Copyright (C) 2013 John Benediktsson.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: base64.private byte-arrays combinators endian io
4 io.encodings.binary io.streams.byte-array kernel kernel.private
5 literals math namespaces sequences ;
8 ERROR: malformed-base85 ;
14 "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"
19 : ch>base85 ( ch -- ch )
22 : base85>ch ( ch -- ch )
23 $[ alphabet alphabet-inverse ] nth
24 [ malformed-base85 ] unless* { fixnum } declare ; inline
26 : encode4 ( seq -- seq' )
27 be> 5 [ 85 /mod ch>base85 ] B{ } replicate-as reverse! nip ; inline
29 : (encode-base85) ( stream column -- )
30 4 pick stream-read dup length {
32 { 4 [ encode4 write-lines (encode-base85) ] }
35 [ 4 0 pad-tail encode4 ]
36 [ length 4 swap - head-slice* write-lines ] bi
43 : encode-base85 ( -- )
44 input-stream get f (encode-base85) ;
46 : encode-base85-lines ( -- )
47 input-stream get 0 (encode-base85) ;
51 : decode5 ( seq -- seq' )
52 0 [ [ 85 * ] [ base85>ch ] bi* + ] reduce 4 >be ; inline
54 : (decode-base85) ( stream -- )
55 5 "\n\r" pick read-ignoring dup length {
57 { 5 [ decode5 write (decode-base85) ] }
60 [ 5 CHAR: ~ pad-tail decode5 ]
61 [ length 5 swap - head-slice* write ] bi
68 : decode-base85 ( -- )
69 input-stream get (decode-base85) ;
71 : >base85 ( seq -- base85 )
72 binary [ binary [ encode-base85 ] with-byte-reader ] with-byte-writer ;
74 : base85> ( base85 -- seq )
75 binary [ binary [ decode-base85 ] with-byte-reader ] with-byte-writer ;
77 : >base85-lines ( seq -- base85 )
78 binary [ binary [ encode-base85-lines ] with-byte-reader ] with-byte-writer ;