Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add async variant of ByteBuffer.withUnsafeReadableBytes. #2694

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions Sources/NIOCore/ByteBuffer-core.swift
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,21 @@ public struct ByteBuffer {
return try body(.init(fastRebase: self._slicedStorageBuffer[range]))
}

/// Yields a buffer pointer containing this `ByteBuffer`'s readable bytes to the async closure.
///
/// - warning: Do not escape the pointer from the closure for later use.
///
/// - parameters:
/// - body: The closure that will accept the yielded bytes.
/// - returns: The value returned by `body`.
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
@inlinable
public func withUnsafeReadableBytes<T>(_ body: (UnsafeRawBufferPointer) async throws -> T) async rethrows -> T {
// This is safe, writerIndex >= readerIndex
let range = Range<Int>(uncheckedBounds: (lower: self.readerIndex, upper: self.writerIndex))
return try await body(.init(fastRebase: self._slicedStorageBuffer[range]))
}

/// Yields a buffer pointer containing this `ByteBuffer`'s readable bytes. You may hold a pointer to those bytes
/// even after the closure returned iff you model the lifetime of those bytes correctly using the `Unmanaged`
/// instance. If you don't require the pointer after the closure returns, use `withUnsafeReadableBytes`.
Expand Down