ws-cleanup: shared plumbing: Err.from, core/Sniff, Pcm.drain, Bits.msbPut; DUP lint; tools/move.py

- core/Err.from(message, offset?, kind?): the private-submodule -> Err plumbing (a kind, or a 'code: ' prefix /
  'truncated' / 'past the end' in the message) that Brotli, Bzip2, Zstd, Jpeg, WOFF2, FBX, plist, msgpack and
  bmfont each wrote.
- core/Sniff (new): Sniff.text(r, n, trim?) (the start of a text file without its BOM), Sniff.dropBom(s),
  Sniff.magic(r, s); 13 text formats' sniff / decode BOM handling goes through it.
- codecs/Pcm.drain(dec, source?, maxFrames?): a format's decode() through its open(); the collect-the-Decoder
  loops of aac, aiff, au, caf, flac, m4a, mp3, opus, vorbis and wav are one call each.
- core/Bits.msbPut: the MSB-first bit writer the MP3 / MP2 / FLAC encoders each copied.
- tools/lint_rules.py DUP: a function body of 12+ code lines repeated token for token in another module fails.
- tools/move.py: moves a module and rewrites every reference (requires, deps, headers, fixture INPUTS, docs).
- tools/fixtures/zstd.py: the incompressible corpus is smaller (zstd.luau 15.1 -> 13.4 MB; every fixture module is
  now under 14.3 MB).
- tools/bench.luau: MPEG-1 also runs with the api's LuaJIT trace limits; the sections that compare tuned / default
  limits set them explicitly (jitTune), so the order of sections no longer leaks the tuning.
This commit is contained in:
4DBug committed 2026-10-31 12:00:59 -05:00
1 parent 3243404374
commit 763f4a7c04
44 files changed
+374 -370

No files matched your search

+40 -13
View File
@@ -22,6 +22,19 @@ local Types = require("@formats/Types")
local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau"
-- jitTune(on): LuaJIT's trace limits as host/init.luau sets them for the api (on) or LuaJIT's defaults (off); the
-- codec sections that care print both
local function jitTune(on: boolean)
local jit = (_G :: any).jit
if jit and type(jit.opt) == "table" then
if on then
jit.opt.start("maxtrace=8000", "maxmcode=65536")
else
jit.opt.start("maxtrace=1000", "maxmcode=8192")
end
end
end
local function bench(label: string, n: number, bytes: number, f: () -> ())
f()
local dt = math.huge -- best of n: the machine is shared, the mean is noisy
@@ -935,19 +948,29 @@ do
Jpeg.encode(img, { quality = 85 })
end)
end
for _, s in M1 do
local file = Base64.decode(s.file) :: buffer
for _, rgba in { false, true } do
fps(string.format("mpeg1 decode %s %dx%d", if rgba then "rgba" else "yuv", s.width, s.height), 3, #s.units, function()
local dec = Mpeg1.new({ reorder = true, rgba = rgba })
for i, u in s.units do
dec:decode(file, u[1], u[2], i)
end
while dec:flush() do
end
end)
-- (LuaJIT also with the trace limits the api sets, host/init.luau: the default 1000 traces thrash on MPEG-1)
local function mpeg1(tag: string)
for _, s in M1 do
local file = Base64.decode(s.file) :: buffer
for _, rgba in { false, true } do
fps(string.format("mpeg1 decode %s %dx%d%s", if rgba then "rgba" else "yuv", s.width, s.height, tag), 3, #s.units, function()
local dec = Mpeg1.new({ reorder = true, rgba = rgba })
for i, u in s.units do
dec:decode(file, u[1], u[2], i)
end
while dec:flush() do
end
end)
end
end
end
jitTune(false)
mpeg1("")
if runtime == "luajit" then
jitTune(true)
mpeg1(" (jit tuned)")
jitTune(false)
end
end
-- ------------------------------------------------------------------------------------------- ws-video: containers
do
@@ -1024,10 +1047,12 @@ do
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #frames .. " frames)", #frames / dt))
end
end
jitTune(false)
run("")
if runtime == "luajit" then
require("@formats/host")
jitTune(true)
run(" (jit tuned)")
jitTune(false)
end
end
do
@@ -1045,9 +1070,11 @@ do
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #c.frames .. " frames)", #c.frames / dt))
end
end
jitTune(false)
run("")
if runtime == "luajit" then
require("@formats/host")
jitTune(true)
run(" (jit tuned)")
jitTune(false)
end
end
+1 -1
View File
@@ -42,7 +42,7 @@ def generate(ctx):
"one": b"a",
"short": b"hello, hello, hello zstd world\n",
"text": text[:200000],
"random": rng.randbytes(50000),
"random": rng.randbytes(16000), # incompressible: kept small (each case stores it again)
"runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300,
"far": (lambda r: r + rng.randbytes(30000) + r)(rng.randbytes(20000)),
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(60000)),
+31
View File
@@ -16,6 +16,9 @@
# extensions, mime, deps, caps (with decode / encode matching the functions), function <X>.sniff, at least
# one of decode / encode / open, the section markers in order, and ends with return <X>; it has a test
# tests/<category>/<fmt>.luau with a fuzz pass (:fuzz().
# DUP no copy-pasted code: a function body of DUP_LINES (12) or more code lines whose tokens (comments and
# whitespace dropped, identifiers kept) equal another module's function body fails; move it down to a
# shared module (core / codecs / containers) and call it from both.
import os, re, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
@@ -275,5 +278,33 @@ for folder in folders:
elif ":fuzz(" not in open(test).read():
bad(test, 0, "CONTRACT: a format test includes the fuzz no-throw pass (t:fuzz(...))")
# ---------------------------------------------------------------------------------------------------- DUP
DUP_LINES = 12
TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|\[=*\[.*?\]=*\]|[A-Za-z_][A-Za-z0-9_]*|\d[\w.]*|\S')
FUNC = re.compile(r"^(\s*)(?:local\s+)?function\b")
bodies = {}
for f, lines in text.items():
for i, line in enumerate(lines):
m = FUNC.match(line)
if not m:
continue
end = re.compile("^" + re.escape(m.group(1)) + r"end\b")
j = i + 1
while j < len(lines) and not end.match(lines[j]):
j += 1
body = [code(x).strip() for x in lines[i + 1:j]]
body = [x for x in body if x]
if len(body) < DUP_LINES:
continue
key = " ".join(TOKEN.findall(" ".join(body)))
bodies.setdefault(key, []).append((f, i + 1, line.strip()))
for key, where in bodies.items():
files_ = {w[0] for w in where}
if len(files_) > 1:
first = where[0]
for f, ln, head in where[1:]:
if f != first[0]:
bad(f, ln, "DUP: `%s` repeats %s:%d (move it to a shared module)" % (head[:60], os.path.relpath(first[0], ROOT), first[1]))
print("\n".join(out))
sys.exit(1 if out else 0)
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
# Module moves (python3 -I tools/move.py [--dry] old=new ...): moves src/Formats/<old>(.luau | /) to <new> with
# git mv, then rewrites every reference to the module path in the repo: requires ("@formats/old" and
# "@formats/old/Sub"), contract deps ("old"), header comment lines ("-- old: ..." / "-- old/Sub: ..."), fixture
# INPUTS ("src/Formats/old"), docs and comments ("old" as a whole path token). Paths are module paths
# (codecs/Deflate, core/Huffman). Generated files are not edited: rerun tools/gen_registry.py afterwards.
#
# python3 -I tools/move.py codecs/Deflate=codecs/compress/Deflate core/Huffman=codecs/entropy/Huffman
import os, re, subprocess, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "src", "Formats")
SCAN = ["src", "tests", "tools", "docs", "examples", "README.md", "default.project.json"]
SKIP = {os.path.join("tests", "gen"), os.path.join("tools", "move.py"), "build"}
EXTS = (".luau", ".lua", ".py", ".md", ".json", ".sh")
def files():
for top in SCAN:
p = os.path.join(ROOT, top)
if os.path.isfile(p):
yield p
continue
for d, dirs, fs in os.walk(p):
rel = os.path.relpath(d, ROOT)
dirs[:] = [x for x in dirs if os.path.join(rel, x) not in SKIP and x not in ("build", "__pycache__")]
for f in fs:
q = os.path.join(d, f)
if f.endswith(EXTS) and os.path.relpath(q, ROOT) not in SKIP:
yield q
def source(mod):
base = os.path.join(SRC, *mod.split("/"))
if os.path.isdir(base):
return base
if os.path.isfile(base + ".luau"):
return base + ".luau"
return None
def main():
dry = "--dry" in sys.argv
pairs = [a.split("=", 1) for a in sys.argv[1:] if "=" in a]
if not pairs:
print(__doc__ if __doc__ else "usage: move.py old=new ...")
sys.exit(2)
for old, new in pairs:
src = source(old)
if not src:
sys.exit("move.py: no module %s" % old)
dst = os.path.join(SRC, *new.split("/")) + ("" if os.path.isdir(src) else ".luau")
if os.path.exists(dst):
sys.exit("move.py: %s exists" % os.path.relpath(dst, ROOT))
print("move %s -> %s" % (os.path.relpath(src, ROOT), os.path.relpath(dst, ROOT)))
if not dry:
os.makedirs(os.path.dirname(dst), exist_ok=True)
subprocess.run(["git", "mv", src, dst], cwd=ROOT, check=True)
# a path token: not preceded by a word char or "."; not followed by a word char
subs = [(re.compile(r"(?<![\w.])" + re.escape(old) + r"(?![\w])"), new) for old, new in pairs]
lua_subs = [(re.compile(r"(?<![\w.])formats\." + re.escape(old.replace("/", ".")) + r"(?![\w])"),
"formats." + new.replace("/", ".")) for old, new in pairs]
changed = 0
for f in files():
with open(f, encoding="utf-8", errors="surrogateescape") as h:
text = h.read()
out = text
for rx, rep in subs + lua_subs:
out = rx.sub(rep, out)
if out != text:
changed += 1
if not dry:
with open(f, "w", encoding="utf-8", errors="surrogateescape") as h:
h.write(out)
print("move.py: %d files rewritten%s" % (changed, " (dry run)" if dry else ""))
if __name__ == "__main__":
main()