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