43 lines
1.4 KiB
Luau
43 lines
1.4 KiB
Luau
--!strict
|
|
--!native
|
|
--!optimize 2
|
|
-- archive/cab/Sum: the cabinet data block checksum (the XOR of the data's little-endian 32-bit words, the last 1..3
|
|
-- bytes packed most significant first, then the block's cbData / cbUncomp word). Written from the CAB format
|
|
-- description ([MS-CAB] 2.4, CFDATA.csum).
|
|
|
|
local readu8, readu32, blen = buffer.readu8, buffer.readu32, buffer.len
|
|
local bxor, bor, lshift = bit32.bxor, bit32.bor, bit32.lshift
|
|
|
|
local Sum = {}
|
|
|
|
-- of(buf, off, len, seed) -> the checksum of buf[off, off + len) continuing from seed (0 for a new sum)
|
|
function Sum.of(buf: buffer, off: number, len: number, seed: number): number
|
|
if off < 0 or len <= 0 or off + len > blen(buf) then
|
|
return seed
|
|
end
|
|
local s = seed
|
|
local p = off
|
|
local stop = off + len - len % 4
|
|
while p < stop do
|
|
s = bxor(s, readu32(buf, p))
|
|
p += 4
|
|
end
|
|
local rem = len % 4
|
|
local tail = 0
|
|
if rem == 3 then
|
|
tail = bor(lshift(readu8(buf, p), 16), lshift(readu8(buf, p + 1), 8), readu8(buf, p + 2))
|
|
elseif rem == 2 then
|
|
tail = bor(lshift(readu8(buf, p), 8), readu8(buf, p + 1))
|
|
elseif rem == 1 then
|
|
tail = readu8(buf, p)
|
|
end
|
|
return bxor(s, tail)
|
|
end
|
|
|
|
-- block(buf, dataAt, cbData, cbUncomp) -> the csum field of a CFDATA block with these sizes over buf[dataAt, +cbData)
|
|
function Sum.block(buf: buffer, dataAt: number, cbData: number, cbUncomp: number): number
|
|
return bxor(Sum.of(buf, dataAt, cbData, 0), cbData + cbUncomp * 65536)
|
|
end
|
|
|
|
return Sum
|