rev: b5263db721ebca6ff9509f69a7255c55f9c956e4 tukan/lib/tukan/baseN.sc -rw-r--r-- 1.4 KiB View raw Log this file
b5263db721eb — Leonard Ritter * initial work on base encoding 29 days ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# base58 encoding

using import String
using import itertools

let BASE16-TABLE = "0123456789abcdef"
assert ((countof BASE16-TABLE) == 16)

let BASE64-TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
assert ((countof BASE64-TABLE) == 64)

inline gen-encoder (table tablesize bitstype readN writeN)
    fn... base-encode (data : rawstring, datasize : usize)
        local result : String
        loop (i = datasize)
            if (i == 0)
                break;
            i := i - 1
            # read
            let nexti = (max 0:usize (i - readN))
            let bits = 
                loop (i bits = i (nullof bitstype))
                    if (i == nexti)
                        break bits
                    print "r"
                    ch := (data @ i) as bitstype
                    _ (i - 1) (bits + (ch << ((i - nexti + 1) * 8) as bitstype) as bitstype)
            # write
            fold (bits = bits) for k in (range writeN)
                let bits ch =
                    bits // tablesize
                    bits % tablesize
                print "w"
                'append result
                    table @ ch
                bits
            nexti
        result

let base64-encode = (gen-encoder BASE64-TABLE 64 i32 3 4)

if main-module?
    let s = "any carnal pleasure."
    #let s = "Man" # TFWu
    print
        base64-encode (s as rawstring) (countof s)  

    #YW55IGNhcm5hbCBwbGVhc3VyZS4=

;