RegionSink, ParseInput and IMAPInputBuffer's region plumbing become
internal. Data and DispatchData no longer conform to the parser input
protocols: append them to an IMAPInputBuffer.
History, rejected alternatives and measurements go to implementation
comments; doc comments keep what a caller needs.
The handlers stage reads in an IMAPInputBuffer (IMAPInputProcessor)
instead of NIOSingleStepByteToMessageProcessor's coalesced ByteBuffer,
so a FETCH/APPEND literal piece of at least 1 KiB within one read of
at least 1 KiB is delivered as a reference to the received bytes.
Shorter pieces are copied; bytes from smaller reads are copied twice,
into a tail on arrival and out of it on delivery. The decoders keep
their ByteBuffer entry point for ByteToMessageHandler and the decoder
verifier; that path copies.
A decoder error or PayloadTooLargeError is final: the buffer is dropped
and later reads rethrow it without decoding (ByteToMessageHandler also
stops decoding, but fires dataReceivedInErrorState). Keeping the
unparsed bytes would make every later read append, fail on the same
bytes and copy all of them into IMAPDecoderError.buffer: unbounded
memory and quadratic copying, past the maximumBufferSize check. Errors
thrown by the message receiver (e.g. UnexpectedResponse) pass through
and are not final.
Reads under 1 KiB are copied into IMAPInputBuffer's tails, so 1-byte
reads cost a region per KiB and pin no receive buffers. A larger read
still pins its whole receive buffer, which maximumBufferSize does not
count.
Review focus: IMAPInputProcessor.
Behavior changes:
- A stream whose input failed to parse stays failed.
- IMAPDecoderError.buffer holds the bytes waiting to be parsed when the
error was thrown.
- Leftover literal bytes followed by a read that starts a new region
reach the handler's consumer as two .streamingBytes events, not
one. Every read of at least 1 KiB starts a region; a smaller one
does when the last region is a retained read, or a tail it does not
fit or that is not uniquely referenced.
ParseInput.extractBuffer(upTo:) takes bytes from the current region
only, where the old code took min(remaining, readable) across the
whole buffer. Legal, but observable. A caller passing a multi-region
buffer to the stream parsers directly sees this from the previous
commit on.
The grammar now runs on the ~Escapable ParseInput cursor; ParserLibrary
and its ParseBuffer are deleted. The stream parsers are generic over
ConsumableParserInputBuffer and gather once per call: CommandParser
frames synchronizing literals and parses through the same cursor,
narrowing its limit instead of slicing. The NIO handlers still feed
ByteBuffers, through its ParserInputBuffer conformance.
Review focus: CommandParser.parseCommandStream and
ResponseParser.parseResponseStream (what is consumed on each exit path).
Behavior changes:
- Stray spaces before a line ending: up to
ParseInput.maximumStraySpaces (1024) are accepted; more throw
ParserError. On main, PL.parseNewline recursed through composite once
per space, so ~100 threw TooMuchRecursion from the shared 100-frame
tracker. Both a looser limit and a different error type.
- Trailing spaces with no line ending yet report IncompleteMessage while
under the cap, where they used to throw ParserError. Fixes the client
side (ResponseParser), which has no framing layer, for a read split as
"* 1 EXISTS " | "\r\n".
- From an IMAPInputBuffer, payload pieces of at least 1 KiB taken from
a retained read (>= 1 KiB, fixed address) refer to it; a large Data
is retained as the buffer's one copy. Smaller pieces and tail bytes
are copied. From a bare ByteBuffer, payloads are copied.
Grammar edits beyond the cursor: the QUOTA resource loop binds
parseOptional's result to an explicit `Void?`, and parseLookupKeyword
loses a comment about the tracker it no longer takes. ParserError.hint
gains a note to keep hot-path hints literal: ParserLibrary's
interpolated ones, deleted here, allocated on every mismatch.
Public API break: parseCommandStream(buffer:) and
parseResponseStream(buffer:) are generic. ByteBuffer conforms in
NIOIMAP, so a caller importing only NIOIMAPCore must import NIOIMAP to
pass one.
Temporary: `typealias ParseBuffer = ParseInput` keeps the grammar's
spelling until "Rename ParseBuffer to ParseInput (scripted)". Removes
LegacySubParser, the ParseBuffer cursor-method shim and the framing
bridge from "Move SynchronizingLiteralParser onto ParserInputBuffer".
EncodeBuffer appends to `any EncoderOutputBuffer` (IMAPOutputBuffer by
default) instead of holding a ByteBuffer. Chunks come out as
IMAPBufferList; the handlers write one buffer per payload via
makeOutboundBuffers(). CommandEncoder is deleted: it kept only the first
chunk of a synchronizing literal and had no users but its own test.
nextChunk() caps a chunk at 64 regions, coalescing the tail, whatever
the sink returned, so no sink (a caller's own included) has to.
EncodeBuffer stages writes under 256 bytes inline and appends them to
the sink in one call: one existential call per ~256 bytes, not per
write. It flushes before every hand-out and before any direct sink
append (writeBytes(IMAPBuffer), larger writes), so payloads still reach
the sink by reference and in order. Conformers see batched appends;
byteCount may lag until a hand-out (documented on EncoderOutputBuffer).
Per-write cost therefore no longer separates the two sinks, so the
docs choosing IMAPOutputBuffer over ByteBufferOutput (ByteBufferOutput's,
EncoderOutputBuffer's, IMAPOutputBuffer's, the handlers') rest on the
hand-out instead.
Review focus: totalWritten / handedOut and absolute stop points in
nextChunk() (an off-by-one deadlocks the protocol, see
EncodeBufferSinkTests), the staging flush points, and
IMAPClientHandler.writeChunk's promise handling across several writes.
The CLI example's round-trip handler compares all chunks via the public
nextChunk() (it compared only the first) and drops its SPI import.
Public API breaks:
- CommandEncodeBuffer / ResponseEncodeBuffer: `init(buffer:…)` ->
`init(sink: = IMAPOutputBuffer(), …)`; no longer Sendable.
- EncodeBuffer.Chunk.bytes and ResponseEncodeBuffer.readBytes() are
IMAPBufferList.
- EncodeBuffer.writeBytes takes a Collection; writeBytes(IMAPBuffer) added;
writeBuffer(inout ByteBuffer) removed.
- EncodeBuffer (SPI) is no longer Sendable; == / hash compare the pending
bytes.
Public API addition: CommandEncodeBuffer.nextChunk() -> Chunk?, with
Chunk { bytes, nextStep } and NextStep { proceed,
awaitContinuationRequest }, so a client with its own transport needs no
SPI. nextStep awaits whenever a chunk ends at a synchronizing literal
header, also at the last byte written (APPEND .beginMessage,
.catenateData(.begin)), where the SPI Chunk.waitForContinuation says no
wait. ClientStateMachine uses it and imports no NIOIMAPCore SPI.
Behavior change: an APPEND part that ends in a literal the APPEND flow
doesn't expect (zero-length, e.g. an empty mailbox with quoted strings
off) waits for `+` before the next part instead of running ahead; its
write promise completes after the `+`.
Examples/PerformanceTester (IMAPDispatchClient) does not build from here
until "Measure IMAPDispatchClient against either library".
Temporary: EncodeBuffer+ByteBufferShim.swift keeps an internal
writeBuffer(inout ByteBuffer) for the model types that still hold one.
ParseInput: a ~Escapable, BitwiseCopyable cursor over a table of region
pointers, with the primitives and combinators as methods. Input buffers:
ParserInputBuffer (+ Consumable, StableRegion refinements), conformances
for ByteBuffer / Array / Data, and IMAPInputBuffer, the staging deque that
can hand out payloads by reference.
IMAPInputBuffer keeps reads of at least copyThreshold (1 KiB) by
reference and copies smaller ones into a 1 KiB tail (an OutputSegment),
so a peer sending a byte per read costs a region per KiB, not a region,
an object and a retained receive buffer per byte. A tail is written
only past its end, only while the buffer holds the sole reference, and
never reallocated; a used-up tail with room is continued by the next
small read into an empty buffer. Only a StableAddressByteRegion (arrays,
ByteBuffer) or an IMAPBuffer over one is kept by reference; any other
large region, e.g. Data, is copied once.
A bare DispatchData.Region is copied too: it points into its
DispatchData without keeping it alive, so it is not a
StableAddressByteRegion. append(contentsOf:) is the zero-copy path for
DispatchData.
Public API additions: IMAPInputBuffer.append(contentsOf: DispatchData)
walks a read's regions with enumerateBytes, so it builds no regions
array; a large region is kept with the DispatchData that owns it (also
the owner a makeDispatchData() donation retains), small ones go to the
tail. append(_:) gains overloads for a StableAddressByteRegion and an
IMAPBuffer, so appending a ByteBuffer, an array or an IMAPBuffer pays no
dynamic cast; IMAPByteStorage.init(_:) gains one for an IMAPBuffer.
Additive; the grammar still runs on ParseBuffer. Review focus: _span(_:)
and RegionSink (the two read-side unsafe seams), the head invariant in
advance(by:), the gather's 64-frame recursion cap,
IMAPInputBuffer.writableTail(fitting:), and DispatchDataRegion, what
append(contentsOf:) keeps: its @unchecked Sendable and its
StableAddressByteRegion (fixed-address) promise.
Temporary: main's SubParser is renamed LegacySubParser so both coexist.
IMAPBuffer / IMAPByteStorage (owner + range, no pointer), IMAPBufferList,
OutputSegment, the EncoderOutputBuffer sink protocol and its two
conformers: IMAPOutputBuffer (core, donates to DispatchData) and
ByteBufferOutput (NIOIMAP, fills a ByteBuffer in place).
StableAddressByteRegion is the public opt-in for a foreign region to be
donated by makeDispatchData() rather than copied: arrays conform, and
NIOIMAP conforms ByteBuffer with public API only (CoW keeps a held
copy's readable bytes in place).
makeDispatchData() donates only regions of at least
IMAPBuffer.dispatchDonationThreshold (512) bytes; each run of shorter
or unstable regions is copied into one malloc'd region freed inline
(.free). Measured: a donated region costs ~4 mallocs, 300-500 B and
~400 ns plus an async deallocator block; a copy costs a memcpy. The
deallocator captures the owner's concrete type, not an existential.
Public API for adapting a buffer type, so NIOIMAP's ByteBuffer support
needs no SPI and a third-party type can do the same:
IMAPBuffer.copyThreshold and dispatchDonationThreshold;
backingRegion(as:), which recovers the backing region and range without
copying; withUnsafeBytesAndOwner(_:), which hands out bytes with a fixed
address and their owner, under the same rule makeDispatchData() uses.
IMAPByteStorage.init(_:) has an overload for a StableAddressByteRegion,
which records the fixed address statically: the generic init isn't
specialized across modules, so its dynamic cast would run once per
wrapped ByteBuffer.
Additive; nothing uses them yet. Review focus: OutputSegment's
@unchecked Sendable (handed-out ranges never overlap the write tail),
IMAPOutputBuffer's copy-on-write state box and its
@exclusivity(unchecked) properties, and makeDispatchData()'s copy runs.