 ! Copyright (C) 2008 Doug Coleman, Daniel Ehrenberg.
 ! See http://factorcode.org/license.txt for BSD license.
-USING: combinators io io.binary io.encodings.binary
+USING: combinators fry io io.binary io.encodings.binary
 io.streams.byte-array kernel math namespaces
 sequences strings ;
 IN: base64


SYMBOL: column

: write1-lines ( ch -- )
    write1
    column get [
        1 + [ 76 = [ B{ CHAR: \r CHAR: \n } write ] when ]
        [ 76 mod column set ] bi
    ] when* ;

: write-lines ( str -- )
    [ write1-lines ] each ;

: encode3 ( seq -- )
    be> 4 iota <reversed> [
        -6 * shift 0x3f bitand ch>base64 write1-lines
    ] with each ; inline

: encode-pad ( seq n -- )
    [ 3 0 pad-tail binary [ encode3 ] with-byte-writer ]


<PRIVATE

: read1-ignoring ( ignoring stream -- ch )
    dup stream-read1 pick dupd member?
    [ drop read1-ignoring ] [ 2nip ] if ;

: read-ignoring ( n ignoring stream -- str )
    '[ _ _ read1-ignoring ] replicate
    [ { f 0 } member-eq? not ] "" filter-as
    [ f ] when-empty ;

: ch>base64 ( ch -- ch )
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
