diff --git a/CHANGELOG.md b/CHANGELOG.md
index b307db4..ba46449 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,16 @@ API between minor releases.
contents), and the `container-only` diagnostic. The project is `IsPackable=false` and is not published; it ships on a
`PlaIO` release tag when the reader decodes elements and geometry. See `docs/scene.md`.
+- `PlaDocument.ReadPayload` decodes mode 2 (LZ) payloads. A payload may start with a 9-byte stream header with a
+ 0x46 or 0x47 marker and matching packed and unpacked sizes. The token stream produces the block's declared unpacked size and may reference the
+ decompressed output of any preceding block of the file, so `ReadPayload` for a mode 2 block decodes the file from the
+ start into one global window; the cost of the call grows with the size of the file. Preceding blocks that do not
+ decode (false entries of the scan) are skipped and leave the window unchanged. A final match may omit the length byte
+ (the match length is the remainder of the output). Some blocks declare an output buffer larger than the stream
+ produces: the stream simply ends with the body, the produced bytes fill the head of the buffer and the tail stays
+ zero — the global window holds the buffer space, so directory positions keep addressing it. A back-reference beyond
+ the decoded stream throws `InvalidDataException`.
+
### Changed
- The release workflow follows the IOExtend release order: the NuGet packages are pushed before the GitHub release is
@@ -21,6 +31,9 @@ API between minor releases.
repeatable), and a tag whose version contains a hyphen is published as a prerelease. The changelog section for the
version is checked before anything is published.
+- `PlaDocument.ReadPayload` no longer throws `NotSupportedException` for mode 2 blocks: all three storage modes
+ (raw, zero mask, LZ) decode now.
+
## [0.1.0] - 2026-11-12
### Added
diff --git a/README.md b/README.md
index 3f1877c..2a9e2c2 100644
--- a/README.md
+++ b/README.md
@@ -16,8 +16,8 @@ release tag when the reader decodes elements and geometry (see [the scene adapte
- Detects the file kind from the first bytes: the container shared by `.pla` and `.pln`, or `.bimx`.
- Reads the container header and exposes its fields as raw values where their meaning is not documented.
- Indexes the `BL` and `DY` blocks of the container in one forward scan, without loading the whole file.
-- Decodes block payloads stored raw (mode 0) or with zero masks (mode 1). Mode 2 (LZ) payloads are recognised but not
- decoded, and some mode 1 blocks in real files do not decode (see [Limitations](#limitations)).
+- Decodes block payloads stored raw (mode 0), with zero masks (mode 1), or with LZ compression (mode 2).
+ Some mode 1 blocks in real files do not decode (see [Limitations](#limitations)).
- Searches raw blocks for object directories (30-byte records of class number, position, count and object GUID).
- Reads the PNG cover image at the start of a `.bimx` file and reports where the rest of the content begins.
@@ -94,7 +94,6 @@ using (var document = PlaDocument.Open("project.pln"))
foreach (var block in document.Blocks)
{
- if (block.Mode == PlaBlockMode.Lz) continue; // recognised, not decoded
try
{
byte[] payload = document.ReadPayload(block);
@@ -114,9 +113,9 @@ using (var bimx = BimxDocument.Open("model.bimx"))
File.WriteAllBytes("cover.png", bimx.ReadCover());
```
-`PlaFile.DetectKind` tells the kinds apart before a file is opened. `ReadPayload` throws `NotSupportedException` for a
-mode 2 (LZ) block and `InvalidDataException` for a payload that does not decode to its declared size. The library never
-writes to the console and has no diagnostic output; problems are reported as exceptions.
+`PlaFile.DetectKind` tells the kinds apart before a file is opened. `ReadPayload` throws `InvalidDataException` for a
+payload that does not decode. Each mode 2 read rebuilds the decoded history of preceding blocks. The library reports
+errors through exceptions.
See the [public API](docs/public-api.md) for the supported surface and [dependencies](docs/dependencies.md) for package
details.
@@ -208,7 +207,6 @@ included in the repository. Files from other versions are not tested.
## Limitations
- Version 0.1.0 is a preview. The API can change before 1.0.
-- Mode 2 (LZ) payloads are recognised but not decoded; `ReadPayload` throws `NotSupportedException` for them.
- The meaning of the `pos` and `count` fields of a directory record is not known, so the addressing of objects is not
supported. Class numbers are not mapped to class names, and the contents of objects (elements, parameters, geometry)
are not read.
diff --git a/docs/cli.md b/docs/cli.md
index 3b6a4c2..21a8e13 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -34,7 +34,7 @@ The limits are fixed; the tool has no option to change them.
| --- | --- |
| At most 1048576 (2^20) blocks in one index | A file with more blocks is rejected with exit code 2. |
| Unpacked size of a block at most 2^28 bytes and at most 300 times its packed size plus 65536 | A block header outside these bounds is not taken as a block; the scan moves on. |
-| Mode 2 (LZ) payloads | Recognised and listed, but not decoded. No command decodes payloads; `directory` reads raw blocks only. |
+| Mode 2 (LZ) payloads | Listed by `blocks`. The CLI `directory` command reads raw blocks only. |
| Object directories | Searched in raw (mode 0) blocks of at least 1920 bytes, at most one per block. A directory needs at least 64 records whose extents mostly abut. The run that is reported is an estimate and can be shorter than the real directory. |
The meaning of `pos` and `count` in a directory record is not known, class numbers are not mapped to class names and the
@@ -153,6 +153,6 @@ case $? in
2) echo "the file cannot be read, or directories.json cannot be written" ;;
esac
-# count the blocks whose payload is not decoded (mode 2)
+# count the mode 2 blocks
plaio blocks project.pln | awk -F '\t' 'NR > 1 && $8 == "Lz"' | wc -l
```
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 209dc0f..a914961 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -39,7 +39,6 @@ using (var doc = PlaDocument.Open("project.pln"))
foreach (PlaBlock block in doc.Blocks)
{
- if (block.Mode == PlaBlockMode.Lz) continue; // recognised, but ReadPayload throws NotSupportedException
try
{
byte[] payload = doc.ReadPayload(block);
@@ -64,10 +63,10 @@ using (var bimx = BimxDocument.Open("model.bimx"))
Use `PlaFile.DetectKind` to tell an FDB container (`.pla`, `.pln`) from a `.bimx` file before opening it.
-The library never writes to the console and has no diagnostic writer. A file it cannot read is reported by an exception: `InvalidDataException` for data that is not the expected kind or is cut short, `NotSupportedException` for a mode 2 payload, and the usual I/O exceptions for a file that cannot be opened.
+The library never writes to the console and has no diagnostic writer. A file it cannot read is reported by an exception: `InvalidDataException` for data that is not the expected kind, does not decode to its declared size, or is cut short, and the usual I/O exceptions for a file that cannot be opened.
The supported surface is listed in [Public API](public-api.md); every type is in the [API reference](api/PlaIO.yml).
## Status
-PlaIO 0.1.0 is a preview and the API can change before 1.0. It does not decode mode 2 (LZ) payloads, does not interpret the position and count of directory records, does not map class numbers to class names and does not read object contents. In real files a small share of mode 1 blocks does not decode to its declared size, and `ReadPayload` throws `InvalidDataException` for them. The block index is found by scanning and may contain false entries.
+PlaIO 0.1.0 is a preview and the API can change before 1.0. It does not interpret the position and count of directory records, does not map class numbers to class names and does not read object contents. In real files a small share of mode 1 blocks does not decode to its declared size, and `ReadPayload` throws `InvalidDataException` for them. The block index is found by scanning and may contain false entries.
diff --git a/docs/index.md b/docs/index.md
index 4394409..1cd0954 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -8,7 +8,7 @@ PlaIO is a .NET library and command line tool that reads the container structure
- Detects the file kind from the first bytes of a file.
- Reads the header of the FDB container that `.pla` and `.pln` files share, and builds an index of its blocks.
-- Decodes block payloads stored raw (mode 0) or zero-masked (mode 1). Mode 2 (LZ) payloads are recognised but not decoded, and a small share of mode 1 blocks in real files does not decode to its declared size.
+- Decodes raw (mode 0), zero-mask (mode 1), and LZ (mode 2) payloads. A small share of mode 1 blocks in real files does not decode to its declared size.
- Searches raw blocks for object directories and returns their records as stored (class number, position, count, GUID).
- Reads the PNG cover image of a `.bimx` file.
diff --git a/docs/public-api.md b/docs/public-api.md
index f3e6b94..3f174eb 100644
--- a/docs/public-api.md
+++ b/docs/public-api.md
@@ -21,11 +21,11 @@ The `PlaIO` package is the supported surface listed here; every public type is i
| `PlaDocument.Length` | Length of the file in bytes. |
| `PlaDocument.Header` | The `FdbHeader`. |
| `PlaDocument.Blocks` | The block index in file order, found by scanning from offset 32. No on-disk block map is known, so completeness is not claimed. The scan can take a byte run for a block header, so the index may contain false entries. In real files a small share of mode 1 blocks does not decode to its declared size, and `ReadPayload` throws `InvalidDataException` for them. |
-| `PlaDocument.ReadPayload(PlaBlock block)` | The decoded payload of a block of this document. Decodes mode 0 and mode 1. Throws `NotSupportedException` for mode 2 (LZ), `InvalidDataException` when a mode 1 payload does not decode to the declared size or the file is cut short, and `ArgumentException` when the block is not from this document. |
+| `PlaDocument.ReadPayload(PlaBlock block)` | The decoded payload of a block of this document. Decodes all three storage modes: raw (mode 0), zero masks (mode 1) and the LZ token stream (mode 2). A mode 2 payload may start with a 9-byte stream header with a 0x46 or 0x47 marker and matching packed and unpacked sizes. The token stream produces the block's declared unpacked size — some blocks declare a buffer larger than the stream produces, the tail of the buffer stays zero — and may reference the output of any preceding block, so the payload is produced by decoding every preceding block of the file in order into one global window; the cost of the call grows with the size of the file. Preceding blocks that do not decode (false entries of the scan) are skipped and leave the window unchanged. Throws `InvalidDataException` when a back-reference reaches beyond the decoded stream or the file is cut short, and `ArgumentException` when the block is not from this document. |
| `PlaDocument.FindDirectories()` | Searches every raw (mode 0) block large enough for 64 records of 30 bytes for an object directory, at most one per block. Recomputed on each call; mode 1 payloads are not searched. |
| `PlaDocument.Dispose()` | Releases the stream unless the document was opened with `leaveOpen`. |
| `FdbHeader` | `Size` (64), `LayoutVersion` (u16 at offset 8), `FormatVersion` (u16 at offset 10), `Field12` (u32 at offset 12; meaning not documented), `Raw` (the first min(64, file length) bytes; bytes 32..63 overlap the first block). |
-| `PlaBlockMode` | `Raw` (0), `ZeroMask` (1, flag 0x100), `Lz` (2, flag 0x200; recognised, not decoded). |
+| `PlaBlockMode` | `Raw` (0), `ZeroMask` (1, flag 0x100), `Lz` (2, flag 0x200). |
| `PlaBlock` | One indexed block: `Offset`, `Tag` (`BL` or `DY`), `Id` and `Kind` (raw), `Version` (0 or 1), `Flags` (raw), `SizeClass` (`Flags & 0xF`), `Mode`, `Guid` (present when flag 0x20 is set), `PackedSize`, `UnpackedSize`, `Extra` (present when flag 0x400 is set; raw), `PayloadOffset`, `HeaderLength`, `End`. |
| `ObjectDirectory` | A run of directory records inside a raw block: `Block`, `RecordOffset` (payload offset of the first record), `Phase` (`RecordOffset % 30`), `Records`, `AbuttingPairs`, `OverlappingPairs`, `DuplicatePositions`. The run is an estimate and can be shorter than the real directory: it stops after more than 8 consecutive records without an abutting neighbour. |
| `ObjectDirectoryRecord` | The 30-byte record `[u16 class][u64 pos][u32 count][GUID16]` as `ClassNumber`, `Position`, `Count`, `ObjectId`. The units of position and count are not documented, and the class number is not mapped to a class name. |
diff --git a/src/PlaIO/Internal/LzPayloadDecoder.cs b/src/PlaIO/Internal/LzPayloadDecoder.cs
new file mode 100644
index 0000000..2a15ec3
--- /dev/null
+++ b/src/PlaIO/Internal/LzPayloadDecoder.cs
@@ -0,0 +1,151 @@
+using System.Buffers.Binary;
+
+namespace PlaIO.Internal;
+
+/// Decodes the mode 2 (LZ) token stream of one block payload and appends every produced byte to the window —
+/// the global decompressed stream of the whole file. Back-references reach anywhere inside that stream, including the
+/// output of preceding blocks. Returns the number of body bytes consumed.
+///
+/// A 9-byte stream header has a 0x46 or 0x47 marker and two little-endian sizes matching the packed and
+/// unpacked lengths. The token stream follows the header.
+/// The stream is a chain of sequences. A sequence starts with a token byte: the high nibble is the number of
+/// literal bytes that follow (15 = extended: the following bytes are added while they equal 255). After the literals, if
+/// the output is not complete yet, come the match fields: a 16-bit big-endian distance and a length byte. A distance of 0
+/// emits the match length as zero bytes (RLE); a positive distance copies the match length from that many bytes back in
+/// the global window, byte by byte, so overlapping copies replicate a repeating pattern. The low nibble of the token is
+/// the high byte of the match length, so a match spans up to 4095 bytes (a length byte of 0 with a non-zero high nibble
+/// still means 256). When the output is full the sequence ends; the remaining bytes of the body are slack the writer
+/// reserved and are not consumed.
+/// Two endings depart from the strict scheme. A final match may omit the length byte: the body ends after the
+/// distance, and the match length is the remainder of the output. And some blocks (repeating kinds, sizes near whole
+/// mebibytes) declare an output buffer larger than the stream actually produces: the stream simply ends with the body,
+/// and the real output is what was produced so far. Such a block is detected by retrying with this relaxed ending when
+/// the strict decode runs out of body; the produced count then fills only part of the output and the caller pads the
+/// rest (the directory addresses the buffer space, so the block's contribution to the global window is the declared
+/// size). A back-reference that reaches beyond the decoded stream is always an error.
+///
+internal static class LzPayloadDecoder
+{
+ /// Decodes one mode 2 payload. Returns the consumed source length; receives the
+ /// number of output bytes the stream actually generated (equal to output.Length except for a buffer block).
+ public static int Decode(ReadOnlySpan body, Span output, List window, long blockOffset, out int produced)
+ {
+ var result = DecodeAttempt(body, output, window, blockOffset, bufferMode: false);
+ if (!result.ok)
+ {
+ result = DecodeAttempt(body, output, window, blockOffset, bufferMode: true);
+ if (!result.ok)
+ throw new InvalidDataException($"Mode-2 block at 0x{blockOffset:x}: {result.error}");
+ }
+ produced = result.produced;
+ return result.consumed;
+ }
+
+ private static (bool ok, int consumed, int produced, string error) DecodeAttempt(
+ ReadOnlySpan body, Span output, List window, long blockOffset, bool bufferMode)
+ {
+ int src = 0, o = 0;
+ int windowStart = window.Count;
+ uint declared = (uint)output.Length;
+ if (body.Length > 9 && body[0] is 0x46 or 0x47)
+ {
+ uint firstSize = BinaryPrimitives.ReadUInt32LittleEndian(body[1..]);
+ uint secondSize = BinaryPrimitives.ReadUInt32LittleEndian(body[5..]);
+ if ((firstSize == (uint)body.Length && secondSize == declared) ||
+ (secondSize == (uint)body.Length && firstSize == declared))
+ src = 9;
+ }
+
+ void RollBack()
+ {
+ window.RemoveRange(windowStart, window.Count - windowStart);
+ }
+
+ try
+ {
+ while (o < output.Length)
+ {
+ if (src >= body.Length)
+ {
+ if (bufferMode) break; // the stream simply ends with the body
+ throw new InvalidDataException($"the token stream ends after {o} of {output.Length} output bytes.");
+ }
+ int token = body[src++];
+ int litLen = token >> 4;
+ if (litLen == 15)
+ {
+ byte x;
+ do
+ {
+ if (src >= body.Length)
+ {
+ if (bufferMode) return End(o, src, output.Length); // the stream simply ends with the body
+ throw new InvalidDataException("the literal length extension runs past the payload.");
+ }
+ x = body[src++];
+ litLen += x;
+ }
+ while (x == 255 && src < body.Length);
+ }
+ int litTake = Math.Min(litLen, body.Length - src);
+ int litEnd = Math.Min(o + litLen, output.Length);
+ litTake = Math.Min(litTake, litEnd - o);
+ for (int i = 0; i < litTake; i++, o++)
+ {
+ byte v = body[src++];
+ output[o] = v;
+ window.Add(v);
+ }
+ if (o >= output.Length)
+ return End(o, src, output.Length); // trailing literals completed the block; the body tail is slack
+ if (litTake < litLen && src >= body.Length)
+ {
+ // the declared literal run reaches past the body
+ if (bufferMode) return End(o, src, output.Length); // the stream simply ends with the body
+ throw new InvalidDataException($"the literal run of {litLen} bytes reaches past the payload at {src} ({o} of {output.Length} output bytes).");
+ }
+ if (src + 2 > body.Length)
+ {
+ if (bufferMode) return End(o, src, output.Length); // the stream simply ends with the body
+ throw new InvalidDataException($"the distance of the sequence at {src - 1} runs past the payload ({o} of {output.Length} output bytes).");
+ }
+ int dist = (body[src] << 8) | body[src + 1];
+ src += 2;
+ int matchLen;
+ if (src >= body.Length)
+ {
+ // final match without a length byte: the match length is the remainder of the output
+ matchLen = output.Length - o;
+ }
+ else
+ {
+ int lenByte = body[src++];
+ matchLen = lenByte == 0 ? 256 : (((token & 0xF) << 8) | lenByte);
+ }
+ if (o + matchLen > output.Length)
+ matchLen = output.Length - o; // the final match is clipped at the declared size
+ if (dist == 0)
+ {
+ for (int i = 0; i < matchLen; i++, o++) { output[o] = 0; window.Add(0); }
+ continue;
+ }
+ if (dist > window.Count)
+ throw new InvalidDataException($"the back-reference distance {dist} exceeds the decoded stream ({window.Count} bytes).");
+ for (int i = 0; i < matchLen; i++, o++)
+ {
+ byte v = window[window.Count - dist];
+ output[o] = v;
+ window.Add(v);
+ }
+ }
+ return End(o, src, output.Length);
+ }
+ catch (InvalidDataException e)
+ {
+ RollBack();
+ return (false, src, o, e.Message);
+ }
+
+ static (bool, int, int, string) End(int o, int src, int declared) => (true, src, o, null!);
+ }
+}
diff --git a/src/PlaIO/PlaDocument.cs b/src/PlaIO/PlaDocument.cs
index 4cc7ad1..8c8719f 100644
--- a/src/PlaIO/PlaDocument.cs
+++ b/src/PlaIO/PlaDocument.cs
@@ -2,7 +2,7 @@
namespace PlaIO;
-/// An open FDB container (.pla or .pln): the header, the block index and payload decoding for modes 0 and 1.
+/// An open FDB container (.pla or .pln): the header, the block index and payload decoding for modes 0, 1 and 2.
/// The file is never loaded whole; payloads are read on request. Not thread-safe.
public sealed class PlaDocument : IDisposable
{
@@ -76,8 +76,11 @@ public static PlaDocument Open(Stream stream, bool leaveOpen = false)
}
/// The decoded payload of a block of this document.
- /// The block uses mode 2 ().
- /// A mode-1 stream does not decode to the declared size, or the file is cut
+ /// Reading a mode 2 () block decodes every block of the file in order into
+ /// one global window first, because a mode 2 token stream may reference the output of any preceding block; the cost
+ /// of the call therefore grows with the size of the file. A preceding block that does not decode to its declared
+ /// size (a false entry of the scan) is skipped.
+ /// A payload does not decode to its declared size, or the file is cut
/// short.
/// The block is not one of the of this document.
public byte[] ReadPayload(PlaBlock block) => ReadPayload(block, out _);
@@ -120,11 +123,97 @@ internal byte[] ReadPayload(PlaBlock block, out int consumed)
}
return payload;
}
+ case PlaBlockMode.Lz:
+ {
+ // The mode-2 token stream references the decompressed output of all preceding blocks, so the whole
+ // file is decoded from the start and the requested block's output is returned. The cost of a call
+ // therefore grows with the size of the file. A preceding block that does not decode is a scanner
+ // false positive and not part of the real stream, so it is skipped.
+ var window = new List();
+ foreach (var b in _blocks)
+ {
+ if (ReferenceEquals(b, block)) break;
+ TryAppendToWindow(b, window);
+ }
+ var blockPayload = new byte[block.PackedSize];
+ StreamReads.ReadExactlyAt(_stream, block.PayloadOffset, blockPayload, $"the payload of the block at 0x{block.Offset:x}");
+ // Mode 2 (LZ): the token stream produces the declared unpacked size (some blocks declare a buffer
+ // larger than the stream produces — the tail of the buffer stays zero) and may reference the window;
+ // the body tail after the output is complete is writer slack.
+ var output = new byte[block.UnpackedSize];
+ int lzConsumed;
+ try
+ {
+ lzConsumed = LzPayloadDecoder.Decode(blockPayload, output, window, block.Offset, out _);
+ }
+ catch (InvalidDataException e)
+ {
+ throw new InvalidDataException($"Block at 0x{block.Offset:x}: {e.Message}", e);
+ }
+ consumed = lzConsumed;
+ return output;
+ }
default:
- throw new NotSupportedException($"Block at 0x{block.Offset:x} uses payload mode 2 (LZ). Its compression is not documented yet; only modes 0 and 1 can be decoded.");
+ throw new NotSupportedException($"Block at 0x{block.Offset:x} uses an unknown payload mode {block.Mode}.");
}
}
+ /// Appends the decoded payload of one block to the mode-2 global window, or leaves the window unchanged when
+ /// the block does not decode to its declared size (a false entry of the scan is not part of the real stream, so a
+ /// partial decode is rolled back). Returns whether the block was appended.
+ private bool TryAppendToWindow(PlaBlock b, List window)
+ {
+ int before = window.Count;
+ try
+ {
+ AppendToWindow(b, window);
+ return true;
+ }
+ catch (InvalidDataException)
+ {
+ window.RemoveRange(before, window.Count - before);
+ return false;
+ }
+ }
+
+ /// Decodes the whole file once into the global window: the raw payloads, the full zero-mask decodes and the
+ /// mode-2 outputs, in block order. Blocks that do not decode to their declared size (false entries of the scan) are
+ /// skipped and reported in ; the window stays as if they were not there.
+ internal List DecodeGlobalWindow(out IReadOnlyList skipped)
+ {
+ ObjectDisposedException.ThrowIf(_disposed, this);
+ var window = new List();
+ var failed = new List();
+ foreach (var b in _blocks)
+ {
+ if (!TryAppendToWindow(b, window)) failed.Add(b);
+ }
+ skipped = failed.AsReadOnly();
+ return window;
+ }
+
+ /// Appends the decoded payload of one block to the mode-2 global window. Raw payloads are copied as they
+ /// are; a zero-mask payload contributes its full decode; a mode 2 payload is decoded and the decoder appends every
+ /// produced byte. Throws when the block does not decode to its declared size.
+ private void AppendToWindow(PlaBlock b, List window)
+ {
+ if (b.Mode != PlaBlockMode.Lz)
+ {
+ window.AddRange(ReadPayload(b));
+ return;
+ }
+
+ var payload = new byte[b.PackedSize];
+ StreamReads.ReadExactlyAt(_stream, b.PayloadOffset, payload, $"the payload of the block at 0x{b.Offset:x}");
+ // Mode 2 (LZ): the token stream produces the declared unpacked size (some blocks declare a buffer
+ // larger than the stream produces — the tail of the buffer stays zero) and the decoder appends every
+ // produced byte to the window; the body tail after the output is complete is writer slack.
+ var output = new byte[b.UnpackedSize];
+ int produced;
+ LzPayloadDecoder.Decode(payload, output, window, b.Offset, out produced);
+ for (long i = produced; i < b.UnpackedSize; i++) window.Add(0); // the directory addresses the buffer space
+ }
+
/// Searches every raw block large enough for 64 records for an object directory (at most one per block).
/// Computed on each call; reads the raw blocks one at a time. Mode-1 payloads are not searched.
/// The work grows with the total size of the raw blocks: each block gets a linear pre-check at all 30 record
diff --git a/tests/PlaIO.Tests/LzPayloadTests.cs b/tests/PlaIO.Tests/LzPayloadTests.cs
new file mode 100644
index 0000000..7167c15
--- /dev/null
+++ b/tests/PlaIO.Tests/LzPayloadTests.cs
@@ -0,0 +1,218 @@
+using System.Buffers.Binary;
+using Xunit;
+
+namespace PlaIO.Tests;
+
+/// The mode 2 (LZ) payload decode on synthetic containers: literal runs, back-references across
+/// blocks (the global window), overlapping copies, RLE zeros, the length byte conventions and the
+/// trailing slack. The byte sequences are the model verified against real files (see the format spec).
+public class LzPayloadTests
+{
+ [Fact]
+ public void LiteralsAndBackReferencesAcrossBlocks()
+ {
+ // Block A: raw, provides the window. Block B: mode 2, references it.
+ byte[] a = "ABCDEFGH"u8.ToArray();
+ // seq1: token 0x40 (lit 4) "wxyz"; dist 8 -> copies "EFG" (source at 12-8=4)
+ // seq2: token 0x00 (lit 0); dist 0; len 4 -> four zeros (window is now 19 bytes)
+ // seq3: token 0x00 (lit 0); dist 15 -> copies "EFGH" (source at 19-15=4, block A's bytes:
+ // the back-reference reaches across the block boundary into the raw block)
+ // trailing slack: FF FE
+ var lz = Synthetic.Concat(
+ [0x40], "wxyz"u8.ToArray(), [0x00, 0x08], [0x03],
+ [0x00], [0x00, 0x00], [0x04],
+ [0x00], [0x00, 0x0F], [0x04],
+ [0xFF, 0xFE]);
+ byte[] expected = "wxyzEFG\0\0\0\0EFGH"u8.ToArray();
+
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.Raw, a),
+ Synthetic.Block(PlaBlockMode.Lz, lz, unpacked: (uint)expected.Length))));
+
+ var payload = document.ReadPayload(document.Blocks[1]);
+ Assert.Equal(expected, payload);
+ }
+
+ [Fact]
+ public void LengthByteZeroMeans256AndHighNibbleExtendsTheLength()
+ {
+ // seq1: token 0x40 (lit 4) "ABCD"; dist 4, lenByte 4 -> len 4: copies the literals back,
+ // giving "ABCDABCD". seq2: token 0x01 (lit 0, lenHi 1): dist 4, lenByte 0 -> len 256; the
+ // overlapping copy repeats "ABCD" 64 times. seq3: token 0x10 (lit 1) "Z".
+ var lz = Synthetic.Concat(
+ [0x40], "ABCD"u8.ToArray(), [0x00, 0x04], [0x04],
+ [0x01], [0x00, 0x04], [0x00],
+ [0x10], "Z"u8.ToArray());
+ byte[] expected = "ABCDABCD"u8.ToArray();
+ for (int i = 0; i < 64; i++) expected = expected.Concat("ABCD"u8.ToArray()).ToArray();
+ expected = expected.Concat("Z"u8.ToArray()).ToArray();
+
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.Lz, lz, unpacked: (uint)expected.Length))));
+
+ var payload = document.ReadPayload(document.Blocks.Single());
+ Assert.Equal(expected, payload);
+ }
+
+ [Fact]
+ public void OverlappingCopyReplicatesARepeatingPattern()
+ {
+ // window tail "ABCD"; token 0x01 (lit 0, lenHi 1): dist 4, lenByte 45 -> len 0x12D = 301:
+ // the 4-byte pattern repeats with a 1-byte overlap offset... the copy replicates the
+ // pattern; the output length is clipped at the declared size.
+ var lz = Synthetic.Concat(
+ [0x40], "ABCD"u8.ToArray(), [0x00, 0x04], [0x04],
+ [0x01], [0x00, 0x04], [0x2D]);
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.Lz, lz, unpacked: 301))));
+
+ var payload = document.ReadPayload(document.Blocks.Single());
+ Assert.Equal(301, payload.Length);
+ for (int i = 0; i < 301; i++) Assert.Equal("ABCD"[i % 4], (char)payload[i]);
+ }
+
+ [Fact]
+ public void TrailingLiteralsEndTheBlockAndBodyTailIsSlack()
+ {
+ // token 0xF5: litLen 15 + ext byte 5 = 20 literals; no match follows; the body tail (2 bytes) is slack.
+ var lz = Synthetic.Concat(
+ [0xF5, 0x05], "ABCDEFGHIJKLMNOPQRST"u8.ToArray(),
+ [0xDE, 0xAD]);
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.Lz, lz, unpacked: 20))));
+
+ var payload = document.ReadPayload(document.Blocks.Single());
+ Assert.Equal("ABCDEFGHIJKLMNOPQRST"u8.ToArray(), payload);
+ }
+
+ [Fact]
+ public void BackReferenceBeyondTheWindowIsRejected()
+ {
+ // token 0x00 (lit 0); dist 0x0064 = 100 > the window (0 bytes before the first match in this block)
+ var lz = Synthetic.Concat([0x00], [0x00, 0x64], [0x04]);
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.Lz, lz, unpacked: 64))));
+
+ var ex = Assert.Throws(() => document.ReadPayload(document.Blocks.Single()));
+ Assert.Contains("back-reference distance 100", ex.Message);
+ }
+
+ [Fact]
+ public void AStreamEndingWithTheBodyIsABufferBlockEvenWithoutAStreamHeader()
+ {
+ // token 0x40 declares 4 literals; the payload carries only 2 and ends: the stream ends with the
+ // body, so the block decodes as a buffer block and the payload holds the declared buffer.
+ var lz = Synthetic.Concat([0x40], [0x77, 0x78]);
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.Lz, lz, unpacked: 4))));
+
+ var payload = document.ReadPayload(document.Blocks.Single());
+ Assert.Equal(new byte[] { 0x77, 0x78, 0, 0 }, payload);
+ }
+
+ [Theory]
+ [InlineData(0x46)]
+ [InlineData(0x47)]
+ public void StreamHeaderIsSkippedWhenItsMarkerAndSizesMatch(byte marker)
+ {
+ // [u8][u32 body length][u32 unpacked][token stream]: the u32 at offset 1 equals the whole payload length and the
+ // u32 at offset 5 equals the declared size, so the token stream starts after the 9-byte header.
+ var tail = Synthetic.Concat([0x40], "ABCD"u8.ToArray(), [0xFF, 0xFE]);
+ var header = Synthetic.Concat([marker], BitConverter.GetBytes((uint)(9 + tail.Length)), BitConverter.GetBytes(4u));
+ var lz = Synthetic.Concat(header, tail);
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.Lz, lz, unpacked: 4))));
+
+ Assert.Equal("ABCD"u8.ToArray(), document.ReadPayload(document.Blocks.Single()));
+ }
+
+ [Fact]
+ public void LiteralRunWithBothSizesDoesNotBecomeAHeader()
+ {
+ byte[] expected = [10, 0, 0, 0, 9, 0, 0, 0, 42];
+ byte[] lz = Synthetic.Concat([0x90], expected);
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.Lz, lz, unpacked: (uint)expected.Length))));
+
+ Assert.Equal(expected, document.ReadPayload(document.Blocks.Single()));
+ }
+
+ [Fact]
+ public void ShortZeroMaskPredecessorIsNotUsedAsMatchHistory()
+ {
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.ZeroMask, [1, 9], unpacked: 16),
+ Synthetic.Block(PlaBlockMode.Lz, [0, 0, 8, 1], unpacked: 1))));
+
+ Assert.Throws(() => document.ReadPayload(document.Blocks[0]));
+ Assert.Throws(() => document.ReadPayload(document.Blocks[1]));
+ }
+
+ [Fact]
+ public void ReadingLzDoesNotReadZeroMaskWriterSlack()
+ {
+ byte[] data = Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.ZeroMask, new byte[1024 * 1024], unpacked: 1),
+ Synthetic.Block(PlaBlockMode.Lz, [0, 0, 1, 1], unpacked: 1));
+ using var stream = new CountingStream(data);
+ using var document = PlaDocument.Open(stream, leaveOpen: true);
+ stream.BytesRead = 0;
+
+ Assert.Equal(new byte[] { 0 }, document.ReadPayload(document.Blocks[1]));
+ Assert.Equal(6, stream.BytesRead);
+ }
+
+ private sealed class CountingStream(byte[] data) : MemoryStream(data)
+ {
+ public int BytesRead { get; set; }
+
+ public override int Read(Span buffer)
+ {
+ int count = base.Read(buffer);
+ BytesRead += count;
+ return count;
+ }
+ }
+
+ [Fact]
+ public void FinalMatchWithoutLengthByteClipsToTheDeclaredSize()
+ {
+ // token 0x40 (lit 4) "ABCD"; dist 4 and the body ends: the match length is the remainder
+ // of the output, so the copy fills exactly the declared 8 bytes.
+ var lz = Synthetic.Concat([0x40], "ABCD"u8.ToArray(), [0x00, 0x04]);
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.Lz, lz, unpacked: 8))));
+
+ Assert.Equal("ABCDABCD"u8.ToArray(), document.ReadPayload(document.Blocks.Single()));
+ }
+
+ [Fact]
+ public void ABufferBlockProducesItsActualStreamAndZeroTail()
+ {
+ // the token stream produces 4 bytes, but the block declares a 16-byte buffer: the tail of the
+ // buffer stays zero and the payload returns the whole buffer.
+ var lz = Synthetic.Concat([0x40], "ABCD"u8.ToArray());
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.Lz, lz, unpacked: 16))));
+
+ var payload = document.ReadPayload(document.Blocks.Single());
+ Assert.Equal(16, payload.Length);
+ Assert.Equal("ABCD"u8.ToArray(), payload[..4]);
+ Assert.Equal(new byte[12], payload[4..]);
+ }
+
+ [Fact]
+ public void TheWindowHoldsTheBufferSpaceOfAPrecedingBufferBlock()
+ {
+ // block A is a buffer block (actual "ABCD", declared 16): the window receives the buffer space
+ // (ABCD + 12 zeros). Block B references the window tail: dist 6 lands in the zero padding.
+ var a = Synthetic.Concat([0x40], "ABCD"u8.ToArray());
+ var b = Synthetic.Concat([0x40], "wxyz"u8.ToArray(), [0x00, 0x06], [0x04]);
+ using var document = PlaDocument.Open(new MemoryStream(Synthetic.Fdb(
+ Synthetic.Block(PlaBlockMode.Lz, a, unpacked: 16),
+ Synthetic.Block(PlaBlockMode.Lz, b, unpacked: 8))));
+
+ var payload = document.ReadPayload(document.Blocks[1]);
+ Assert.Equal(new byte[] { (byte)'w', (byte)'x', (byte)'y', (byte)'z', 0, 0, (byte)'w', (byte)'x' }, payload);
+ }
+}
diff --git a/tests/PlaIO.Tests/PlaDocumentTests.cs b/tests/PlaIO.Tests/PlaDocumentTests.cs
index df4f2fd..4dd7c25 100644
--- a/tests/PlaIO.Tests/PlaDocumentTests.cs
+++ b/tests/PlaIO.Tests/PlaDocumentTests.cs
@@ -13,14 +13,15 @@ private static byte[] OneBlockOfEachMode() => Synthetic.Fdb(
Synthetic.Block(PlaBlockMode.Lz, new byte[12], tag: "DY", unpacked: 40));
[Fact]
- public void ReadsModesZeroAndOneAndRefusesModeTwo()
+ public void ReadsAllThreePayloadModes()
{
using var document = PlaDocument.Open(new MemoryStream(OneBlockOfEachMode()));
Assert.Equal([PlaBlockMode.Raw, PlaBlockMode.ZeroMask, PlaBlockMode.Lz], document.Blocks.Select(b => b.Mode));
Assert.Equal(RawPayload, document.ReadPayload(document.Blocks[0]));
Assert.Equal(Plain, document.ReadPayload(document.Blocks[1]));
- var e = Assert.Throws(() => document.ReadPayload(document.Blocks[2]));
- Assert.Contains("mode 2", e.Message);
+ // The mode-2 payload (12 zero bytes) is a token stream: token 0x00 (no literals),
+ // distance 0 (emit zeros), length byte 0 (256) clipped at the declared size of 40.
+ Assert.Equal(new byte[40], document.ReadPayload(document.Blocks[2]));
}
[Fact]
diff --git a/tests/PlaIO.Tests/SampleTests.cs b/tests/PlaIO.Tests/SampleTests.cs
index 533b0ba..61d7473 100644
--- a/tests/PlaIO.Tests/SampleTests.cs
+++ b/tests/PlaIO.Tests/SampleTests.cs
@@ -137,14 +137,15 @@ public void NearlyEveryZeroMaskBlockDecodesToItsDeclaredSize()
}
[SkippableFact]
- public void ReadingAnLzBlockThrowsNotSupported()
+ public void EveryLzBlockDecodesAndOnlyFalseEntriesAreSkipped()
{
- var (sample, block) = corpus.Fdb
- .SelectMany(s => s.Document.Blocks.Where(b => b.Mode == PlaBlockMode.Lz).Select(b => (s, b)))
- .FirstOrDefault();
- Assert.True(block != null, "No sample has a mode-2 block.");
- var e = Assert.Throws(() => sample.Document.ReadPayload(block));
- Assert.Contains("mode 2", e.Message);
+ foreach (var sample in corpus.Fdb)
+ {
+ sample.Document.DecodeGlobalWindow(out var skipped);
+ string where = $"{sample.Name}: {skipped.Count} of {sample.Document.Blocks.Count} blocks skipped";
+ Assert.True(skipped.All(b => b.Mode != PlaBlockMode.Lz), $"{where}; a mode-2 block did not decode");
+ Assert.True(skipped.Count <= 0.01 * sample.Document.Blocks.Count, where);
+ }
}
[SkippableFact]