mirror of
https://github.com/apple/swift-nio-imap
synced 2026-11-30 05:28:46 +00:00
Encode into an EncoderOutputBuffer sink
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.
This commit is contained in:
48 files changed
+1563
-800
No files matched your search
@@ -12,15 +12,13 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import struct NIO.ByteBuffer
|
||||
import struct NIO.ByteBufferView
|
||||
import struct NIO.CircularBuffer
|
||||
import DequeModule
|
||||
|
||||
/// A buffer for encoding IMAP protocol messages into wire format.
|
||||
///
|
||||
/// `EncodeBuffer` is the core infrastructure for converting Swift types into bytes
|
||||
/// that can be transmitted over the network. It wraps a `ByteBuffer` and tracks
|
||||
/// encoding state, supporting both client commands and server responses.
|
||||
/// that can be transmitted over the network. It appends those bytes to an
|
||||
/// ``EncoderOutputBuffer`` — a sink chosen by whoever created the buffer — and tracks encoding state.
|
||||
///
|
||||
/// Part of the internal SPI and is primarily used by:
|
||||
/// - ``CommandEncodeBuffer`` for encoding client commands
|
||||
@@ -40,7 +38,7 @@ import struct NIO.CircularBuffer
|
||||
/// continuation response is expected.
|
||||
///
|
||||
/// - SeeAlso: ``CommandEncodeBuffer``, ``ResponseEncodeBuffer``
|
||||
@_spi(NIOIMAPInternal) public struct EncodeBuffer: Hashable, Sendable {
|
||||
@_spi(NIOIMAPInternal) public struct EncodeBuffer {
|
||||
/// Determines whether the buffer encodes for a client or server.
|
||||
///
|
||||
/// Affects how the buffer formats protocol elements like literals, strings,
|
||||
@@ -65,68 +63,118 @@ import struct NIO.CircularBuffer
|
||||
|
||||
/// Enables logging mode, which obscures binary data for display purposes.
|
||||
///
|
||||
/// When `true`, methods like ``writeBytes(_:)`` and ``writeBuffer(_:)`` will
|
||||
/// write placeholder text like `[N bytes]` instead of the actual binary content.
|
||||
/// Useful for logging and debugging without exposing sensitive data.
|
||||
/// When `true`, methods like ``writeBytes(_:)-1nrmp`` will write placeholder text like
|
||||
/// `[N bytes]` instead of the actual binary content. Useful for logging and debugging without
|
||||
/// exposing sensitive data.
|
||||
public var loggingMode: Bool
|
||||
|
||||
internal var mode: Mode
|
||||
@usableFromInline internal var buffer: ByteBuffer
|
||||
@usableFromInline internal var stopPoints: CircularBuffer<Int> = []
|
||||
|
||||
init(_ buffer: ByteBuffer, mode: Mode, loggingMode: Bool) {
|
||||
self.buffer = buffer
|
||||
/// Where the encoded bytes go.
|
||||
@usableFromInline internal var sink: any EncoderOutputBuffer
|
||||
|
||||
/// Offsets, counted in ``totalWritten``, at which chunks must be broken.
|
||||
///
|
||||
/// These are **absolute** — bytes ever appended to this buffer — rather than positions within
|
||||
/// what the sink is currently holding, because the sink's contents shrink every time a chunk is
|
||||
/// handed out. See ``markStopPoint()``.
|
||||
@usableFromInline internal var stopPoints: Deque<Int> = []
|
||||
|
||||
/// How many bytes have ever been appended, since the buffer was created or last cleared.
|
||||
@usableFromInline internal var totalWritten: Int = 0
|
||||
|
||||
/// How many bytes have ever been handed out by ``nextChunk()``.
|
||||
///
|
||||
/// `handedOut + sink.byteCount + stagedCount == totalWritten` at all times, which is the invariant
|
||||
/// that makes the absolute stop points above meaningful.
|
||||
@usableFromInline internal var handedOut: Int = 0
|
||||
|
||||
/// Small writes collect here and reach the sink as one `append`: one existential call per
|
||||
/// ``stagingCapacity`` bytes instead of one per write. Flushed before any direct sink append and
|
||||
/// before the sink hands bytes out.
|
||||
@usableFromInline internal var staging = Staging(repeating: 0)
|
||||
|
||||
/// How many bytes at the start of ``staging`` are waiting for the sink.
|
||||
@usableFromInline internal var stagedCount: Int = 0
|
||||
|
||||
// 256: a typical command or response line, while keeping copies of `EncodeBuffer` cheap.
|
||||
@usableFromInline typealias Staging = InlineArray<256, UInt8>
|
||||
|
||||
/// The most bytes ``staging`` holds. A write at least this big skips it.
|
||||
@inlinable static var stagingCapacity: Int { Staging.count }
|
||||
|
||||
init(_ sink: some EncoderOutputBuffer, mode: Mode, loggingMode: Bool) {
|
||||
self.sink = sink
|
||||
self.mode = mode
|
||||
self.loggingMode = loggingMode
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sendability
|
||||
|
||||
/// `EncodeBuffer` is deliberately **not** `Sendable`.
|
||||
///
|
||||
/// It writes into an ``EncoderOutputBuffer``, which is not `Sendable` either: a sink belongs to one
|
||||
/// encoder, which belongs to one connection handler, and it may own memory it is actively writing
|
||||
/// into. What does cross a thread is a chunk that has been handed out — ``Chunk`` holds an
|
||||
/// ``IMAPBufferList``, whose bytes are frozen at hand-out and so are `Sendable`.
|
||||
@available(*, unavailable)
|
||||
extension EncodeBuffer: Sendable {}
|
||||
|
||||
extension EncodeBuffer {
|
||||
/// Creates a new `EncodeBuffer` suitable for a client to write commands.
|
||||
/// - parameter buffer: An initial `ByteBuffer` to write to. Note that this is copied and not taken as `inout`.
|
||||
/// - parameter sink: Where the encoded bytes are appended.
|
||||
/// - parameter options: Configuration to use when writing.
|
||||
/// - returns: A new `EncodeBuffer` configured for client use.
|
||||
static func clientEncodeBuffer(
|
||||
buffer: ByteBuffer,
|
||||
sink: some EncoderOutputBuffer = IMAPOutputBuffer(),
|
||||
options: CommandEncodingOptions,
|
||||
loggingMode: Bool
|
||||
) -> EncodeBuffer {
|
||||
EncodeBuffer(buffer, mode: .client(options: options), loggingMode: loggingMode)
|
||||
EncodeBuffer(sink, mode: .client(options: options), loggingMode: loggingMode)
|
||||
}
|
||||
|
||||
/// Creates a new `EncodeBuffer` suitable for a client to write commands.
|
||||
/// - parameter buffer: An initial `ByteBuffer` to write to. Note that this is copied and not taken as `inout`.
|
||||
/// - parameter sink: Where the encoded bytes are appended.
|
||||
/// - parameter capabilities: The capabilities the server advertised, which decide the encoding
|
||||
/// options.
|
||||
/// - returns: A new `EncodeBuffer` configured for client use.
|
||||
static func clientEncodeBuffer(buffer: ByteBuffer, capabilities: [Capability], loggingMode: Bool) -> EncodeBuffer {
|
||||
static func clientEncodeBuffer(
|
||||
sink: some EncoderOutputBuffer = IMAPOutputBuffer(),
|
||||
capabilities: [Capability],
|
||||
loggingMode: Bool
|
||||
) -> EncodeBuffer {
|
||||
clientEncodeBuffer(
|
||||
buffer: buffer,
|
||||
sink: sink,
|
||||
options: CommandEncodingOptions(capabilities: capabilities),
|
||||
loggingMode: loggingMode
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates a new `EncodeBuffer` suitable for a server to write responses.
|
||||
/// - parameter buffer: An initial `ByteBuffer` to write to. Note that this is copied and not taken as `inout`.
|
||||
/// - parameter sink: Where the encoded bytes are appended.
|
||||
/// - parameter options: Configuration to use when writing.
|
||||
/// - returns: A new `EncodeBuffer` configured for server use.
|
||||
static func serverEncodeBuffer(
|
||||
buffer: ByteBuffer,
|
||||
sink: some EncoderOutputBuffer = IMAPOutputBuffer(),
|
||||
options: ResponseEncodingOptions,
|
||||
loggingMode: Bool
|
||||
) -> EncodeBuffer {
|
||||
EncodeBuffer(buffer, mode: .server(streamingAttributes: false, options: options), loggingMode: loggingMode)
|
||||
EncodeBuffer(sink, mode: .server(streamingAttributes: false, options: options), loggingMode: loggingMode)
|
||||
}
|
||||
|
||||
/// Creates a new `EncodeBuffer` suitable for a server to write responses.
|
||||
/// - parameter buffer: An initial `ByteBuffer` to write to. Note that this is copied and not taken as `inout`.
|
||||
/// - parameter sink: Where the encoded bytes are appended.
|
||||
/// - parameter capabilities: The capabilities the server advertises, which decide the encoding
|
||||
/// options.
|
||||
/// - returns: A new `EncodeBuffer` configured for server use.
|
||||
static func serverEncodeBuffer(buffer: ByteBuffer, capabilities: [Capability], loggingMode: Bool) -> EncodeBuffer {
|
||||
static func serverEncodeBuffer(
|
||||
sink: some EncoderOutputBuffer = IMAPOutputBuffer(),
|
||||
capabilities: [Capability],
|
||||
loggingMode: Bool
|
||||
) -> EncodeBuffer {
|
||||
serverEncodeBuffer(
|
||||
buffer: buffer,
|
||||
sink: sink,
|
||||
options: ResponseEncodingOptions(capabilities: capabilities),
|
||||
loggingMode: loggingMode
|
||||
)
|
||||
@@ -142,9 +190,27 @@ extension EncodeBuffer {
|
||||
options.useQuotedString = true
|
||||
options.useSynchronizingLiteral = false
|
||||
options.useNonSynchronizingLiteralPlus = true
|
||||
var buffer = EncodeBuffer.clientEncodeBuffer(buffer: ByteBuffer(), options: options, loggingMode: false)
|
||||
var buffer = EncodeBuffer.clientEncodeBuffer(options: options, loggingMode: false)
|
||||
closure(&buffer)
|
||||
return String(bestEffortDecodingUTF8Bytes: buffer.buffer.readableBytesView)
|
||||
return String(bestEffortDecodingUTF8Bytes: buffer.makePendingBufferList().copiedBytes())
|
||||
}
|
||||
|
||||
/// The bytes appended but not yet handed out, as one list.
|
||||
///
|
||||
/// Cold path only — equality, hashing and debug descriptions. This allocates per pending region,
|
||||
/// which is why it is a method rather than a property.
|
||||
internal func makePendingBufferList() -> IMAPBufferList {
|
||||
var list = sink.withPendingRegions { regions in
|
||||
var list = IMAPBufferList()
|
||||
for index in 0..<regions.count {
|
||||
list.append(regions[index])
|
||||
}
|
||||
return list
|
||||
}
|
||||
if self.stagedCount > 0 {
|
||||
list.append(withUnsafeBytes(of: self.staging) { IMAPBuffer(Array($0.prefix(self.stagedCount))) })
|
||||
}
|
||||
return list
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,8 +227,10 @@ extension EncodeBuffer {
|
||||
public struct Chunk: Hashable, Sendable {
|
||||
/// The encoded bytes ready to write to the network.
|
||||
///
|
||||
/// Contains the next portion of IMAP protocol data to transmit.
|
||||
public var bytes: ByteBuffer
|
||||
/// Contains the next portion of IMAP protocol data to transmit, as one or more regions —
|
||||
/// usually one. A networking caller writes them in order and lets the transport gather
|
||||
/// them; ``IMAPBufferList/copiedBytes()`` coalesces them where they have to be contiguous.
|
||||
public var bytes: IMAPBufferList
|
||||
|
||||
/// Whether a continuation request (`+`) should be expected before sending the next chunk.
|
||||
///
|
||||
@@ -170,6 +238,9 @@ extension EncodeBuffer {
|
||||
/// response before calling ``nextChunk()`` again. This synchronization is required
|
||||
/// by RFC 3501 for commands containing literals.
|
||||
///
|
||||
/// `false` for a chunk that ends at a stop point with nothing written after it yet, e.g.
|
||||
/// APPEND's `{5}\r\n`; ``CommandEncodeBuffer/nextChunk()`` reports that one as awaiting `+`.
|
||||
///
|
||||
/// - SeeAlso: ``ContinuationRequest``
|
||||
public var waitForContinuation: Bool
|
||||
}
|
||||
@@ -178,6 +249,11 @@ extension EncodeBuffer {
|
||||
self.stopPoints.count > 0
|
||||
}
|
||||
|
||||
/// How many bytes have been written but not yet handed out by ``nextChunk()``.
|
||||
internal var pendingByteCount: Int {
|
||||
self.sink.byteCount + self.stagedCount
|
||||
}
|
||||
|
||||
/// Retrieves the next chunk of encoded data ready to transmit.
|
||||
///
|
||||
/// In client mode with synchronizing literals, this may return multiple chunks with
|
||||
@@ -196,24 +272,60 @@ extension EncodeBuffer {
|
||||
/// *NOTE*: Use This function with caution. You probably shouldn't be using it, using nextChunk() instead.
|
||||
/// - returns: The next chunk that is ready to be written.
|
||||
@_spi(NIOIMAPInternal) public mutating func nextChunk(allowEmptyChunk: Bool) -> Chunk {
|
||||
self.takeChunk(allowEmptyChunk: allowEmptyChunk).chunk
|
||||
}
|
||||
|
||||
/// Where a chunk handed out by ``takeChunk(allowEmptyChunk:)`` ends.
|
||||
enum ChunkEnd {
|
||||
/// At a stop point: a synchronizing literal header, whose `+` the client awaits. Possibly the
|
||||
/// last byte written, e.g. APPEND's `{5}\r\n` before the message bytes are written.
|
||||
case stopPoint
|
||||
/// With everything pending; no stop point remains.
|
||||
case pendingBytes
|
||||
}
|
||||
|
||||
/// ``nextChunk(allowEmptyChunk:)``, and whether the chunk ended at a stop point.
|
||||
///
|
||||
/// ``Chunk/waitForContinuation`` can't tell: it is `false` for a stop point that is the last byte
|
||||
/// written so far.
|
||||
mutating func takeChunk(allowEmptyChunk: Bool) -> (chunk: Chunk, end: ChunkEnd) {
|
||||
switch self.mode {
|
||||
case .client:
|
||||
guard let stopPoint = self.stopPoints.popFirst() else {
|
||||
precondition(allowEmptyChunk || self.buffer.readableBytes > 0, "No next chunk to send.")
|
||||
return .init(
|
||||
bytes: self.buffer.readSlice(length: self.buffer.readableBytes)!,
|
||||
waitForContinuation: false
|
||||
)
|
||||
// A zero-*bytes* check, deliberately not `regionCount == 0`: a chunk carrying one
|
||||
// zero-length region holds no bytes at all.
|
||||
precondition(allowEmptyChunk || self.pendingByteCount > 0, "No next chunk to send.")
|
||||
return (.init(bytes: self.takeEverythingPending(), waitForContinuation: false), .pendingBytes)
|
||||
}
|
||||
return .init(
|
||||
bytes: self.buffer.readSlice(length: stopPoint - self.buffer.readerIndex)!,
|
||||
waitForContinuation: stopPoint != self.buffer.writerIndex
|
||||
)
|
||||
// Both are absolute offsets, so the difference is what is pending below the stop point.
|
||||
// Comparing a stop point against the sink's own (resetting) byte count instead is the
|
||||
// mistake that deadlocks the protocol.
|
||||
let bytes = self.takeFromSink(stopPoint - self.handedOut)
|
||||
self.handedOut = stopPoint
|
||||
return (.init(bytes: bytes, waitForContinuation: stopPoint != self.totalWritten), .stopPoint)
|
||||
case .server:
|
||||
return .init(bytes: self.buffer.readSlice(length: self.buffer.readableBytes)!, waitForContinuation: false)
|
||||
return (.init(bytes: self.takeEverythingPending(), waitForContinuation: false), .pendingBytes)
|
||||
}
|
||||
}
|
||||
|
||||
private mutating func takeEverythingPending() -> IMAPBufferList {
|
||||
let bytes = self.takeFromSink(self.pendingByteCount)
|
||||
self.handedOut = self.totalWritten
|
||||
return bytes
|
||||
}
|
||||
|
||||
/// Takes pending bytes, staged ones included, capped at ``IMAPBufferList/maximumRegionsPerChunk``
|
||||
/// regions whatever the sink returned.
|
||||
///
|
||||
/// The cap is here rather than in each sink so that a sink of the caller's own gets it too. Checking
|
||||
/// is O(1); only a list over the cap is rebuilt.
|
||||
private mutating func takeFromSink(_ byteCount: Int) -> IMAPBufferList {
|
||||
self.flushStaging()
|
||||
let bytes = self.sink.takeFirst(byteCount)
|
||||
guard bytes.regionCount > IMAPBufferList.maximumRegionsPerChunk else { return bytes }
|
||||
return IMAPBufferList(cappingRegionCount: bytes.regions)
|
||||
}
|
||||
|
||||
/// Marks the end of a command, potentially creating a stop point for chunking.
|
||||
///
|
||||
/// In client mode, this sets a stop point that ``nextChunk()`` uses to determine
|
||||
@@ -226,7 +338,7 @@ extension EncodeBuffer {
|
||||
@discardableResult
|
||||
public mutating func markStopPoint() -> Int {
|
||||
if case .client = mode {
|
||||
stopPoints.append(buffer.writerIndex)
|
||||
stopPoints.append(totalWritten)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
@@ -240,7 +352,11 @@ extension EncodeBuffer {
|
||||
@discardableResult
|
||||
@inlinable
|
||||
public mutating func writeString(_ string: String) -> Int {
|
||||
self.buffer.writeString(string)
|
||||
// Contiguous for every native string. A foreign one, e.g. a bridged non-ASCII `NSString`,
|
||||
// has to be transcoded, which allocates.
|
||||
let written = string.utf8.withContiguousStorageIfAvailable { self.appendBytes(UnsafeRawBufferPointer($0)) }
|
||||
if let written { return written }
|
||||
return Array(string.utf8).withUnsafeBytes { self.appendBytes($0) }
|
||||
}
|
||||
|
||||
/// Writes a single byte to the buffer.
|
||||
@@ -274,7 +390,7 @@ extension EncodeBuffer {
|
||||
/// interpolation machinery and heap-allocates as soon as the result exceeds 15 UTF-8 bytes,
|
||||
/// whereas this formats the digits into a stack buffer and copies them once.
|
||||
///
|
||||
/// Unlike ``writeBytes(_:)``, this is never redacted in ``loggingMode`` — the numbers
|
||||
/// Unlike ``writeBytes(_:)-1nrmp``, this is never redacted in ``loggingMode`` — the numbers
|
||||
/// written here are lengths, offsets and identifiers, not payload.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -322,30 +438,52 @@ extension EncodeBuffer {
|
||||
/// - Returns: The number of bytes written (in logging mode, this is the length of the placeholder).
|
||||
@discardableResult
|
||||
@inlinable
|
||||
public mutating func writeBytes<Bytes: Sequence>(_ bytes: Bytes) -> Int where Bytes.Element == UInt8 {
|
||||
guard loggingMode else {
|
||||
return self.buffer.writeBytes(bytes)
|
||||
public mutating func writeBytes(_ bytes: some Collection<UInt8>) -> Int {
|
||||
guard !loggingMode else {
|
||||
return self.writeRedactedByteCount(bytes.count)
|
||||
}
|
||||
return self.writeRedactedByteCount(bytes.reduce(into: 0) { count, _ in count += 1 })
|
||||
// Every caller in the encoder passes an array, an `ArraySlice`, or a `String.UTF8View`, all
|
||||
// of which take the contiguous path.
|
||||
if let written = bytes.withContiguousStorageIfAvailable({ buffer -> Int in
|
||||
guard let base = buffer.baseAddress else { return 0 }
|
||||
return self.appendBytes(UnsafeRawBufferPointer(start: base, count: buffer.count))
|
||||
}) {
|
||||
return written
|
||||
}
|
||||
let contiguous = ContiguousArray(bytes)
|
||||
return contiguous.withUnsafeBytes { self.appendBytes($0) }
|
||||
}
|
||||
|
||||
/// Writes a `ByteBuffer` to the buffer.
|
||||
/// Writes raw message bytes to the buffer.
|
||||
///
|
||||
/// When ``loggingMode`` is enabled, this writes a placeholder like `[N bytes]`
|
||||
/// instead of the actual binary data.
|
||||
/// This is the overload the four raw-payload model cases use — `messageBytes`, `catenateData`,
|
||||
/// `continuationResponse` and `streamingBytes`. It exists so that a multi-megabyte literal can be
|
||||
/// handed to the encoder without being copied, which is what an ``IMAPBuffer`` gives a caller
|
||||
/// that received it from the parser or wrapped its own memory in it.
|
||||
///
|
||||
/// - Parameter buffer: The buffer to write.
|
||||
/// Whether the bytes are actually copied is the sink's decision: ``IMAPOutputBuffer`` keeps a
|
||||
/// large region by reference and copies a small one, so forwarding a `FETCH` literal into an
|
||||
/// `APPEND` costs nothing.
|
||||
///
|
||||
/// When ``loggingMode`` is enabled, this writes a placeholder like `[N bytes]` instead of the
|
||||
/// payload, matching the other byte-writing primitives.
|
||||
///
|
||||
/// - Parameter region: The bytes to write.
|
||||
/// - Returns: The number of bytes written (in logging mode, this is the length of the placeholder).
|
||||
@discardableResult
|
||||
@inlinable
|
||||
public mutating func writeBuffer(_ buffer: inout ByteBuffer) -> Int {
|
||||
guard loggingMode else {
|
||||
return self.buffer.writeBuffer(&buffer)
|
||||
public mutating func writeBytes(_ region: IMAPBuffer) -> Int {
|
||||
guard !loggingMode else {
|
||||
return self.writeRedactedByteCount(region.count)
|
||||
}
|
||||
return self.writeRedactedByteCount(buffer.readableBytes)
|
||||
// Flush first: the sink must see the bytes in order, and gets the region itself, uncopied.
|
||||
self.flushStaging()
|
||||
self.sink.append(region)
|
||||
self.totalWritten += region.count
|
||||
return region.count
|
||||
}
|
||||
|
||||
/// Appends bytes to the buffer with no redaction.
|
||||
/// Appends bytes with no redaction: into ``staging`` if they fit, else to the sink.
|
||||
///
|
||||
/// The primitive the redaction-exempt writers (``writeByte(_:)``,
|
||||
/// ``writeDecimal(_:minimumDigits:)``) and the already-redacted ones build on. A caller that
|
||||
@@ -356,7 +494,32 @@ extension EncodeBuffer {
|
||||
@discardableResult
|
||||
@inlinable
|
||||
mutating func appendBytes(_ bytes: UnsafeRawBufferPointer) -> Int {
|
||||
self.buffer.writeBytes(bytes)
|
||||
let count = bytes.count
|
||||
self.totalWritten += count
|
||||
guard count < Self.stagingCapacity else {
|
||||
self.flushStaging()
|
||||
self.sink.append(bytes)
|
||||
return count
|
||||
}
|
||||
guard let source = bytes.baseAddress else { return count }
|
||||
if count > Self.stagingCapacity - self.stagedCount {
|
||||
self.flushStaging()
|
||||
}
|
||||
let offset = self.stagedCount
|
||||
withUnsafeMutableBytes(of: &self.staging) { staging in
|
||||
staging.baseAddress!.advanced(by: offset).copyMemory(from: source, byteCount: count)
|
||||
}
|
||||
self.stagedCount += count
|
||||
return count
|
||||
}
|
||||
|
||||
/// Hands the staged bytes to the sink.
|
||||
@inlinable
|
||||
mutating func flushStaging() {
|
||||
guard self.stagedCount > 0 else { return }
|
||||
let count = self.stagedCount
|
||||
self.stagedCount = 0
|
||||
withUnsafeBytes(of: &self.staging) { self.sink.append(UnsafeRawBufferPointer(rebasing: $0.prefix(count))) }
|
||||
}
|
||||
|
||||
/// Writes the `[123 bytes]` placeholder that ``loggingMode`` substitutes for payload bytes.
|
||||
@@ -375,7 +538,39 @@ extension EncodeBuffer {
|
||||
@inlinable
|
||||
public mutating func clear() {
|
||||
self.stopPoints.removeAll()
|
||||
self.buffer.clear()
|
||||
self.sink.removeAll()
|
||||
self.stagedCount = 0
|
||||
self.totalWritten = 0
|
||||
self.handedOut = 0
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Equatable & Hashable
|
||||
|
||||
extension EncodeBuffer: Hashable {
|
||||
/// Compares two buffers by their state and by the bytes they are holding.
|
||||
///
|
||||
/// The bytes are compared byte by byte rather than region by region, so two buffers holding the
|
||||
/// same bytes are equal however their sinks happened to split them up. That matters because the
|
||||
/// split depends on segment sizes and on whether a payload was retained or copied.
|
||||
///
|
||||
/// - Complexity: O(``pendingByteCount``).
|
||||
public static func == (lhs: EncodeBuffer, rhs: EncodeBuffer) -> Bool {
|
||||
lhs.mode == rhs.mode && lhs.loggingMode == rhs.loggingMode && lhs.stopPoints == rhs.stopPoints
|
||||
&& lhs.totalWritten == rhs.totalWritten && lhs.handedOut == rhs.handedOut
|
||||
&& lhs.makePendingBufferList() == rhs.makePendingBufferList()
|
||||
}
|
||||
|
||||
/// Hashes the buffer's state and the bytes it is holding.
|
||||
///
|
||||
/// - Complexity: O(``pendingByteCount``).
|
||||
public func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(mode)
|
||||
hasher.combine(loggingMode)
|
||||
hasher.combine(stopPoints)
|
||||
hasher.combine(totalWritten)
|
||||
hasher.combine(handedOut)
|
||||
hasher.combine(makePendingBufferList())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user