Files
swift-nio-imap/Sources/NIOIMAP/Bytes/ByteBuffer+ParserInput.swift
T
Daniel Eggert 871703670e Deliver received literals zero-copy via IMAPInputProcessor
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.
2026-11-24 18:10:39 +09:00

50 lines
2.5 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import NIO
import NIOIMAPCore
// This file is what lets a caller holding a `ByteBuffer` append it to an `IMAPInputBuffer` without
// copying it. `NIOIMAPCore` does not know about NIO, so the conformances live here; `NIOIMAP` re-exports
// `NIOIMAPCore`, so which of the two modules declares them is invisible to anyone importing `NIOIMAP`.
//
// They need no `@retroactive`: the protocols are declared in this package, so this is not a conformance
// two other modules could also add.
extension ByteBuffer: ByteRegion {
/// Calls the given closure with a pointer to the buffer's readable bytes.
///
/// This is `withUnsafeReadableBytes(_:)` under the name `ByteRegion` requires, and it is what
/// lets a `ByteBuffer` be handed to `NIOIMAPCore` without being copied first.
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
try withUnsafeReadableBytes(body)
}
}
// A copy of a `ByteBuffer` keeps its storage alive, and while copies share storage a write through any of
// them copies it first — so the readable bytes a copy sees neither move nor change. That lets
// `IMAPInputBuffer` keep a large one and `makeDispatchData()` donate one, rather than copy.
extension ByteBuffer: StableAddressByteRegion {
/// The capacity of the storage, which every copy and slice of this buffer keeps alive: a 1 KiB
/// slice of a 64 KiB read pins 64 KiB.
public var pinnedByteCount: Int { storageCapacity }
}
// A `ByteBuffer` deliberately does *not* conform to `StableRegionParserInputBuffer`, so a payload
// extracted from one is copied rather than referred to. Vouching for a region means handing the gather
// an `IMAPByteStorage` that outlives it, and `RegionSink.append` takes that owner *unretained* — so a
// conformer that boxes inside `withStableRegions` would hand over a box that is already dead. Only
// something that *stores* the box can promise this, which is what `IMAPInputBuffer` is for: append a
// `ByteBuffer` to one of those and a multi-megabyte literal reaches the caller uncopied.