~rootmos/lua-hack

baf2c3f17e715fc2fc1eb8661b4ee97cd234fb80 — Gustav Behm 1 year, 6 months ago dd45c0d base64
Reorder cases
1 files changed, 21 insertions(+), 19 deletions(-)

M base64.lua
M base64.lua => base64.lua +21 -19
@@ 29,20 29,21 @@ for k, v in pairs(M.alphabeth) do
end

function M.encode(bs)
    local alph = M.alphabeth
    local i = 1
    local s = ""
    while i <= #bs do
        local a, b, c = bs:byte(i, i+2)
        s = s .. M.alphabeth[a>>2]
        if b ~= nil then
            s = s .. M.alphabeth[(a&3)<<4|b>>4]
            if c ~= nil then
                s = s .. M.alphabeth[(b&15)<<2|c>>6] .. M.alphabeth[c&63]
        s = s .. alph[a>>2]
        if b == nil then
            s = s .. alph[(a&3)<<4] .. alph.pad .. alph.pad
        else
            s = s .. alph[(a&3)<<4 | b>>4]
            if c == nil then
                s = s .. alph[(b&15)<<2] .. alph.pad
            else
                s = s .. M.alphabeth[(b&15)<<2] .. M.alphabeth.pad
                s = s .. alph[(b&15)<<2 | c>>6] .. alph[c&63]
            end
        else
             s = s .. M.alphabeth[(a&3)<<4] .. M.alphabeth.pad .. M.alphabeth.pad
        end
        i = i + 3
    end


@@ 53,22 54,23 @@ function M.decode(s)
    local i = 1
    local bs = ""
    local pad = M.alphabeth.pad:byte()
    local inv = M.alphabeth_inv
    while i <= #s do
        local a, b, c, d = s:byte(i, i+3)
        if b ~= pad then
            bs = bs .. string.char(M.alphabeth_inv[a]<<2 | M.alphabeth_inv[b]>>4)
            if c ~= pad then
                bs = bs .. string.char((M.alphabeth_inv[b]&15)<<4 | M.alphabeth_inv[c]>>2)
                if d ~= pad then
                    bs = bs .. string.char((M.alphabeth_inv[c]&3)<<6 | M.alphabeth_inv[d])
        if b == pad then
            bs = bs .. string.char(inv[a]<<2) .. "\0\0"
        else
            bs = bs .. string.char(inv[a]<<2 | inv[b]>>4)
            if c == pad then
                bs = bs .. string.char((inv[b]&15)<<4) .. "\0"
            else
                bs = bs .. string.char((inv[b]&15)<<4 | inv[c]>>2)
                if d == pad then
                    bs = bs .. string.char((inv[c]&3)<<6)
                else
                    bs = bs .. string.char((M.alphabeth_inv[c]&3)<<6)
                    bs = bs .. string.char((inv[c]&3)<<6 | inv[d])
                end
            else
                bs = bs .. string.char((M.alphabeth_inv[b]&15)<<4) .. "\0"
            end
        else
            bs = bs .. string.char(M.alphabeth_inv[a]<<2) .. "\0\0"
        end
        i = i + 4
    end