diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f77afa..403ee08 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -48,6 +48,16 @@ API between minor releases. - `PlaStream.SkippedBlocks`: the indexed blocks that failed to decode to their declared size (false entries of the scan), in file order — the blocks behind `UnreliableFrom`. +- `CompressedPool.ReadSubgroups()` decodes mode-2 pool subgroups. A mode-2 payload is an LZ token stream like a + mode-2 block payload; it may start with a 13-byte pool header (a u32, the 0x47 marker, the packed payload length + and the unpacked size) or with the file block's 9-byte stream header. Its back-references reach into the pool + stream — the reconstruction of every preceding pool of the document and of this pool before the record — so a read + decodes the pools before the named one; reading the pools in file order advances one shared window, so every pool + decodes once. A skipped pool or an undecodable mode-2 subgroup resets the history. A mode-2 payload that cannot + decode is reported with empty data and `Partial`. The decoder discards history beyond the maximum back-reference + distance between records. `FindCompressedPools` caches its list after the first scan, so the pool objects stay + identical between calls. + ### Changed - The core library follows the IOExtend reference layout (RvtIO, NwcIO): the entry points (`PlaDocument`, diff --git a/docs/public-api.md b/docs/public-api.md index a332161..072500d 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -62,7 +62,7 @@ independent decoding of saved-file frames verified the correspondence. PlaIO has | Member | Use | |---|---| -| `PlaDocument.FindCompressedPools()` | Finds pool markers outside indexed block payloads and validates frame headers and sizes. Computed on each call. | +| `PlaDocument.FindCompressedPools()` | Finds pool markers outside indexed block payloads and validates frame headers and sizes. The first call scans the file; later calls return the cached list, so the pool objects stay identical. | | `CompressedPool.Offset` and `End` | File offsets of the pool marker and of the end of the pool. | | `CompressedPool.TotalDecompressed` and `BlockCount` | Decoded byte count and number of frames in the pool. | | `CompressedPool.Decode()` | Decoded frame payloads in order. Throws `InvalidDataException` on invalid framing or data (a pool past `PlaReaderOptions.MaxDecodedPoolBytes` included) and `ObjectDisposedException` after disposing the document. | @@ -70,15 +70,23 @@ independent decoding of saved-file frames verified the correspondence. PlaIO has ### Pool subgroups The subgroup header uses the FDB size field widths and may carry a GUID. It does not contain the file-level extra field. -Offsets are relative to the decoded pool. The scanner retries an unmatched BL candidate at the next byte. +Offsets are relative to the decoded pool. The scanner retries an unmatched BL candidate at the next byte. A mode-2 +payload is an LZ token stream like a mode-2 block payload: it may start with a 13-byte pool header (a u32, the 0x47 +marker, the packed payload length and the unpacked size) or with the file block's 9-byte stream header, and its +back-references reach into the pool stream — the reconstruction of every preceding pool of the document and of this +pool before the record — so a read decodes the pools before the named one. Reading the pools in file order advances +one shared window, so every pool decodes once. A read that names an earlier pool rebuilds the window. A skipped +pool or an undecodable mode-2 subgroup resets the history. A reference into missing history returns empty data +with `Partial` set. Subgroups can continue to reference bytes decoded after the gap. A back-reference distance is a +u16, so the decoder can discard older history between records. | Member | Use | |---|---| -| `CompressedPool.ReadSubgroups()` | Decodes the pool and returns the recognised BL-tagged records in pool order. | +| `CompressedPool.ReadSubgroups()` | Decodes the pool and returns the recognised BL-tagged records in pool order, with mode-2 payloads decoded against the pool stream. | | `PoolSubgroup.Offset` | Start of the subgroup header in the decoded pool. | | `PoolSubgroup.Kind`, `Version`, `Flags` and `ObjectId` | Raw header metadata and the optional GUID. | -| `PoolSubgroup.Mode` and `Data` | Raw or zero-mask payload bytes. Mode 2 is reported with empty data. | -| `PoolSubgroup.Partial` | True for unavailable mode 2 data or an incomplete zero-mask literal. A zero-mask stream ending at a group boundary can leave valid zero padding. | +| `PoolSubgroup.Mode` and `Data` | The payload bytes: raw as they are, zero-mask and mode-2 as their decoded output. A mode-2 payload that does not decode is reported with empty data and `Partial`. | +| `PoolSubgroup.Partial` | True for a mode-2 payload that does not decode (or produces less than declared) or an incomplete zero-mask literal. A zero-mask stream ending at a group boundary can leave valid zero padding. | ## BIMx file (`.bimx`) diff --git a/src/PlaIO/Internal/PoolSubgroupReader.cs b/src/PlaIO/Internal/PoolSubgroupReader.cs index ee7e8b1..ef6e914 100644 --- a/src/PlaIO/Internal/PoolSubgroupReader.cs +++ b/src/PlaIO/Internal/PoolSubgroupReader.cs @@ -1,10 +1,24 @@ +using System.Buffers.Binary; using PlaIO.Model; namespace PlaIO.Internal; +/// Reads the BL-tagged records of one decoded pool. A mode-2 payload is an LZ token stream like a mode-2 +/// block payload; its back-references reach into the pool stream — the reconstruction of every preceding pool of the +/// document (each subgroup's header, raw payloads as they are, zero-mask and mode-2 payloads as their full decodes, +/// concatenated in pool order), followed by this pool's own reconstruction so far. The window keeps only its tail: a +/// back-reference distance is a u16, so nothing reaches further back than bytes and the +/// memory stays constant in the size of the file. internal static class PoolSubgroupReader { - public static IReadOnlyList Read(byte[] pool) + /// The window tail kept for back-references: the largest distance the format can name. + private const int WindowTail = 1 << 16; + + /// Walks one decoded pool: parses each BL-tagged record, decodes its payload against + /// , and appends the record's contribution to the window — its header bytes and its + /// payload exactly once — so the following subgroups can reference it. A truncated zero-mask payload contributes + /// its stored bytes. An undecodable mode-2 payload resets the history. + internal static IReadOnlyList ReadPool(byte[] pool, List window) { var subgroups = new List(); int pos = 0; @@ -20,26 +34,66 @@ public static IReadOnlyList Read(byte[] pool) } ReadOnlySpan payload = pool.AsSpan((int)header.PayloadOffset, (int)header.PackedSize); + ReadOnlySpan headerBytes = pool.AsSpan(pos, (int)header.PayloadOffset - pos); byte[] data; bool partial; - switch (header.Mode) + if (header.Mode == PlaBlockMode.Lz) + { + // The LZ decoder appends every produced byte to the window itself, so the header goes in first and + // the payload's contribution is made exactly once — inside DecodeLz. + window.AddRange(headerBytes); + (data, partial) = DecodeLz(payload, header, window); + } + else { - case PlaBlockMode.Raw: + if (header.Mode == PlaBlockMode.Raw) + { data = payload.ToArray(); partial = false; - break; - case PlaBlockMode.ZeroMask: + } + else + { data = new byte[header.UnpackedSize]; PayloadDecoder.DecodeZeroMask(payload, data, out _, out partial); - break; - default: - data = []; - partial = true; - break; + } + window.AddRange(headerBytes); + // A truncated zero-mask literal leaves the rest of its buffer zero-filled; the window takes the raw + // bytes instead, because that is what the saved stream addresses. + window.AddRange(partial ? payload.ToArray() : data); } subgroups.Add(new PoolSubgroup(header, data, partial)); + if (window.Count > 4 * WindowTail) window.RemoveRange(0, window.Count - WindowTail); pos = (int)header.End; } return subgroups.AsReadOnly(); } + + /// Decodes one mode-2 subgroup payload. A 13-byte header — a u32, the marker 0x47 at +4, then the packed + /// payload length at +5 (the length including the header) and the unpacked size at +9 — precedes the token stream; + /// without it the payload starts with the file block's 9-byte stream header or with the tokens themselves. + /// Returns the declared unpacked buffer with a zero tail when the stream produces less than declared (partial), + /// or empty data with partial set when the stream does not decode at all. The window receives the payload's + /// contribution exactly once: the decoder appends the produced bytes, this method adds the declared tail of a + /// buffer block. A failed stream resets the history so later references cannot reach across the missing output. + private static (byte[] Data, bool Partial) DecodeLz(ReadOnlySpan payload, PlaBlock header, List window) + { + bool hasPoolHeader = payload.Length > 13 && payload[4] == 0x47 + && BinaryPrimitives.ReadUInt32LittleEndian(payload[5..]) == (uint)header.PackedSize + && BinaryPrimitives.ReadUInt32LittleEndian(payload[9..]) == (uint)header.UnpackedSize; + ReadOnlySpan body = hasPoolHeader ? payload[13..] : payload; + + var output = new byte[header.UnpackedSize]; + try + { + LzPayloadDecoder.Decode(body, output, window, header.Offset, out int produced); + if (produced < header.UnpackedSize) + window.AddRange(new byte[(int)(header.UnpackedSize - produced)]); // the buffer space stays addressed + return (output, produced < header.UnpackedSize); + } + catch (InvalidDataException) + { + window.Clear(); + return ([], true); + } + } } diff --git a/src/PlaIO/Model/CompressedPool.cs b/src/PlaIO/Model/CompressedPool.cs index cf60aa1..0ee9494 100644 --- a/src/PlaIO/Model/CompressedPool.cs +++ b/src/PlaIO/Model/CompressedPool.cs @@ -8,15 +8,18 @@ public sealed class CompressedPool { private readonly PlaDocument _document; - internal CompressedPool(PlaDocument document, PoolRange range) + internal CompressedPool(PlaDocument document, PoolRange range, int index) { _document = document; + Index = index; Offset = range.Offset; End = range.End; TotalDecompressed = range.UnpackedSize; BlockCount = range.FrameCount; } + internal int Index { get; } + /// The file offset of the pool marker. public long Offset { get; } @@ -34,8 +37,13 @@ internal CompressedPool(PlaDocument document, PoolRange range) /// The owning document is disposed. public byte[] Decode() => _document.DecodePool(Offset); - /// Decodes the pool and reads BL-tagged records in pool order. + /// Decodes the pool and reads BL-tagged records in pool order. A mode-2 payload is an LZ token stream + /// whose back-references reach into the pool stream — the reconstruction of every preceding pool of the document + /// and of this pool before the record — so the pools are decoded in order until this one and the cost of the call + /// grows with the size of the file. Reading the pools in file order advances one shared window, so every pool + /// decodes once; a read that names an earlier pool rebuilds the window. An unreadable preceding pool resets + /// the history, and a subgroup that references missing bytes returns empty data with Partial set. /// The pool does not decode. /// The owning document is disposed. - public IReadOnlyList ReadSubgroups() => PoolSubgroupReader.Read(Decode()); + public IReadOnlyList ReadSubgroups() => _document.ReadPoolSubgroups(this); } diff --git a/src/PlaIO/Model/PoolSubgroup.cs b/src/PlaIO/Model/PoolSubgroup.cs index a19ea7c..db9e4a9 100644 --- a/src/PlaIO/Model/PoolSubgroup.cs +++ b/src/PlaIO/Model/PoolSubgroup.cs @@ -33,7 +33,7 @@ internal PoolSubgroup(PlaBlock header, byte[] data, bool partial) /// The object GUID when present in the header. public Guid? ObjectId { get; } - /// The decoded payload. Mode 2 returns empty data pending a supported decoder. + /// The decoded payload. Mode 2 returns empty data when its stream cannot be decoded. public byte[] Data { get; } /// True when decoding is unavailable or the zero-mask stream ends inside a literal group. diff --git a/src/PlaIO/PlaDocument.cs b/src/PlaIO/PlaDocument.cs index 3f59e20..15abbc9 100644 --- a/src/PlaIO/PlaDocument.cs +++ b/src/PlaIO/PlaDocument.cs @@ -13,6 +13,7 @@ public sealed class PlaDocument : IDisposable private readonly bool _leaveOpen; private readonly List _blocks; private readonly PlaReaderOptions _options; + private IReadOnlyList? _pools; private bool _disposed; private PlaDocument(Stream stream, bool leaveOpen, long length, FdbHeader header, List blocks, PlaReaderOptions options) @@ -212,11 +213,14 @@ public IReadOnlyList FindDirectories() return found.AsReadOnly(); } - /// Finds compressed pools whose marker and frame headers parse, outside indexed block payloads. + /// Finds compressed pools whose marker and frame headers parse, outside indexed block payloads. The first + /// call scans the file; later calls return the cached list, so the pool objects stay identical. public IReadOnlyList FindCompressedPools() { ObjectDisposedException.ThrowIf(_disposed, this); - return PoolReader.Find(_stream, Length, Blocks).Select(range => new CompressedPool(this, range)).ToList().AsReadOnly(); + if (_pools is null) + _pools = PoolReader.Find(_stream, Length, Blocks).Select((range, index) => new CompressedPool(this, range, index)).ToList().AsReadOnly(); + return _pools; } internal byte[] DecodePool(long offset) @@ -225,6 +229,45 @@ internal byte[] DecodePool(long offset) return PoolReader.Decode(_stream, Length, offset, _options.MaxDecodedPoolBytes); } + /// The window that decoding builds while the pools are read in order: + /// the tail of the pool-stream reconstruction up to the pool with index (that + /// pool excluded). Reading the pools in file order advances the window, so every pool decodes once; a read that + /// names an earlier pool rebuilds the window from the start. + private List? _poolWindow; + private int _poolWindowThrough; + + /// Reads the subgroups of one pool of this document, decoding the pool stream up to it (see + /// ). A preceding pool that fails to decode resets the + /// history. Subgroups of the named pool can still use bytes decoded after that gap. + internal IReadOnlyList ReadPoolSubgroups(CompressedPool pool) + { + ObjectDisposedException.ThrowIf(_disposed, this); + var pools = FindCompressedPools(); + int target = pool.Index; + if ((uint)target >= (uint)pools.Count || !ReferenceEquals(pools[target], pool)) + throw new ArgumentException("The pool is not one of the compressed pools of this document.", nameof(pool)); + + if (_poolWindow is null || target < _poolWindowThrough) + { + _poolWindow = new List(); + _poolWindowThrough = 0; + } + for (; _poolWindowThrough < target; _poolWindowThrough++) + { + try + { + PoolSubgroupReader.ReadPool(pools[_poolWindowThrough].Decode(), _poolWindow); + } + catch (InvalidDataException) + { + _poolWindow.Clear(); + } + } + var subgroups = PoolSubgroupReader.ReadPool(pools[target].Decode(), _poolWindow); + _poolWindowThrough = target + 1; + return subgroups; + } + /// Releases the stream unless the document was opened with leaveOpen. public void Dispose() { diff --git a/tests/PlaIO.Tests/PoolSubgroupTests.cs b/tests/PlaIO.Tests/PoolSubgroupTests.cs index c769ff5..a0f19a9 100644 --- a/tests/PlaIO.Tests/PoolSubgroupTests.cs +++ b/tests/PlaIO.Tests/PoolSubgroupTests.cs @@ -49,6 +49,203 @@ public void LzSubgroupReportsPartialWithEmptyData() Assert.True(record.Partial); } + [Fact] + public void LzSubgroupDecodesAgainstAnEarlierPool() + { + // Pool 1: one raw subgroup "ABCDEFGH"; its reconstruction in the pool stream is the 13-byte + // header followed by the payload, so "ABCD" starts at offset 13 of the window. + byte[] first = Synthetic.Block(PlaBlockMode.Raw, "ABCDEFGH"u8.ToArray()); + // Pool 2: one mode-2 subgroup. Its payload starts with the pool header [u32][0x47][u32 packed][u32 unpacked] + // and the token stream emits the literals XY, then a match of length 4. The subgroup's own 17-byte header is + // already part of the window when its stream decodes, so the window ends at 21 + 17 + 2 = 40 and the distance + // 40 - 13 = 27 reaches "ABCD" of pool 1. + byte[] tokens = [0x20, (byte)'X', (byte)'Y', 0x00, 0x1B, 0x04]; + byte[] payload = PoolLzPayload(tokens, unpacked: 6); + byte[] second = Synthetic.Block(PlaBlockMode.Lz, payload, unpacked: 6); + using var doc = OpenPools(first, second); + + var record = Assert.Single(doc.FindCompressedPools()[1].ReadSubgroups()); + Assert.Equal(PlaBlockMode.Lz, record.Mode); + Assert.Equal("XYABCD"u8.ToArray(), record.Data); + Assert.False(record.Partial); + } + + [Fact] + public void ALaterLzSubgroupMatchesTheDecodedOutputOfAnEarlierOneExactlyOnce() + { + // Pool 1: raw "ABCDEFGH" (13-byte header + 8 payload = 21 bytes of window). + byte[] first = Synthetic.Block(PlaBlockMode.Raw, "ABCDEFGH"u8.ToArray()); + // Pool 2, subgroup 1: mode 2 emitting the literals WXYZ. Its 17-byte header plus the 4 produced bytes end + // the window at 21 + 17 + 4 = 42, with WXYZ at 38..41. + byte[] firstTokens = [0x40, (byte)'W', (byte)'X', (byte)'Y', (byte)'Z']; + byte[] firstLz = Synthetic.Block(PlaBlockMode.Lz, PoolLzPayload(firstTokens, unpacked: 4), unpacked: 4); + // Pool 2, subgroup 2: mode 2 matching length 4. The window at its match is 42 bytes of content plus the + // subgroup's own 17-byte header (the header joins the window before the stream decodes), so the distance + // 59 - 38 = 21 lands on WXYZ only when the output of subgroup 1 entered the window exactly once. A + // duplicated contribution shifts the distance onto other bytes, and the match returns wrong data while + // still reporting a complete decode. + byte[] secondTokens = [0x00, 0x00, 0x15, 0x04]; + byte[] secondLz = Synthetic.Block(PlaBlockMode.Lz, PoolLzPayload(secondTokens, unpacked: 4), unpacked: 4); + using var doc = OpenPools(first, Synthetic.Concat(firstLz, secondLz)); + + var records = doc.FindCompressedPools()[1].ReadSubgroups(); + Assert.Equal(2, records.Count); + Assert.Equal("WXYZ"u8.ToArray(), records[0].Data); + Assert.Equal("WXYZ"u8.ToArray(), records[1].Data); + Assert.False(records[1].Partial); + } + + [Fact] + public void ATruncatedZeroMaskSubgroupContributesItsRawBytesToTheWindow() + { + // Pool 1: raw "ABCD" (13 + 4 = 17 bytes of window, "ABCD" at 13..16). + byte[] first = Synthetic.Block(PlaBlockMode.Raw, "ABCD"u8.ToArray()); + // Pool 2, subgroup 1: a zero-mask subgroup whose single mask byte 0x80 starts a literal that the payload + // never delivers — the decode reports partial and the window takes the one raw payload byte, not the + // zero-filled remainder of the declared buffer. + byte[] truncated = Synthetic.Block(PlaBlockMode.ZeroMask, [0x80], unpacked: 8); + // Pool 2, subgroup 2: a match of length 4 at distance 52 - 13 = 39 (35 bytes of content plus the + // subgroup's own 17-byte header), which reaches "ABCD" of pool 1 only when the truncated subgroup + // contributed its 1 raw byte (17 + 17 + 1 = 35); a zero-filled contribution of 8 bytes shifts the + // distance onto zeros. + byte[] tokens = [0x00, 0x00, 0x27, 0x04]; + byte[] match = Synthetic.Block(PlaBlockMode.Lz, PoolLzPayload(tokens, unpacked: 4), unpacked: 4); + using var doc = OpenPools(first, Synthetic.Concat(truncated, match)); + + var records = doc.FindCompressedPools()[1].ReadSubgroups(); + Assert.Equal(2, records.Count); + Assert.True(records[0].Partial); + Assert.Equal("ABCD"u8.ToArray(), records[1].Data); + Assert.False(records[1].Partial); + } + + [Fact] + public void APoolThatDoesNotDecodeDoesNotBlockLaterPools() + { + // Pool 1: structurally valid framing whose compressed frame fails inside the QuickLZ decode, so the pool is + // found but does not decode. Pool 2 is a plain raw pool and must still be readable. + byte[] goodPool = StoredPool(Synthetic.Block(PlaBlockMode.Raw, "sample"u8.ToArray())); + using var doc = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(UnreadablePool(), goodPool))); + + var pools = doc.FindCompressedPools(); + Assert.Equal(2, pools.Count); + Assert.Throws(() => pools[0].ReadSubgroups()); + var record = Assert.Single(pools[1].ReadSubgroups()); + Assert.Equal("sample"u8.ToArray(), record.Data); + } + + [Fact] + public void APoolOverTheCapCannotSubstituteHistoryFromAnOlderPool() + { + byte[] first = StoredPool(Synthetic.Block(PlaBlockMode.Raw, "ABCD"u8.ToArray())); + byte[] excluded = StoredPool(Synthetic.Block(PlaBlockMode.Raw, "12345WXYZ"u8.ToArray())); + byte[] match = StoredPool(Synthetic.Block(PlaBlockMode.Lz, [0, 0, 21, 4], unpacked: 4)); + byte[] knownSuffix = StoredPool(Synthetic.Block(PlaBlockMode.Raw, "EFGH"u8.ToArray())); + byte[] file = Synthetic.Fdb(first, excluded, match, match, knownSuffix, match); + using var unlimited = PlaDocument.Open(new MemoryStream(file)); + using var limited = PlaDocument.Open(new MemoryStream(file), leaveOpen: false, + options: new PlaReaderOptions { MaxDecodedPoolBytes = 21 }); + + Assert.Equal("WXYZ"u8.ToArray(), Assert.Single(unlimited.FindCompressedPools()[2].ReadSubgroups()).Data); + var pools = limited.FindCompressedPools(); + for (int index = 2; index <= 3; index++) + { + var record = Assert.Single(pools[index].ReadSubgroups()); + Assert.True(record.Partial); + Assert.Empty(record.Data); + } + var recovered = Assert.Single(pools[5].ReadSubgroups()); + Assert.False(recovered.Partial); + Assert.Equal("EFGH"u8.ToArray(), recovered.Data); + } + + [Fact] + public void FailedTargetReadDoesNotReplayPreviouslyDecodedPools() + { + byte[] first = StoredPool(Synthetic.Block(PlaBlockMode.Raw, "ABCD"u8.ToArray())); + byte[] match = StoredPool(Synthetic.Block(PlaBlockMode.Lz, [0, 0, 38, 4], unpacked: 4)); + using var stream = new CountingStream(Synthetic.Fdb(first, UnreadablePool(), match)); + using var doc = PlaDocument.Open(stream); + + var pools = doc.FindCompressedPools(); + stream.Watch(pools.Select(pool => pool.Offset)); + Assert.Throws(() => pools[1].ReadSubgroups()); + + var record = Assert.Single(pools[2].ReadSubgroups()); + Assert.True(record.Partial); + Assert.Empty(record.Data); + Assert.Equal(1, stream.TimesRead(pools[0].Offset)); + } + + [Fact] + public void ReadingThePoolsInOrderDecodesEachPoolOnce() + { + // Eight raw pools; a full pass reads every pool's subgroups in file order. The counting stream counts how + // often each pool header is read (every decode of a pool starts by reading its 32-byte header), so the test + // pins the shared window: N pools decode N times, not N(N+1)/2 = 36 times as a per-call rebuild would. + const int count = 8; + byte[] file = Synthetic.Fdb(Enumerable.Range(0, count).Select(i => + { + byte[] content = Synthetic.Block(PlaBlockMode.Raw, [(byte)i]); + return Synthetic.QuickLzPool(((uint)content.Length, + Synthetic.QuickLzFrame(content, content.Length, flags: 0x46))); + }).ToArray()); + var counter = new CountingStream(file); + using var doc = PlaDocument.Open(counter); + + var pools = doc.FindCompressedPools(); + Assert.Equal(count, pools.Count); + counter.Watch(pools.Select(p => p.Offset)); // the find scan is over; count from here + + foreach (var pool in pools) pool.ReadSubgroups(); + + Assert.Equal(count, counter.Total); + Assert.All(pools, pool => Assert.Equal(1, counter.TimesRead(pool.Offset))); + } + + /// A stream that counts how often a seek lands on one of the watched offsets — every decode of a pool + /// seeks to the pool marker to read its header first. + private sealed class CountingStream(byte[] data) : MemoryStream(data) + { + private readonly HashSet _watch = []; + private readonly Dictionary _counts = []; + + public void Watch(IEnumerable offsets) + { + foreach (long offset in offsets) _watch.Add(offset); + } + + public int Total => _counts.Values.Sum(); + + public int TimesRead(long offset) => _counts.GetValueOrDefault(offset); + + public override long Seek(long offset, SeekOrigin origin) + { + if (origin == SeekOrigin.Begin && _watch.Contains(offset)) + _counts[offset] = _counts.GetValueOrDefault(offset) + 1; + return base.Seek(offset, origin); + } + } + + [Fact] + public void LzSubgroupWithTheBlockStreamHeaderDecodesWithoutAPoolHeader() + { + // A mode-2 payload may instead start with the file block's 9-byte stream header, which the LZ decoder + // recognises itself; here 6 literals stand alone, so nothing is referenced. + byte[] tokens = [0x60, (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F']; + byte[] payload = new byte[9 + tokens.Length]; + payload[0] = 0x47; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(1), (uint)payload.Length); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(5), 6); + tokens.CopyTo(payload, 9); + byte[] subgroup = Synthetic.Block(PlaBlockMode.Lz, payload, unpacked: 6); + using var doc = OpenPool(subgroup); + + var record = Assert.Single(Assert.Single(doc.FindCompressedPools()).ReadSubgroups()); + Assert.Equal("ABCDEF"u8.ToArray(), record.Data); + Assert.False(record.Partial); + } + [Fact] public void ShortHeaderCandidateDoesNotHideLaterRecord() { @@ -88,6 +285,50 @@ public void ReadsSubgroupsFromSavedFiles() if (pools == 0) throw TestFiles.Missing("FDB fixture with nonempty QuickLZ pools"); } - private static PlaDocument OpenPool(byte[] data) => PlaDocument.Open(new MemoryStream(Synthetic.Fdb( - Synthetic.QuickLzPool(((uint)data.Length, Synthetic.QuickLzFrame(data, data.Length, flags: 0x46)))))); + [SkippableFact] + public void EveryLzSubgroupOfSavedFilesDecodes() + { + using var corpus = new SampleCorpus(); + long mode2 = 0, decoded = 0; + foreach (var sample in corpus.Fdb) + { + foreach (var pool in sample.Document.FindCompressedPools()) + { + foreach (var record in pool.ReadSubgroups()) + { + if (record.Mode != PlaBlockMode.Lz) continue; + mode2++; + if (!record.Partial && record.Data.Length > 0) decoded++; + } + } + } + if (mode2 == 0) throw TestFiles.Missing("FDB fixture with mode-2 pool subgroups"); + Assert.True(decoded >= 0.99 * mode2, $"{decoded} of {mode2} mode-2 subgroups decode"); + } + + private static PlaDocument OpenPool(byte[] data) => OpenPools(data); + + private static PlaDocument OpenPools(params byte[][] data) + { + byte[][] pools = data.Select(StoredPool).ToArray(); + return PlaDocument.Open(new MemoryStream(Synthetic.Fdb(pools))); + } + + private static byte[] StoredPool(byte[] content) => Synthetic.QuickLzPool( + ((uint)content.Length, Synthetic.QuickLzFrame(content, content.Length, flags: 0x46))); + + private static byte[] UnreadablePool() => Synthetic.QuickLzPool( + (8, Synthetic.QuickLzFrame([1, 0, 0, 0x80, 0xF1, 0xFF], 8, flags: 0x45))); + + /// The 13-byte mode-2 pool header: a u32, the 0x47 marker, the packed payload length (including the + /// header) and the unpacked size, followed by the token stream. + private static byte[] PoolLzPayload(byte[] tokens, int unpacked) + { + byte[] payload = new byte[13 + tokens.Length]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(5), (uint)payload.Length); + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(payload.AsSpan(9), (uint)unpacked); + payload[4] = 0x47; + tokens.CopyTo(payload, 13); + return payload; + } }