Files
rosetta/src/Formats/model/mca/Lz4Block.luau
T

71 lines
2.1 KiB
Luau

--!strict
-- model/mca/Lz4Block: the lz4-java LZ4BlockOutputStream framing Minecraft (24w04a+) uses for compression type 4
-- chunks, from lz4-java's LZ4BlockOutputStream source: blocks of "LZ4Block", a token (method 0x10 raw / 0x20 LZ4 |
-- level), compressed and decompressed lengths and an XXH32 checksum (little-endian i32s; not verified), then the
-- block, each block independent; an empty block ends the stream. The blocks decode through codecs/compress/Lz4.
local Lz4 = require("@formats/codecs/compress/Lz4")
local Lz4Block = {}
local MAGIC = "LZ4Block"
-- decode(buf, offset, length, maxBytes) -> buffer | nil, message
function Lz4Block.decode(b: buffer, offset: number, length: number, maxBytes: number): (buffer?, string?)
local p, e = offset, offset + length
local parts, total = {}, 0
while true do
if p + 21 > e then
if #parts > 0 and p >= e then
break -- some writers stop without the empty end block
end
return nil, "truncated LZ4 block header"
end
if buffer.readstring(b, p, 8) ~= MAGIC then
return nil, "bad LZ4Block magic"
end
local token = buffer.readu8(b, p + 8)
local clen, dlen = buffer.readi32(b, p + 9), buffer.readi32(b, p + 13)
p += 21
local method = token // 16 * 16
if clen < 0 or dlen < 0 or p + clen > e then
return nil, "truncated LZ4 block"
end
if dlen == 0 and clen == 0 then
break
end
total += dlen
if total > maxBytes then
return nil, "limit: chunk inflates past maxBytes"
end
if method == 0x10 then
if clen ~= dlen then
return nil, "raw LZ4 block length mismatch"
end
local out = buffer.create(dlen)
buffer.copy(out, 0, b, p, clen)
table.insert(parts, out)
elseif method == 0x20 then
local out, err = Lz4.decompress(b, p, clen, dlen)
if not out then
return nil, "LZ4: " .. tostring(err and err.message)
end
table.insert(parts, out)
else
return nil, "unsupported: LZ4Block method " .. method
end
p += clen
end
if #parts == 1 then
return parts[1], nil
end
local res = buffer.create(total)
local w = 0
for _, part in parts do
buffer.copy(res, w, part)
w += buffer.len(part)
end
return res, nil
end
return Lz4Block