1 USING: kernel math sequences namespaces io strings hashtables ;
4 : count-end ( seq quot -- count )
5 >r [ length ] keep r> find-last drop dup -1 = [ 2drop 0 ] [ - 1- ] if ;
7 : ch>base64 ( ch -- ch )
8 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" nth ;
10 : base64>ch ( ch -- ch )
12 f f f f f f f f f f f f f f f f f f f f f f f f f f f f f f f f f
13 f f f f f f f f f f 62 f f f 63 52 53 54 55 56 57 58 59 60 61 f f
14 f 0 f f f 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
15 22 23 24 25 f f f f f f 26 27 28 29 30 31 32 33 34 35 36 37 38 39
16 40 41 42 43 44 45 46 47 48 49 50 51
19 : encode3 ( seq -- seq )
20 be> 4 [ 3 swap - -6 * shift HEX: 3f bitand ch>base64 ] map-with ;
22 : decode4 ( str -- str )
23 [ base64>ch ] map 0 [ swap 6 shift bitor ] reduce 3 >be ;
25 : >base64-rem ( str -- str )
26 [ 3 0 pad-right encode3 ] keep length 1+ head 4 CHAR: = pad-right ;
29 : >base64 ( str -- str )
30 #! cut string into two pieces, convert 3 bytes at a time
31 #! pad string with = when not enough bits
32 [ length dup 3 mod - ] keep cut swap
34 3 group [ encode3 % ] each
35 dup empty? [ drop ] [ >base64-rem % ] if
38 : base64> ( str -- str )
39 #! input length must be a mulitple of 4
41 [ 4 group [ decode4 % ] each ] keep [ CHAR: = = not ] count-end
42 ] SBUF" " make swap [ dup pop* ] times >string ;