lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, Nov 4, 2014 at 8:39 AM, Ico Doornekamp <lua@zevv.nl> wrote:
> local function base64(s)
>    local byte, rep = string.byte, string.rep
>    local pad = 2 - ((#s-1) % 3)
>    s = (s..rep('\0', pad)):gsub("...", function(cs)
>       local a, b, c = byte(cs, 1, 3)
>       return bs[a>>2] .. bs[(a&3)<<4|b>>4] .. bs[(b&15)<<2|c>>6] .. bs[c&63]
>    end)
>    return s:sub(1, #s-pad) .. rep('=', pad)
> end

You can avoid allocating 2 copies of s doing:

 local function base64(s)
    local byte = string.byte
    return s:gsub("..?.?", function(cs)
       local a, b, c = byte(cs, 1, 3)
       if not b then
         return bs[a>>2] .. bs[(a&3)<<4] .. "=="
       elseif not c then
         return bs[a>>2] .. bs[(a&3)<<4|b>>4] .. bs[(b&15)<<2] .. "="
       else
         return bs[a>>2] .. bs[(a&3)<<4|b>>4] .. bs[(b&15)<<2|c>>6] .. bs[c&63]
       end
    end)
 end

I suspect the if statements are faster than the padding gymnastics.

-- 
Patrick Donnelly