]> git.lizzy.rs Git - hydra-dragonfire.git/blob - builtin/base64.lua
Add map component
[hydra-dragonfire.git] / builtin / base64.lua
1 --[[ builtin/base64.lua ]]--
2
3 -- Taken from: http://lua-users.org/wiki/BaseSixtyFour with minor modifications
4
5 -- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de>
6 -- licensed under the terms of the LGPL2
7
8 local base64 = {}
9 package.loaded.base64 = base64
10
11 -- character table string
12 local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
13
14 -- encoding
15 function base64.encode(data)
16     return ((data:gsub('.', function(x)
17         local r,b='',x:byte()
18         for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end
19         return r;
20     end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x)
21         if (#x < 6) then return '' end
22         local c=0
23         for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end
24         return b:sub(c+1,c+1)
25     end)..({ '', '==', '=' })[#data%3+1])
26 end
27
28 -- decoding
29 function base64.decode(data)
30     data = string.gsub(data, '[^'..b..'=]', '')
31     return (data:gsub('.', function(x)
32         if (x == '=') then return '' end
33         local r,f='',(b:find(x)-1)
34         for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
35         return r;
36     end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
37         if (#x ~= 8) then return '' end
38         local c=0
39         for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
40         return string.char(c)
41     end))
42 end
43