summaryrefslogtreecommitdiff
path: root/base64.lua
diff options
context:
space:
mode:
Diffstat (limited to 'base64.lua')
-rw-r--r--base64.lua38
1 files changed, 38 insertions, 0 deletions
diff --git a/base64.lua b/base64.lua
new file mode 100644
index 0000000..4f9a967
--- /dev/null
+++ b/base64.lua
@@ -0,0 +1,38 @@
+local alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+
+-- really bad
+local function encode(s)
+ local x = 0
+ local n = 0
+ local out = {}
+ local outn = 1
+ local pad = ""
+ local function si(v, m) x = (x << m) | v; n = n + m end
+ local function so(m)
+ local rem = n - m
+ local res = x >> rem
+ x = x & ((1 << rem) - 1)
+ n = n - m
+ return res
+ end
+ local function o()
+ while n >= 6 do
+ local i = so(6)+1
+ out[outn] = alphabet:sub(i,i)
+ outn = outn + 1
+ end
+ end
+ for i = 1, #s do
+ si(s:byte(i), 8)
+ o()
+ end
+ if n > 0 then
+ local on = n
+ si(0, 6-n)
+ o()
+ pad = ('='):rep(3-on/2) -- bad
+ end
+ return table.concat(out)..pad
+end
+
+return {encode=encode}