core/Crc16 is new (CRC-16/XMODEM for BinHex / MacBinary, CRC-16/ARC for LHA / Zoo). containers/Archive gains Archive.files(value, name?) (additive).
53 lines
1.7 KiB
Luau
53 lines
1.7 KiB
Luau
--!strict
|
|
--!native
|
|
-- core/Crc16: the two 16-bit CRCs old archive and encoding formats use, table driven. New code.
|
|
-- Crc16.ccitt(buf, off, len, crc?) CRC-16/XMODEM: polynomial 0x1021, MSB first, init 0, no final XOR (BinHex 4.0,
|
|
-- MacBinary II / III headers)
|
|
-- Crc16.arc(buf, off, len, crc?) CRC-16/ARC: polynomial 0x8005 reflected (0xA001), init 0 (LHA, Zoo, ARC)
|
|
-- Pass a previous result as crc to continue it. Never throws: the range is clamped to the buffer.
|
|
local band, bxor, rshift, lshift = bit32.band, bit32.bxor, bit32.rshift, bit32.lshift
|
|
local readu8 = buffer.readu8
|
|
|
|
local MSB = table.create(256, 0)
|
|
local ARC = table.create(256, 0)
|
|
for n = 0, 255 do
|
|
local c = lshift(n, 8)
|
|
for _ = 1, 8 do
|
|
c = if band(c, 0x8000) ~= 0 then bxor(band(lshift(c, 1), 0xFFFF), 0x1021) else band(lshift(c, 1), 0xFFFF)
|
|
end
|
|
MSB[n + 1] = c
|
|
local r = n
|
|
for _ = 1, 8 do
|
|
r = if band(r, 1) ~= 0 then bxor(rshift(r, 1), 0xA001) else rshift(r, 1)
|
|
end
|
|
ARC[n + 1] = r
|
|
end
|
|
|
|
local Crc16 = {}
|
|
|
|
local function clamp(buf: buffer, off: number, len: number): (number, number)
|
|
local n = buffer.len(buf)
|
|
local o = math.clamp(math.floor(off), 0, n)
|
|
return o, math.clamp(math.floor(len), 0, n - o)
|
|
end
|
|
|
|
function Crc16.ccitt(buf: buffer, off: number, len: number, crc: number?): number
|
|
local o, l = clamp(buf, off, len)
|
|
local c = crc or 0
|
|
for i = o, o + l - 1 do
|
|
c = bxor(band(lshift(c, 8), 0xFFFF), MSB[bxor(rshift(c, 8), readu8(buf, i)) + 1])
|
|
end
|
|
return c
|
|
end
|
|
|
|
function Crc16.arc(buf: buffer, off: number, len: number, crc: number?): number
|
|
local o, l = clamp(buf, off, len)
|
|
local c = crc or 0
|
|
for i = o, o + l - 1 do
|
|
c = bxor(rshift(c, 8), ARC[bxor(band(c, 0xFF), readu8(buf, i)) + 1])
|
|
end
|
|
return c
|
|
end
|
|
|
|
return Crc16
|