ws-arch2: codecs/compress/Lzh (lh1 / lh4-lh7 / lhx / lzs / lz5 / ARJ 4; ported from lhasa, ISC) + archive/lha (levels 0-3, extended headers, symlinks, DOS-name case, read; level-2 lh0 write); bench lines

This commit is contained in:
4DBug committed 2026-10-31 14:40:25 -05:00
1 parent 94d79313d4
commit 572cd42f8a
10 files changed
+1303

No files matched your search

+12
View File
@@ -650,6 +650,18 @@ local list: { Entry } = {
return require("@formats/archive/gzip")
end,
},
{
name = "lha",
category = "archive",
path = "archive/lha",
extensions = { "lzh", "lha", "lzs" },
mime = { "application/x-lzh-compressed" },
deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" },
caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } },
load = function()
return require("@formats/archive/lha")
end,
},
{
name = "macbinary",
category = "archive",
+451
View File
@@ -0,0 +1,451 @@
--!strict
-- archive/lha: LHA / LZH archives (and LArc .lzs) read into an Archive: header levels 0, 1, 2 and 3 with their
-- extended headers (file and directory names, Unix permissions / uid / gid / user and group names / mtime, MS-DOS
-- attributes, Windows timestamps, comments), methods lh0 / lz4 (stored), lhd (directory), lh1, lh4, lh5, lh6, lh7,
-- lhx, lzs and lz5 through codecs/compress/Lzh; every file's CRC-16 (ARC) is verified (Err.CHECKSUM) when read.
-- Unix LHA symlinks ("name|target") become link entries; all-capital names from MS-DOS-like systems read in lower
-- case (as lhasa and LHa do). Level 0 / 1 MS-DOS times are read as UTC. Writes header
-- level 2 archives with stored (lh0) data from any Archive. Written from the LHA header documentation (Haruyasu
-- Yoshizaki's LHa notes, lhasa's lha_file_header.c as a reference, ISC). Not supported: pm0 / pm1 / pm2 (PMarc),
-- compression when writing, multi-volume archives, self-extracting stubs (the archive must start at offset 0 or
-- at the first header found in the first 64 KB).
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Crc16 = require("@formats/core/Crc16")
local Lzh = require("@formats/codecs/compress/Lzh")
local Archive = require("@formats/containers/Archive")
-- ------------------------------------------------------------------------------------------------ contract
local Lha = {
name = "lha",
category = "archive",
extensions = { "lzh", "lha", "lzs" },
mime = { "application/x-lzh-compressed" },
deps = { "core/Err", "core/Bytes", "core/Crc16", "codecs/compress/Lzh", "containers/Archive" },
caps = { decode = true, encode = true, methods = { "lh0", "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "lz4", "lhd" } },
}
export type DecodeOptions = {
maxBytes: number?, -- refuse an entry larger than this (default 2^30)
maxEntries: number?, -- default 65536
}
export type EncodeOptions = {}
-- ------------------------------------------------------------------------------------------------ constants
local METHODS: { [string]: boolean } = {
["-lh0-"] = true, ["-lz4-"] = true, ["-lhd-"] = true, ["-lh1-"] = true, ["-lh4-"] = true, ["-lh5-"] = true,
["-lh6-"] = true, ["-lh7-"] = true, ["-lhx-"] = true, ["-lzs-"] = true, ["-lz5-"] = true, ["-lh2-"] = true,
["-lh3-"] = true, ["-pm0-"] = true, ["-pm1-"] = true, ["-pm2-"] = true, ["-lk7-"] = true,
}
-- ------------------------------------------------------------------------------------------------ sniff
local function isHeader(s: string): boolean
if #s < 22 then
return false
end
local m = string.sub(s, 3, 7)
local level = string.byte(s, 21)
return METHODS[m] == true and level <= 3
end
function Lha.sniff(r: Bytes.Reader): number
if isHeader(r:peek(22)) then
return 0.95
end
return 0
end
-- ------------------------------------------------------------------------------------------------ decode
local function dosTime(v: number): number?
local time, date = v % 65536, v // 65536
if date == 0 then
return nil
end
local y, m, d = 1980 + bit32.rshift(date, 9), bit32.band(bit32.rshift(date, 5), 15), bit32.band(date, 31)
if m < 1 or m > 12 or d < 1 then
return nil
end
local yy = if m <= 2 then y - 1 else y
local era = yy // 400
local yoe = yy - era * 400
local doy = (153 * (if m > 2 then m - 3 else m + 9) + 2) // 5 + d - 1
local days = era * 146097 + yoe * 365 + yoe // 4 - yoe // 100 + doy - 719468
return days * 86400 + bit32.rshift(time, 11) * 3600 + bit32.band(bit32.rshift(time, 5), 63) * 60 + bit32.band(time, 31) * 2
end
-- a path with "/" separators, without a leading "/" and without "." / ".." components (as lhasa collapses them)
local function path(s: string): string
s = string.gsub(s, "[\\\255]", "/")
local parts = {}
for part in string.gmatch(s, "[^/]+") do
if part ~= "." and part ~= ".." then
table.insert(parts, part)
end
end
return table.concat(parts, "/") .. (if string.sub(s, -1) == "/" and #parts > 0 then "/" else "")
end
type Header = {
method: string,
packed: number,
size: number,
mtime: number?,
level: number,
name: string,
dir: string?,
crc: number?,
mode: number?,
uid: number?,
gid: number?,
uname: string?,
gname: string?,
attr: number?,
comment: string?,
os: string?,
dataAt: number,
}
-- the extended headers from offset p (size field width w), until a zero size; returns the end offset
local function extended(r: Bytes.Reader, p: number, w: number, first: number, h: Header, limit: number): (number?, string?)
local size = first
local guard = 0
while size ~= 0 do
guard += 1
if guard > 4096 or size < w + 1 or p + size > limit then
return nil, "bad extended header"
end
local e = r:sub(p, size)
local kind = e:u8()
local body = size - 1 - w
if kind == 0x01 then
h.name = e:string(body)
elseif kind == 0x02 then
h.dir = e:string(body)
elseif kind == 0x3F or kind == 0x71 then
h.comment = e:string(body)
elseif kind == 0x40 and body >= 2 then
h.attr = e:u16le()
elseif kind == 0x50 and body >= 2 then
h.mode = e:u16le()
elseif kind == 0x51 and body >= 4 then
h.gid, h.uid = e:u16le(), e:u16le()
elseif kind == 0x52 then
h.gname = e:string(body)
elseif kind == 0x53 then
h.uname = e:string(body)
elseif kind == 0x54 and body >= 4 then
h.mtime = e:u32le()
elseif kind == 0x42 and body >= 16 then
h.packed, h.size = e:u64le(), e:u64le()
end
e:seek(size - w)
local nextSize = if w == 2 then e:u16le() else e:u32le()
if e.err then
return nil, "truncated extended header"
end
p += size
size = nextSize
end
return p, nil
end
local OS = { [0x4D] = "msdos", [0x55] = "unix", [0x32] = "os2", [0x39] = "os9", [0x4B] = "os68k", [0x33] = "os386",
[0x48] = "human68k", [0x43] = "cpm", [0x46] = "flex", [0x6D] = "mac", [0x77] = "windows95", [0x57] = "windowsnt",
[0x52] = "runser", [0x54] = "townsos", [0x58] = "xosk", [0x41] = "amiga", [0x61] = "atari", [0x4A] = "java" }
-- one header at p -> Header (h.dataAt: where the data starts), or nil at the end marker
local function header(r: Bytes.Reader, p: number): (Header?, string?)
local limit = r:size()
if p >= limit or r:sub(p, 1):u8() == 0 then
return nil, nil
end
if p + 22 > limit then
return nil, "truncated header"
end
local s = r:sub(p, 26)
local b0 = s:u8()
s:u8()
local method = s:string(5)
local packed, size, stamp = s:u32le(), s:u32le(), s:u32le()
s:u8()
local level = s:u8()
if not METHODS[method] then
return nil, "bad method " .. method
end
local h: Header = { method = string.sub(method, 2, 4), packed = packed, size = size, level = level, name = "", dataAt = 0 }
if level == 0 or level == 1 then
local hsize = b0 + 2
if p + hsize > limit or hsize < 24 then
return nil, "truncated header"
end
local hr = r:sub(p + 21, hsize - 21)
local nlen = hr:u8()
h.name = hr:string(nlen)
h.crc = hr:u16le()
h.mtime = dosTime(stamp)
if level == 0 then
-- an optional Unix extension: 'U', mtime, mode, uid, gid
if hr:remaining() >= 11 and (hr:peekU8() == 0x55 or hr:peekU8() == 0x4B) then
h.os = if hr:u8() == 0x55 then "unix" else "os68k"
h.mtime = hr:u32le()
h.mode = hr:u16le()
h.uid, h.gid = hr:u16le(), hr:u16le()
end
h.dataAt = p + hsize
else
h.os = OS[hr:u8()]
local first = r:sub(p + hsize - 2, 2):u16le()
local e, err = extended(r, p + hsize, 2, first, h, limit)
if not e then
return nil, err
end
h.packed = packed - (e - (p + hsize))
h.dataAt = e
end
if hr.err then
return nil, "truncated header"
end
elseif level == 2 then
local total = r:sub(p, 2):u16le()
local hr = r:sub(p + 21, 5)
h.crc = hr:u16le()
local osByte = hr:u8()
h.os = OS[osByte]
if osByte == 0x4B then
total += 2 -- LHa for OS-9/68k writes the header length without its own two bytes (as lhasa compensates)
end
local first = hr:u16le()
h.mtime = stamp
local e, err = extended(r, p + 26, 2, first, h, limit)
if not e or hr.err then
return nil, err or "truncated header"
end
h.dataAt = p + total
if total < 26 or h.dataAt > limit then
return nil, "bad level 2 header size"
end
elseif level == 3 then
local hr = r:sub(p + 21, 11)
h.crc = hr:u16le()
h.os = OS[hr:u8()]
local total = hr:u32le()
local first = hr:u32le()
h.mtime = stamp
local e, err = extended(r, p + 32, 4, first, h, limit)
if not e or hr.err then
return nil, err or "truncated header"
end
h.dataAt = p + total
if total < 32 or h.dataAt > limit then
return nil, "bad level 3 header size"
end
else
return nil, "unsupported: header level " .. level
end
return h, nil
end
local LZH_METHOD = { lh1 = "lh1", lh4 = "lh4", lh5 = "lh5", lh6 = "lh6", lh7 = "lh7", lhx = "lhx", lzs = "lzs", lz5 = "lz5" }
local function encoder(a: any, o: any?): (buffer?, Err.Err?)
return Lha.encode(a, o)
end
function Lha.decode(r: Bytes.Reader, opts: DecodeOptions?): (any, Err.Err?)
local o: DecodeOptions = opts or {}
local maxBytes = o.maxBytes or 2 ^ 30
local maxEntries = o.maxEntries or 65536
local p = 0
-- a self-extracting stub: find the first header
if not isHeader(r:peek(22)) then
local head = r:peek(65536)
local at = nil
for k = 1, #head - 22 do
if string.byte(head, k + 2) == 45 and isHeader(string.sub(head, k, k + 21)) then
at = k - 1
break
end
end
if not at then
return nil, Err.new(Err.CORRUPT, "no LHA header")
end
p = at
end
local a = Archive.new("lha", encoder)
local count = 0
local levels = {}
while true do
local h, err = header(r, p)
if err then
return nil, Err.from(err, r.base + p)
end
if not h then
break
end
count += 1
if count > maxEntries then
return nil, Err.new(Err.LIMIT, "more than maxEntries entries")
end
levels[h.level] = true
if h.packed < 0 or h.dataAt + h.packed > r:size() then
return nil, Err.new(Err.TRUNCATED, "entry " .. path(h.name) .. " data past the end", r.base + h.dataAt)
end
-- MS-DOS-like archives store names in capitals: all-caps names read in lower case, as lhasa / LHa do
local os = h.os
if os == nil or os == "msdos" or os == "atari" or os == "os2" then
if not string.find(h.name .. (h.dir or ""), "%l") then
h.name = string.lower(h.name)
h.dir = if h.dir then string.lower(h.dir) else nil
end
end
-- the full path (a Unix symlink "name|target" may be split across the directory and file name headers)
local name = path(h.name)
if h.dir and h.dir ~= "" then
local d = path(h.dir)
if string.sub(d, -1) ~= "/" then
d ..= "/"
end
name = d .. name
end
local link: string? = nil
local bar = string.find(name, "|", 1, true)
if bar then
name, link = string.sub(name, 1, bar - 1), string.sub(name, bar + 1)
end
local isDir = h.method == "lhd"
if isDir and link == nil and string.sub(name, -1) ~= "/" then
name ..= "/"
end
local e: any = {
name = name,
size = if isDir or link then 0 else h.size,
compressedSize = h.packed,
method = h.method,
mtime = h.mtime,
dir = isDir and link == nil,
mode = h.mode,
uid = h.uid,
gid = h.gid,
uname = h.uname,
gname = h.gname,
attr = h.attr,
comment = h.comment,
os = h.os,
level = h.level,
crc = h.crc,
}
if link then
e.link = link
e.type = "symlink"
elseif not isDir and h.size > 0 then
if h.size > maxBytes then
return nil, Err.new(Err.LIMIT, name .. ": larger than maxBytes")
end
local at, packed, size, method, crc = h.dataAt, h.packed, h.size, h.method, h.crc
local buf, base = r.buf, r.base
e.load = function(): (buffer?, Err.Err?)
local out: buffer?, derr: string?
if method == "lh0" or method == "lz4" then
if packed < size then
return nil, Err.new(Err.CORRUPT, "stored entry shorter than its size")
end
out = buffer.create(size)
buffer.copy(out :: buffer, 0, buf, base + at, size)
elseif LZH_METHOD[method] then
out, derr = Lzh.decode(buf, base + at, packed, size, LZH_METHOD[method])
else
return nil, Err.new(Err.UNSUPPORTED, "method " .. method)
end
if not out then
return nil, Err.from(derr)
end
if crc and Crc16.arc(out, 0, size) ~= crc then
return nil, Err.new(Err.CHECKSUM, "CRC-16 mismatch")
end
return out, nil
end
end
Archive.put(a, e)
p = h.dataAt + h.packed
end
a.meta.source = { format = "lha", levels = levels }
return a, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Lha.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?)
local items = Archive.entries(value)
if not items then
return nil, Err.new(Err.ARG, "expected an Archive")
end
local out = Bytes.writer()
for _, it in items do
local e: any = it.entry
local data = buffer.create(0)
if not e.dir then
local b, err = it.read()
if not b then
return nil, err
end
data = b
end
local full = string.gsub(e.name, "/+$", "")
local dirPart, base = string.match(full, "^(.*/)([^/]*)$")
if not dirPart then
dirPart, base = "", full
end
if e.dir then
dirPart, base = full .. "/", ""
end
local h = Bytes.writer()
h:u16le(0) -- total size, patched
h:string(if e.dir then "-lhd-" else "-lh0-")
h:u32le(buffer.len(data))
h:u32le(buffer.len(data))
h:u32le(if type(e.mtime) == "number" and e.mtime >= 0 then math.floor(e.mtime) % 4294967296 else 0)
h:u8(0x20)
h:u8(2)
h:u16le(Crc16.arc(data, 0, buffer.len(data)))
h:u8(0x55) -- 'U'nix
-- extended headers: [type][body][size of the next one]; the first size ends the base header
local exts: { { any } } = { { 0x00, "\0\0" }, { 0x01, base } }
if dirPart ~= "" then
table.insert(exts, { 0x02, (string.gsub(dirPart :: string, "/", "\255")) })
end
if type(e.mode) == "number" then
local m = bit32.band(e.mode, 0xFFF) + (if e.dir then 0x4000 else 0x8000)
table.insert(exts, { 0x50, string.char(m % 256, m // 256) })
end
h:u16le(#exts[1][2] + 3)
for i, x in exts do
h:u8(x[1])
h:string(x[2])
h:u16le(if exts[i + 1] then #exts[i + 1][2] + 3 else 0)
end
local hb = h:finish()
local total = buffer.len(hb)
if total > 65535 then
return nil, Err.new(Err.ARG, "header too long for " .. e.name)
end
buffer.writeu16(hb, 0, total)
-- the header CRC covers the whole header with its own field zero
local crcAt = 24 + 2 + 1 -- first ext: size (2) at 24, type at 26, CRC at 27
buffer.writeu16(hb, crcAt, Crc16.arc(hb, 0, total))
out:bytes(hb)
out:bytes(data)
end
out:u8(0)
return out:finish(), nil
end
-- ------------------------------------------------------------------------------------------------ extras
-- new() -> an empty LHA Archive: a:add(name, data, { mtime, mode }); a:write() (level 2 headers, stored data)
function Lha.new(): any
local a = Archive.new("lha", encoder)
a.meta.source = { format = "lha" }
return a
end
return Lha
+626
View File
@@ -0,0 +1,626 @@
--!strict
--!native
--!optimize 2
-- codecs/compress/Lzh: the LHA family of LZSS decoders, used by archive/lha, archive/arj and archive/zoo:
-- lh4 / lh5 / lh6 / lh7 / lhx static Huffman blocks (code-length "temp" table, 510 literal / length codes, offset
-- bit-length codes); also ARJ methods 1..3 (= "lh6") and Zoo method 2 (= "lh5")
-- lh1 adaptive Huffman (LHarc 1.x: 314 codes, grouped frequency tree) with fixed-length
-- offset prefixes, 4 KB window
-- lzs / lz5 LArc's plain LZSS (2 KB / 4 KB windows, flag bits / flag bytes)
-- arj4 ARJ method 4 (unary-prefixed lengths and offsets, no Huffman)
-- Every method decodes into a buffer of the known output size; the windows start filled as the original tools fill
-- them (spaces; lz5's pattern), and offsets before the start of the output read that fill.
-- Ported from lhasa 0.6.0 (Simon Howard, ISC licence: licenses/lhasa-LICENSE.txt): lh_new_decoder.c, lh1_decoder.c,
-- lzs_decoder.c, lz5_decoder.c; the static Huffman tables are canonical codes built with codecs/entropy/Huffman instead
-- of lhasa's trees. ARJ method 4 is written from the ARJ technical notes (unarj's decode_f description).
--
-- local out, err = Lzh.decode(src, off, len, outSize, "lh5") -- buffer | nil, message
--
-- Never throws: bad codes / truncated input return nil, message (truncated input: "truncated ..." after the bytes
-- decoded so far would be useless, so nothing partial is returned). Not supported: pm0 / pm1 / pm2 (PMarc), lk7.
local Huffman = require("@formats/codecs/entropy/Huffman")
local Lzh = {}
local readu8, writeu8, readu32 = buffer.readu8, buffer.writeu8, buffer.readu32
local band, rshift, lshift = bit32.band, bit32.rshift, bit32.lshift
local floor = math.floor
-- ------------------------------------------------------------------------------------------------ bit reader
-- an MSB-first bit reader over src[pos, limit): acc holds cnt bits (cnt <= 32); past the end, zero bits are read and
-- over counts them
type Reader = { src: buffer, pos: number, limit: number, acc: number, cnt: number, over: number }
local function reader(src: buffer, off: number, len: number): Reader
return { src = src, pos = off, limit = math.min(off + len, buffer.len(src)), acc = 0, cnt = 0, over = 0 }
end
local function fill(r: Reader)
while r.cnt <= 24 do
local b = 0
if r.pos < r.limit then
b = readu8(r.src, r.pos)
r.pos += 1
else
r.over += 8
end
r.acc = r.acc * 256 + b
r.cnt += 8
end
end
local function peek(r: Reader, n: number): number
if r.cnt < n then
fill(r)
end
return floor(r.acc / 2 ^ (r.cnt - n)) % 2 ^ n
end
local function skip(r: Reader, n: number)
if r.cnt < n then
fill(r)
end
r.cnt -= n
r.acc = r.acc % 2 ^ r.cnt
end
local function bits(r: Reader, n: number): number
if n == 0 then
return 0
end
local v = peek(r, n)
skip(r, n)
return v
end
-- ------------------------------------------------------------------------------------------------ static Huffman
type Table = { tab: buffer, P: number, S: number, single: number }
local function newTable(nsym: number, P: number): Table
return { tab = buffer.create(Huffman.capacity(nsym, P, 16) * 4), P = P, S = 0, single = -1 }
end
local function build(t: Table, lens: buffer, n: number): boolean
t.single = -1
local S = Huffman.buildMsb(lens, 0, n, t.tab, t.P)
if S < 0 then
return false
end
t.S = S
return true
end
local function decodeSym(r: Reader, t: Table): number
if t.single >= 0 then
return t.single
end
local P, S = t.P, t.S
local e = readu32(t.tab, peek(r, P) * 4)
local l = band(e, 31)
if l == 0 then
if e == 0 then
return -1
end
local idx = peek(r, P + S)
e = readu32(t.tab, (rshift(e, 5) + band(idx, lshift(1, S) - 1)) * 4)
l = band(e, 31)
if l == 0 then
return -1
end
end
skip(r, l)
return rshift(e, 5)
end
local lens = buffer.create(512)
local function lengthValue(r: Reader): number
local len = bits(r, 3)
if len == 7 then
while bits(r, 1) == 1 do
len += 1
if len > 16 then
return 17
end
end
end
return len
end
-- the temp (code-length code) table and the offset table share this layout; special = 2 for the temp table
local function readLengths(r: Reader, t: Table, nbits: number, maxN: number, special: number): boolean
local n = bits(r, nbits)
if n == 0 then
t.single = bits(r, nbits)
return true
end
n = math.min(n, maxN)
buffer.fill(lens, 0, 0, 512)
local i = 0
while i < n do
local l = lengthValue(r)
if l > 16 then
return false
end
writeu8(lens, i, l)
if i == special then
local z = bits(r, 2)
i += z -- zeros (already zero)
end
i += 1
end
return build(t, lens, math.min(i, maxN))
end
local function readCodes(r: Reader, temp: Table, codes: Table): boolean
local n = bits(r, 9)
if n == 0 then
codes.single = bits(r, 9)
return true
end
n = math.min(n, 510)
buffer.fill(lens, 0, 0, 512)
local i = 0
while i < n do
local c = decodeSym(r, temp)
if c < 0 then
return false
end
if c <= 2 then
local count = if c == 0 then 1 elseif c == 1 then bits(r, 4) + 3 else bits(r, 9) + 20
i += count
else
if c - 2 > 16 then
return false
end
writeu8(lens, i, c - 2)
i += 1
end
end
return build(codes, lens, n)
end
local OFFSET_BITS = { lh4 = 4, lh5 = 4, lh6 = 5, lh7 = 5, lhx = 5 }
local function decodeNew(src: buffer, off: number, len: number, out: buffer, n: number, method: string): string?
local r = reader(src, off, len)
local obits = OFFSET_BITS[method]
local temp, codes, offs = newTable(19, 8), newTable(510, 10), newTable(32, 8)
local o = 0
local remaining = 0
while o < n do
if remaining == 0 then
remaining = bits(r, 16)
if not readLengths(r, temp, 5, 19, 2) or not readCodes(r, temp, codes) or not readLengths(r, offs, obits, lshift(1, obits) - 1, -1) then
return if r.over > 0 then "truncated" else "bad Huffman table"
end
if r.over > 32 then
return "truncated"
end
if remaining == 0 then
return "empty block"
end
end
remaining -= 1
local c = decodeSym(r, codes)
if c < 0 then
return "bad code"
end
if c < 256 then
writeu8(out, o, c)
o += 1
else
local count = c - 256 + 3
local p = decodeSym(r, offs)
if p < 0 then
return "bad offset code"
end
if p > 1 then
p = lshift(1, p - 1) + bits(r, p - 1)
end
local from = o - p - 1
for _ = 1, count do
if o >= n then
break
end
writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20)
o += 1
from += 1
end
end
if r.over > 32 then
return "truncated"
end
end
return nil
end
-- ------------------------------------------------------------------------------------------------ lh1
local NUM_CODES = 314
local NUM_NODES = NUM_CODES * 2 - 1
local REORDER = 32 * 1024
local FDIST = { 1, 3, 8, 12, 24, 16 }
local offsetLookup = table.create(256, 0)
local offsetLength = table.create(64, 0)
do
local code, offset = 0, 0
for i, count in FDIST do
local l = i - 1 + 3
local iter = lshift(1, 8 - l)
for _ = 1, count do
for k = 0, iter - 1 do
offsetLookup[code + k + 1] = offset
end
offsetLength[offset + 1] = l
code += iter
offset += 1
end
end
end
local function decodeLh1(src: buffer, off: number, len: number, out: buffer, n: number): string?
local r = reader(src, off, len)
-- node arrays (0-based indexes stored at [i + 1])
local leaf = table.create(NUM_NODES, false)
local child = table.create(NUM_NODES, 0)
local parent = table.create(NUM_NODES, 0)
local freq = table.create(NUM_NODES, 0)
local group = table.create(NUM_NODES, 0)
local leafNodes = table.create(NUM_CODES, 0)
local groups = table.create(NUM_NODES, 0)
local leader = table.create(NUM_NODES, 0)
local numGroups = 0
local function initGroups()
for i = 0, NUM_NODES - 1 do
groups[i + 1] = i
end
numGroups = 0
end
local function allocGroup(): number
local g = groups[numGroups + 1]
numGroups += 1
return g
end
local function freeGroup(g: number)
numGroups -= 1
groups[numGroups + 1] = g
end
initGroups()
do
local ni = NUM_NODES - 1
local lg = allocGroup()
for i = 0, NUM_CODES - 1 do
leaf[ni + 1], child[ni + 1], freq[ni + 1], group[ni + 1] = true, i, 1, lg
leader[lg + 1] = ni
leafNodes[i + 1] = ni
ni -= 1
end
local c = NUM_NODES - 1
while ni >= 0 do
leaf[ni + 1], child[ni + 1] = false, c
parent[c + 1], parent[c] = ni, ni
freq[ni + 1] = freq[c + 1] + freq[c]
if freq[ni + 1] == freq[ni + 2] then
group[ni + 1] = group[ni + 2]
else
group[ni + 1] = allocGroup()
end
leader[group[ni + 1] + 1] = ni
ni -= 1
c -= 2
end
end
local function makeLeader(ni: number): number
local g = group[ni + 1]
local li = leader[g + 1]
if li == ni then
return ni
end
leaf[li + 1], leaf[ni + 1] = leaf[ni + 1], leaf[li + 1]
child[li + 1], child[ni + 1] = child[ni + 1], child[li + 1]
for _, x in { ni, li } do
if leaf[x + 1] then
leafNodes[child[x + 1] + 1] = x
else
parent[child[x + 1] + 1] = x
parent[child[x + 1]] = x
end
end
return li
end
local function incrementNode(ni: number)
freq[ni + 1] += 1
if ni < NUM_NODES - 1 and group[ni + 1] == group[ni + 2] then
leader[group[ni + 1] + 1] += 1
if freq[ni + 1] == freq[ni] then
group[ni + 1] = group[ni]
else
group[ni + 1] = allocGroup()
leader[group[ni + 1] + 1] = ni
end
elseif freq[ni + 1] == freq[ni] then
freeGroup(group[ni + 1])
group[ni + 1] = group[ni]
end
end
local function reconstruct()
-- leaves to the front, halved
local li = 0
for i = 0, NUM_NODES - 1 do
if leaf[i + 1] then
leaf[li + 1], child[li + 1], freq[li + 1] = true, child[i + 1], (freq[i + 1] + 1) // 2
li += 1
end
end
local lp = NUM_CODES - 1
local c = NUM_NODES - 1
local i = NUM_NODES - 1
while i >= 0 do
while c - i < 2 do
leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1]
leafNodes[child[i + 1] + 1] = i
i -= 1
lp -= 1
end
local f = freq[c + 1] + freq[c]
while lp >= 0 and f >= freq[lp + 1] do
leaf[i + 1], child[i + 1], freq[i + 1] = leaf[lp + 1], child[lp + 1], freq[lp + 1]
leafNodes[child[i + 1] + 1] = i
i -= 1
lp -= 1
end
leaf[i + 1], freq[i + 1], child[i + 1] = false, f, c
parent[c + 1], parent[c] = i, i
i -= 1
c -= 2
end
initGroups()
local g = allocGroup()
group[1] = g
leader[g + 1] = 0
for k = 1, NUM_NODES - 1 do
if freq[k + 1] == freq[k] then
group[k + 1] = group[k]
else
g = allocGroup()
group[k + 1] = g
leader[g + 1] = k
end
end
end
local o = 0
while o < n do
local ni = 0
local guard = 0
while not leaf[ni + 1] do
ni = child[ni + 1] - bits(r, 1)
guard += 1
if guard > NUM_NODES or ni < 0 then
return "bad tree"
end
end
local code = child[ni + 1]
-- increment_for_code
if freq[1] >= REORDER then
reconstruct()
end
freq[1] += 1
local x = leafNodes[code + 1]
while x ~= 0 do
x = makeLeader(x)
incrementNode(x)
x = parent[x + 1]
end
if code < 256 then
writeu8(out, o, code)
o += 1
else
local future = peek(r, 8)
local hi = offsetLookup[future + 1]
skip(r, offsetLength[hi + 1])
local offset = hi * 64 + bits(r, 6)
local count = code - 256 + 3
local from = o - offset - 1
for _ = 1, count do
if o >= n then
break
end
writeu8(out, o, if from >= 0 then readu8(out, from) else 0x20)
o += 1
from += 1
end
end
if r.over > 32 then
return "truncated"
end
end
return nil
end
-- ------------------------------------------------------------------------------------------------ LArc lzs / lz5
-- the ring of a 2 KB / 4 KB window (positions are absolute ring positions, not distances)
local function decodeLzs(src: buffer, off: number, len: number, out: buffer, n: number): string?
local r = reader(src, off, len)
local ring = buffer.create(2048)
buffer.fill(ring, 0, 0x20)
local rp = 2048 - 17
local o = 0
while o < n do
if bits(r, 1) == 1 then
local b = bits(r, 8)
writeu8(out, o, b)
writeu8(ring, rp, b)
rp = (rp + 1) % 2048
o += 1
else
local pos = bits(r, 11)
local l = bits(r, 4) + 2
for k = 0, l - 1 do
if o >= n then
break
end
local b = readu8(ring, (pos + k) % 2048)
writeu8(out, o, b)
writeu8(ring, rp, b)
rp = (rp + 1) % 2048
o += 1
end
end
if r.over > 32 then
return "truncated"
end
end
return nil
end
local LZ5_INIT = buffer.create(4096)
do
local p = 0
for i = 0, 255 do
for _ = 1, 13 do
writeu8(LZ5_INIT, p, i)
p += 1
end
end
for i = 0, 255 do
writeu8(LZ5_INIT, p, i)
p += 1
end
for i = 0, 255 do
writeu8(LZ5_INIT, p, 255 - i)
p += 1
end
p += 128
for _ = 1, 110 do
writeu8(LZ5_INIT, p, 0x20)
p += 1
end
end
local function decodeLz5(src: buffer, off: number, len: number, out: buffer, n: number): string?
local ring = buffer.create(4096)
buffer.copy(ring, 0, LZ5_INIT)
local rp = 4096 - 18
local p = off
local limit = math.min(off + len, buffer.len(src))
local o = 0
while o < n do
if p >= limit then
return "truncated"
end
local flags = readu8(src, p)
p += 1
for bit = 0, 7 do
if o >= n then
break
end
if band(flags, lshift(1, bit)) ~= 0 then
if p >= limit then
return "truncated"
end
local b = readu8(src, p)
p += 1
writeu8(out, o, b)
writeu8(ring, rp, b)
rp = (rp + 1) % 4096
o += 1
else
if p + 2 > limit then
return "truncated"
end
local c0, c1 = readu8(src, p), readu8(src, p + 1)
p += 2
local start = lshift(band(c1, 0xF0), 4) + c0
local l = band(c1, 15) + 3
for k = 0, l - 1 do
if o >= n then
break
end
local b = readu8(ring, (start + k) % 4096)
writeu8(out, o, b)
writeu8(ring, rp, b)
rp = (rp + 1) % 4096
o += 1
end
end
end
end
return nil
end
-- ------------------------------------------------------------------------------------------------ ARJ method 4
local function decodeArj4(src: buffer, off: number, len: number, out: buffer, n: number): string?
local r = reader(src, off, len)
local function prefixed(start: number, stop: number): number
local plus, pwr = 0, lshift(1, start)
local width = start
while width < stop do
if bits(r, 1) == 0 then
break
end
plus += pwr
pwr *= 2
width += 1
end
return (if width ~= 0 then bits(r, width) else 0) + plus
end
local o = 0
while o < n do
local c = prefixed(0, 7)
if c == 0 then
writeu8(out, o, bits(r, 8))
o += 1
else
local count = c - 1 + 3
local pos = prefixed(9, 13)
local from = o - pos - 1
for _ = 1, count do
if o >= n then
break
end
writeu8(out, o, if from >= 0 then readu8(out, from) else 0)
o += 1
from += 1
end
end
if r.over > 32 then
return "truncated"
end
end
return nil
end
-- ------------------------------------------------------------------------------------------------ api
Lzh.METHODS = { "lh1", "lh4", "lh5", "lh6", "lh7", "lhx", "lzs", "lz5", "arj4" }
-- decode(src, off, len, outSize, method) -> buffer | nil, message
function Lzh.decode(src: buffer, off: number, len: number, outSize: number, method: string): (buffer?, string?)
if off < 0 or len < 0 or off > buffer.len(src) or outSize < 0 or outSize ~= outSize then
return nil, "bad arguments"
end
local out = buffer.create(outSize)
if outSize == 0 then
return out, nil
end
local err: string?
if OFFSET_BITS[method] then
err = decodeNew(src, off, len, out, outSize, method)
elseif method == "lh1" then
err = decodeLh1(src, off, len, out, outSize)
elseif method == "lzs" then
err = decodeLzs(src, off, len, out, outSize)
elseif method == "lz5" then
err = decodeLz5(src, off, len, out, outSize)
elseif method == "arj4" then
err = decodeArj4(src, off, len, out, outSize)
else
return nil, "unsupported: method " .. tostring(method)
end
if err then
return nil, err
end
return out, nil
end
return Lzh