1 ! Copyright (C) 2019 John Benediktsson.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: base64.private byte-arrays combinators io
4 io.encodings.binary io.streams.byte-array kernel kernel.private
5 literals math namespaces sequences ;
8 ERROR: malformed-base16 ;
10 ! XXX: Optional handle lower-case input
15 CONSTANT: alphabet $[ "0123456789ABCDEF" >byte-array ]
18 : ch>base16 ( ch -- ch )
21 : base16>ch ( ch -- ch )
22 $[ alphabet alphabet-inverse ] nth
23 [ malformed-base16 ] unless* { fixnum } declare ; inline
25 :: (encode-base16) ( stream -- )
27 16 /mod [ ch>base16 write1 ] bi@
28 stream (encode-base16)
33 : encode-base16 ( -- )
34 input-stream get (encode-base16) ;
38 : decode2 ( seq -- n )
39 first2 [ base16>ch ] bi@ [ 16 * ] [ + ] bi* ;
41 :: (decode-base16) ( stream -- )
42 2 stream stream-read dup length {
44 { 2 [ decode2 write1 stream (decode-base16) ] }
50 : decode-base16 ( -- )
51 input-stream get (decode-base16) ;
53 : >base16 ( seq -- base16 )
54 binary [ binary [ encode-base16 ] with-byte-reader ] with-byte-writer ;
56 : base16> ( base16 -- seq )
57 binary [ binary [ decode-base16 ] with-byte-reader ] with-byte-writer ;