compare-dispatch-client.sh benchmarks a pinned pre-migration worktree
against this tree. README records the results; Package.swift and
IMAPDispatchClient.swift point to it.
IMAPProfile runs one corpus N times, for tracing under Instruments'
Allocations template; the README says how to read the trace.
summarize-comparison.py condenses `baseline compare` output.
Output of `benchmark thresholds update`, measured before a rebase and
not re-measured since. Host-specific; not gated in CI. Apple M5 Max,
macOS 27.3, Swift 6.4.4. From Examples/PerformanceTester, with
six = --metric mallocCountTotal --metric mallocBytesCount
--metric objectAllocCount --metric retainCount
--metric releaseCount --metric retainReleaseDelta
two = --metric mallocCountTotal --metric mallocBytesCount:
swift package --disable-sandbox benchmark thresholds update \
--target IMAPParsing $six
swift package --disable-sandbox benchmark thresholds update \
--target IMAPEncoding --skip 'encode\.dispatch\..*' $six
swift package --disable-sandbox benchmark thresholds update \
--target IMAPEncoding --filter 'encode\.dispatch\..*' $two
Encoder benchmarks for commands and responses, through contiguous,
NIO-handler and DispatchData drivers. Adds those drivers to
IMAPBenchmarkSupport, plus the response model corpus.
IMAPDispatchClient's no-ARC note now points at encode.dispatch.*'s.
Parser benchmarks for commands and responses, plus IMAPBenchmarkSupport:
the command corpus and the parse drivers. Post-migration only; not
built with IMAP_IMPL=main.
Generated with the two commands in "Add IMAPDispatchClient benchmark
thresholds (generated)", before a rebase; not re-measured since.
"Regenerate benchmark thresholds (generated)" re-measures later.
Apple M5 Max, macOS 27.3, Swift 6.4.4.
The DispatchData client now has two drivers. DispatchClient+Current
uses IMAPInputBuffer (each read appended with append(contentsOf:)),
IMAPBuffer payloads and IMAPOutputBuffer donated via
makeDispatchData(); DispatchClient+Legacy, the ByteBuffer client,
compiles only under IMAP_LEGACY_BUFFERS. IMAP_IMPL=main in Package.swift
points the path dependency at a pre-migration checkout (IMAP_MAIN_PATH)
and defines that flag, so one set of case names yields before/after
numbers.
The encode cases' no-ARC note gains the reasons donation adds: the
queue-dependent retain deltas and the thread the hook race fires on.
Built both ways (IMAP_IMPL=main against f5fa7d36). Thresholds follow
separately.
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 four raw-payload cases become IMAPBuffer so a large literal can be
handed in and out without a copy: FetchResponse.streamingBytes,
AppendCommand.messageBytes, AppendCommand.CatenateData.bytes,
CommandStreamPart.continuationResponse.
Review focus: writeBytes(IMAPBuffer) keeps payloads by reference
(ZeroCopyWriteTests); the parser's extractBuffer(upTo:) still copies.
Updates IMAPTool and the IMAPCommands append/continuation wrappers.
Public API breaks:
- The four cases above: ByteBuffer -> IMAPBuffer.
Removes the writeBuffer(inout ByteBuffer) shim from "Encode into an
EncoderOutputBuffer sink".
Small fields (mailbox names, atoms, quoted strings, envelope fields,
base64, URLs, the authentication challenge, catenateURL, ...) become
[UInt8]. The four raw-payload cases stay ByteBuffer until "Make payload
cases IMAPBuffer".
The grammar's string productions return [UInt8]. The parser still runs
on ParseBuffer, so its cursor methods copy out of the ByteBuffer for now.
Review focus: the model files' encoders and ModifiedUTF7 on arrays.
Updates IMAPTool and the IMAPCommands catenate-URL wrapper.
Public API breaks:
- ~38 public declarations ByteBuffer -> [UInt8].
- ModifiedUTF7.EncodingRoundtripError.buffer -> .bytes.
- Response.authenticationChallenge and ContinuationRequest.data are
[UInt8]; an empty challenge is [].
Internal: writeBufferAsBase64 -> writeBytesAsBase64; the ByteBuffer
writeIMAPString overload is gone.
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.
The new byte types need `Span`-producing stdlib accessors (`Array.span`,
`String.utf8Span`) that are gated at 26. Also adds `DequeModule`.
Public break: raises the deployment floor to 26 on every platform (was
macOS 15, iOS 18, tvOS 18, watchOS 11, visionOS 2). Examples follow,
since a path dependency cannot have a higher floor than its dependent.
IMAPDispatchClient: a DispatchData client (parse + encode), measured
with allocation counters (plus ARC counters for parsing) instead of
Date(). Needs Swift 6.3 (malloc-interposer), so CI builds it in its own
job.
The "Legacy" file name anticipates the migration's
DispatchClient+Current.
* Reject invalid response text when writing
`.no(.init(text: "No mailbox x\r\n* BYE pwned"))` was written verbatim,
injecting an untagged response; likewise tagged, BYE, PREAUTH and
continuation responses.
RFC 9051: `text = 1*(TEXT-CHAR / UTF8-2 / UTF8-3 / UTF8-4)`. `writeText`
now asserts no NUL, CR or LF. Empty stays valid. The parser now accepts
UTF-8 text.
* Add Command.Tag for command and response tags
`TaggedCommand(tag: "A1 NOOP\r\nA2 DELETE INBOX\r\nA3", command: .noop)`
was written verbatim, injecting a command; likewise `APPEND` start.
`TaggedResponse(tag: "* BYE x\r\nA1", …)` injected a response.
RFC 3501: `tag = 1*<any ASTRING-CHAR except "+">`. New `Command.Tag`
replaces the `String` in `TaggedCommand`, `TaggedResponse`, `Response`,
`CommandStreamPart`, `AppendCommand`, `BadCommand` and NIOIMAP's state
machine errors; `init?(_:)` validates, literals trap. The parser already
enforces the production. IMAPCommands converts its numeric tags.
* Validate and escape namespace delimiters
`NamespaceDescription(string: "x", char: "\r\n", …)` wrote a raw CRLF
inside `"…"`, injecting a response. `"\""` encoded as `"""`, and `"\\"`
as `"\"` (unterminated); non-ASCII was accepted.
RFC 2342: `DQUOTE QUOTED-CHAR DQUOTE / nil`. `init(string:delimiter:
responseExtensions:)` (was `char:`) throws `InvalidDelimiterError` for
non-ASCII, CR, LF, NUL; the delimiter is stored as a byte, read-only.
Quoted-specials are escaped on write and parsed when escaped.
* Gate a capturing exit test on Swift 6.3