ws-3d: codecs/Base64 (RFC 4648 standard + url, padding optional, whitespace-tolerant decode, data: URIs); shared: glTF data URIs now, YAML !!binary / Brotli's dictionary / SVG could use it instead of private copies
This commit is contained in:
1 parent
bc4cf2dd9d
commit
fb909438a5
3 files changed
+199
No files matched your search
@@ -0,0 +1,140 @@
|
||||
--!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:[<mime>][;params][;base64],<data>" (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:<mime>;base64,..."
|
||||
function Base64.dataUri(buf: buffer, mime: string?): string
|
||||
return "data:" .. (mime or "application/octet-stream") .. ";base64," .. Base64.encode(buf)
|
||||
end
|
||||
|
||||
return Base64
|
||||
@@ -0,0 +1,46 @@
|
||||
-- codecs/Base64 tests: encode / decode against Python's base64 (standard, URL-safe, unpadded) for every length 0..70
|
||||
-- and some large inputs, whitespace and missing padding on decode, data: URIs, bad input, and the fuzz no-throw pass.
|
||||
-- Fixtures: tools/fixtures/base64.py.
|
||||
local T = require("@tests/T")
|
||||
local Base64 = require("@formats/codecs/Base64")
|
||||
local Cases = require("@tests/gen/base64_cases")
|
||||
|
||||
local t = T.suite("base64")
|
||||
|
||||
for _, c in Cases do
|
||||
local b = buffer.fromstring(c.data)
|
||||
t:eq(Base64.encode(b), c.std, "encode " .. #c.data)
|
||||
t:eq(Base64.encode(b, { url = true }), c.url, "encode url " .. #c.data)
|
||||
t:eq(Base64.encode(b, { pad = false }), c.nopad, "encode unpadded " .. #c.data)
|
||||
for _, s in { c.std, c.url, c.nopad } do
|
||||
local d, err = Base64.decode(s)
|
||||
t:check(d and buffer.tostring(d) == c.data, "decode " .. #c.data .. ": " .. tostring(err))
|
||||
end
|
||||
-- with line breaks every 76 characters (MIME)
|
||||
local wrapped = string.gsub(c.std, "(" .. string.rep(".", 76) .. ")", "%1\r\n")
|
||||
local d = Base64.decode(wrapped)
|
||||
t:check(d and buffer.tostring(d) == c.data, "decode wrapped " .. #c.data)
|
||||
end
|
||||
-- a sub-range
|
||||
t:eq(Base64.encode(buffer.fromstring("xxhelloyy"), nil, 2, 5), "aGVsbG8=", "encode a range")
|
||||
-- data URIs
|
||||
local b, mime = Base64.decodeDataUri("data:application/gltf-buffer;base64,AAEC")
|
||||
t:check(b and buffer.len(b) == 3 and buffer.readu8(b, 2) == 2 and mime == "application/gltf-buffer", "data URI")
|
||||
local b2, m2 = Base64.decodeDataUri("data:,a%20b")
|
||||
t:check(b2 and buffer.tostring(b2) == "a b" and m2 == "text/plain", "percent-encoded data URI")
|
||||
t:eq(Base64.dataUri(buffer.fromstring("hi"), "text/plain"), "data:text/plain;base64,aGk=", "dataUri")
|
||||
-- bad input
|
||||
t:check(Base64.decode("ab$d") == nil, "bad character")
|
||||
t:check(Base64.decode("abcde") == nil, "a lone last character")
|
||||
t:check(Base64.decode("ab==cd") == nil, "data after padding")
|
||||
t:check(Base64.decodeDataUri("http://x") == nil, "not a data URI")
|
||||
local samples = {}
|
||||
for i, c in Cases do
|
||||
if i % 10 == 0 then
|
||||
table.insert(samples, c.std)
|
||||
end
|
||||
end
|
||||
t:fuzz("decode", function(x: buffer)
|
||||
return Base64.decode(x)
|
||||
end, samples)
|
||||
t:done()
|
||||
@@ -0,0 +1,13 @@
|
||||
# Base64 fixtures (tools/fixtures.py): random byte strings of every length 0..70 plus a few large ones, with Python's
|
||||
# base64 (standard, URL-safe, unpadded) as the reference.
|
||||
# tests/gen/base64_cases.luau { data, std, url, nopad }
|
||||
import base64
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
rng = ctx.rng(3)
|
||||
cases = []
|
||||
for n in list(range(71)) + [1000, 4097, 65536]:
|
||||
d = bytes(rng.randrange(256) for _ in range(n))
|
||||
cases.append({"data": d, "std": base64.b64encode(d), "url": base64.urlsafe_b64encode(d), "nopad": base64.b64encode(d).rstrip(b"=")})
|
||||
ctx.emit("base64_cases", cases)
|
||||
Reference in new issue
Block a user