Skip to content

0004 — Frame parser: Parse over a span

IFrameParser<TFrame> has one method the framework calls:

ParseResult Parse(ReadOnlySpan<byte> data, out TFrame? frame);

data is every unconsumed received byte in one span. The parser says what its start holds; the framework consumes the bytes, calls again after a skip or a frame, and waits for more data otherwise. TryParse(ref ReadOnlySequence<byte>, out TFrame) is an [Obsolete(error: true)] member that the framework never calls.

Breaks: every TCP adapter. Its parser class no longer builds: CS0535 (Parse is not implemented) and PQ0006 on the old TryParse, which links here. A test that calls TryParse fails with CS0619.

Why

A parser that got the ReadOnlySequence had to find frames, skip garbage, wait for data and advance the buffer itself, and the easiest way to index the bytes was buffer.ToArray() of the whole buffer on every call. With a span the parser indexes the bytes directly and copies only what its frame keeps. Skipping, waiting and advancing are done once, in the framework.

Migrate the parser

Step 1 — Replace the method

Change this To this
public bool TryParse(ref ReadOnlySequence<byte> buffer, out MyFrame frame) public ParseResult Parse(ReadOnlySpan<byte> data, out MyFrame? frame)
frame = null!; frame = null;
return false; for incomplete data, buffer unchanged return ParseResult.NeedMore;
buffer = buffer.Slice(n); return false; (skip garbage, bad checksum) return ParseResult.Skip(n);
buffer = buffer.Slice(total); return true; return ParseResult.Frame(total);
a resync loop (while/continue over garbage) one Skip per call; delete the loop

Step 2 — Read the bytes from the span

Change this To this
var bytes = buffer.ToArray(); then bytes[i] data[i]
SequenceReader, PositionOf, buffer.Slice(a, b) data.IndexOf(...), data[a..b]
bytes[a..b] kept by the frame data[a..b].ToArray() (the one copy)
Encoding.ASCII.GetString(slice.ToArray()) Encoding.ASCII.GetString(data[a..b])

data is valid only during the call: a frame property that keeps bytes needs its own copy.

Step 3 — Migrate the tests

Replace parser.TryParse(ref buffer, out var frame) with parser.TryRead(ref buffer, out var frame) (using Pq.Adapters.Framework.Communication.Tcp;). TryRead reads exactly like the connection: it skips what the parser skips and returns false when the parser needs more data.

Step 4 — Verify

Build the adapter and run its tests. The build shows no CS0535 or CS0619 that names IFrameParser.