]> gitweb.factorcode.org Git - factor.git/blob - basis/base64/base64.factor
Create basis vocab root
[factor.git] / basis / base64 / base64.factor
1 USING: kernel math sequences io.binary splitting grouping ;
2 IN: base64
3
4 <PRIVATE
5
6 : count-end ( seq quot -- count )
7     >r [ length ] keep r> find-last drop dup [ - 1- ] [ 2drop 0 ] if ; inline
8
9 : ch>base64 ( ch -- ch )
10     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" nth ;
11
12 : base64>ch ( ch -- ch )
13     {
14         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
15         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
16         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
17         22 23 24 25 f f f f f f 26 27 28 29 30 31 32 33 34 35 36 37 38 39
18         40 41 42 43 44 45 46 47 48 49 50 51
19     } nth ;
20
21 : encode3 ( seq -- seq )
22     be> 4 <reversed> [ -6 * shift HEX: 3f bitand ch>base64 ] with B{ } map-as ;
23
24 : decode4 ( str -- str )
25     0 [ base64>ch swap 6 shift bitor ] reduce 3 >be ;
26
27 : >base64-rem ( str -- str )
28     [ 3 0 pad-right encode3 ] [ length 1+ ] bi head 4 CHAR: = pad-right ;
29
30 PRIVATE>
31
32 : >base64 ( seq -- base64 )
33     #! cut string into two pieces, convert 3 bytes at a time
34     #! pad string with = when not enough bits
35     dup length dup 3 mod - cut
36     [ 3 <groups> [ encode3 ] map concat ]
37     [ dup empty? [ drop "" ] [ >base64-rem ] if ]
38     bi* append ;
39
40 : base64> ( base64 -- str )
41     #! input length must be a multiple of 4
42     [ 4 <groups> [ decode4 ] map concat ]
43     [ [ CHAR: = = not ] count-end ]
44     bi head* ;