perf: F.detect: the extension's format scoring 1 returns at once (65x with a name), archive/br's trial-decode sniff runs last and only when it could still win; mpegts sniff finds sync bytes with string.find; inflate reuses its dynamic-table scratch buffers

This commit is contained in:
4DBug committed 2026-11-01 19:14:53 -06:00
1 parent 11b7f89dab
commit 3320339507
3 files changed
+70 -25

No files matched your search

+40 -4
View File
@@ -76,6 +76,8 @@ local function find(key: string, category: string?): Registry.Entry?
return nil
end
local LATE: { [string]: number } = { br = 0.3 } -- archive/br: a trial decode of up to 256 KB
local function detect(buf: buffer, name: string?, category: string?, format: string?): (Registry.Entry?, Err.Err?)
if format then
local e = find(format, category)
@@ -86,18 +88,52 @@ local function detect(buf: buffer, name: string?, category: string?, format: str
end
local ext = Input.extension(name)
local best: Registry.Entry? = nil
local bestScore = 0
for _, e in Registry do
local bestScore, bestIdx = 0, 0
-- sniffs score 0..1 (core/Sniff); the extension's format scoring 1 cannot be beaten. Formats with a costly sniff
-- (LATE: the most they score) run last, and only when they could still win; ties go to registry order.
local late: { number }? = nil
for idx, e in Registry do
if inCategory(e, category) and (e.caps.decode or e.caps.open) then
local cap = LATE[e.name]
if cap then
late = late or {}
table.insert(late :: { number }, idx)
continue
end
local m = module(e)
if m and m.sniff then
local ok, score = pcall(m.sniff, Bytes.reader(buf))
if ok and type(score) == "number" and score > 0 then
if ext and table.find(e.extensions, ext) then
local extHit = ext and table.find(e.extensions, ext)
if extHit then
score += 0.01 -- ties go to the extension
end
if score > bestScore then
best, bestScore = e, score
best, bestScore, bestIdx = e, score, idx
if extHit and score >= 1.01 then
return e, nil
end
end
end
end
end
end
if late then
for _, idx in late do
local e = Registry[idx]
local extHit = ext and table.find(e.extensions, ext)
local cap = LATE[e.name] + (if extHit then 0.01 else 0)
if cap > bestScore or (cap == bestScore and idx < bestIdx) then
local m = module(e)
if m and m.sniff then
local ok, score = pcall(m.sniff, Bytes.reader(buf))
if ok and type(score) == "number" and score > 0 then
if extHit then
score += 0.01
end
if score > bestScore or (score == bestScore and idx < bestIdx) then
best, bestScore, bestIdx = e, score, idx
end
end
end
end