-- codecs/compress/PackBits tests: the Apple technote example, encode -> decode round trips of random / runny rows, -- the clean flag on short input and overflowing runs, and a no-throw pass over garbage. local T = require("@tests/T") local PackBits = require("@rosetta/codecs/compress/PackBits") local t = T.suite("packbits") -- Apple Technical Note TN1023 local packed = T.bytes({ 0xFE, 0xAA, 0x02, 0x80, 0x00, 0x2A, 0xFD, 0xAA, 0x03, 0x80, 0x00, 0x2A, 0x22, 0xF7, 0xAA }) local want = T.bytes({ 0xAA, 0xAA, 0xAA, 0x80, 0x00, 0x2A, 0xAA, 0xAA, 0xAA, 0xAA, 0x80, 0x00, 0x2A, 0x22, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA, 0xAA }) local out = buffer.create(24) local n, pEnd, clean = PackBits.decode(packed, 0, buffer.len(packed), out, 0, 24) t:check(n == 24 and pEnd == buffer.len(packed) and clean and buffer.tostring(out) == buffer.tostring(want), "TN1023 example") local rand = T.rng(11) for k = 1, 40 do local len = rand(600) local row = buffer.create(len) local i = 0 while i < len do local v, run = rand(256) - 1, (if rand(3) == 1 then rand(200) else 1) for _ = 1, run do if i < len then buffer.writeu8(row, i, v) i += 1 end end end local enc = PackBits.encode(row, 0, len) local dec = buffer.create(len) local m, _, ok = PackBits.decode(enc, 0, buffer.len(enc), dec, 0, len) t:check(m == len and ok and buffer.tostring(dec) == buffer.tostring(row), "round trip " .. k) end local short = buffer.create(10) local m1, _, ok1 = PackBits.decode(T.bytes({ 0x05, 1, 2 }), 0, 3, short, 0, 10) t:check(m1 == 2 and not ok1, "short literal: what is there, not clean") local m2, _, ok2 = PackBits.decode(T.bytes({ 0x81, 7 }), 0, 2, short, 0, 10) t:check(m2 == 10 and not ok2, "a run past n is clipped, not clean") t:fuzz("decode", function(b: buffer) local o = buffer.create(256) return PackBits.decode(b, 0, buffer.len(b), o, 0, 256) end, { buffer.tostring(packed) }) t:done()