--!strict --!native -- codecs/Base64: RFC 4648 base64 (standard alphabet, and base64url with opts.url) encode / decode, for data: URIs -- (glTF, SVG, CSS), PEM-like text, YAML !!binary, ... New code. decode skips whitespace, accepts missing padding and -- both alphabets; any other character is an error. Never throws. -- -- local Base64 = require("@formats/codecs/Base64") -- local s = Base64.encode(buf) -- string ("" for an empty buffer) -- local b, err = Base64.decode(s) -- buffer | nil, "message" -- local b2 = Base64.decodeDataUri("data:application/octet-stream;base64,AAEC") -- buffer, mime | nil, message local Base64 = {} local ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" local ALPHA_URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" local ENC = buffer.fromstring(ALPHA) local ENC_URL = buffer.fromstring(ALPHA_URL) -- the decode table: 0..63, 64 = skip (whitespace), 65 = padding, 255 = bad local DEC = buffer.create(256) buffer.fill(DEC, 0, 255) for i = 1, 64 do buffer.writeu8(DEC, string.byte(ALPHA, i), i - 1) end buffer.writeu8(DEC, string.byte("-"), 62) buffer.writeu8(DEC, string.byte("_"), 63) for _, c in { 9, 10, 13, 32 } do buffer.writeu8(DEC, c, 64) end buffer.writeu8(DEC, string.byte("="), 65) local readu8, writeu8 = buffer.readu8, buffer.writeu8 -- encode(buf, opts?, offset?, length?) -> string. opts.url: the URL-safe alphabet; opts.pad = false: no "=" padding. function Base64.encode(buf: buffer, opts: { url: boolean?, pad: boolean? }?, offset: number?, length: number?): string local o = math.clamp(offset or 0, 0, buffer.len(buf)) local n = math.clamp(length or (buffer.len(buf) - o), 0, buffer.len(buf) - o) local enc = if opts and opts.url then ENC_URL else ENC local pad = not (opts and opts.pad == false) local full = n // 3 local rest = n - full * 3 local outLen = full * 4 + (if rest == 0 then 0 elseif pad then 4 else rest + 1) local out = buffer.create(outLen) local p = 0 for i = 0, full - 1 do local q = o + i * 3 local v = readu8(buf, q) * 65536 + readu8(buf, q + 1) * 256 + readu8(buf, q + 2) writeu8(out, p, readu8(enc, v // 262144)) writeu8(out, p + 1, readu8(enc, (v // 4096) % 64)) writeu8(out, p + 2, readu8(enc, (v // 64) % 64)) writeu8(out, p + 3, readu8(enc, v % 64)) p += 4 end if rest > 0 then local q = o + full * 3 local v = readu8(buf, q) * 65536 + (if rest == 2 then readu8(buf, q + 1) * 256 else 0) writeu8(out, p, readu8(enc, v // 262144)) writeu8(out, p + 1, readu8(enc, (v // 4096) % 64)) if rest == 2 then writeu8(out, p + 2, readu8(enc, (v // 64) % 64)) elseif pad then writeu8(out, p + 2, 61) end if pad then writeu8(out, p + 3, 61) end end return buffer.tostring(out) end -- decode(s) -> buffer | nil, message function Base64.decode(s: string | buffer): (buffer?, string?) local src = if type(s) == "string" then buffer.fromstring(s) else s local n = buffer.len(src) local out = buffer.create((n // 4 + 1) * 3) local acc, bits, p = 0, 0, 0 local padded = false for i = 0, n - 1 do local d = readu8(DEC, readu8(src, i)) if d < 64 then if padded then return nil, "data after padding" end acc = acc * 64 + d bits += 6 if bits >= 8 then bits -= 8 local byte = acc // (2 ^ bits) writeu8(out, p, byte % 256) p += 1 acc = acc % (2 ^ bits) end elseif d == 65 then padded = true elseif d ~= 64 then return nil, string.format("bad base64 character 0x%02x at %d", readu8(src, i), i) end end if bits >= 6 then return nil, "truncated base64 (a single character in the last group)" end local res = buffer.create(p) buffer.copy(res, 0, out, 0, p) return res, nil end -- decodeDataUri(uri) -> buffer, mime | nil, message: "data:[][;params][;base64]," (percent-encoded data -- when not base64) function Base64.decodeDataUri(uri: string): (buffer?, string?) if string.sub(uri, 1, 5) ~= "data:" then return nil, "not a data: URI" end local comma = string.find(uri, ",", 6, true) if not comma then return nil, "data: URI without a comma" end local head = string.sub(uri, 6, comma - 1) local isB64 = string.sub(head, -7) == ";base64" local mime = string.match(head, "^([^;]*)") or "" if mime == "" then mime = "text/plain" end local body = string.sub(uri, comma + 1) if isB64 then local b, err = Base64.decode(body) if not b then return nil, err end return b, mime end local decoded = string.gsub(body, "%%(%x%x)", function(h: string): string return string.char(tonumber(h, 16) :: number) end) return buffer.fromstring(decoded), mime end -- dataUri(buf, mime) -> "data:;base64,..." function Base64.dataUri(buf: buffer, mime: string?): string return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf) end return Base64