Files
rosetta/src/Formats/data/plist/Base64.luau
T

72 lines
1.9 KiB
Luau

--!strict
--!native
-- data/plist/Base64: RFC 4648 base64 for plist <data> (decode skips whitespace; encode wraps lines). Never throws.
local Base64 = {}
local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
local DEC: { [number]: number } = {}
for i = 1, 64 do
DEC[string.byte(ALPHA, i)] = i - 1
end
local ENC: { string } = {}
for i = 1, 64 do
ENC[i - 1] = string.sub(ALPHA, i, i)
end
-- decode(s) -> buffer | nil, message (whitespace ignored; padding optional)
function Base64.decode(s: string): (buffer?, string?)
local clean = string.gsub(s, "[ \t\r\n]", "")
clean = string.gsub(clean, "=+$", "")
local n = #clean
if n % 4 == 1 then
return nil, "bad base64 length"
end
local out = buffer.create(n * 3 // 4)
local o = 0
local acc, bits = 0, 0
for i = 1, n do
local v = DEC[string.byte(clean, i)]
if v == nil then
return nil, "bad base64 character"
end
acc = acc * 64 + v
bits += 6
if bits >= 8 then
bits -= 8
local b = acc // (2 ^ bits)
buffer.writeu8(out, o, b)
o += 1
acc -= b * 2 ^ bits
end
end
return out, nil
end
-- encode(b, lineBytes?) -> base64 text; lineBytes > 0 puts "\n" after every lineBytes input bytes (and at the end)
function Base64.encode(b: buffer, lineBytes: number?): string
local n = buffer.len(b)
local parts = table.create(n // 3 + 2)
local per = lineBytes or 0
local k = 0
local i = 0
while i < n do
local a = buffer.readu8(b, i)
local c1 = if i + 1 < n then buffer.readu8(b, i + 1) else 0
local c2 = if i + 2 < n then buffer.readu8(b, i + 2) else 0
local v = a * 65536 + c1 * 256 + c2
local q = ENC[v // 262144] .. ENC[(v // 4096) % 64]
q ..= if i + 1 < n then ENC[(v // 64) % 64] else "="
q ..= if i + 2 < n then ENC[v % 64] else "="
k += 1
parts[k] = q
i += 3
if per > 0 and (i % per == 0 or i >= n) then
k += 1
parts[k] = "\n"
end
end
return table.concat(parts)
end
return Base64