diff --git a/Sources/PlatformExecutors/IO/LowLevel/LeasedBuffer.swift b/Sources/PlatformExecutors/IO/LowLevel/LeasedBuffer.swift new file mode 100644 index 0000000..9c28688 --- /dev/null +++ b/Sources/PlatformExecutors/IO/LowLevel/LeasedBuffer.swift @@ -0,0 +1,133 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#if ExperimentalIO +/// A leased buffer that must be manually returned when you are done using it. +/// +/// ```swift +/// var buffer = try await connection.read() +/// parse(buffer.bytes) +/// buffer.return() +/// ``` +// TODO: Evaluate whether a backend like DPDK fits. +// TODO: Alternatively this could be modelled with custom allocators. +@safe +@available(anyAppleOS 27.0, *) +public struct LeasedBuffer: ~Copyable, @unchecked Sendable { + /// The memory of the buffer. This is the whole capacity, and the bytes that were transferred are its start. + private let memory: UnsafeMutableRawBufferPointer + + /// Gives the memory back to where it came from. + private let release: @Sendable (UnsafeMutableRawBufferPointer) -> Void + + /// The number of bytes of the buffer that hold data. + private var initializedCount: Int + + /// Whether the buffer was returned. + // TODO: Once we have call once closures we should mark release as such and drop this bool to use discard self + private var isReturned = false + + /// The number of bytes of the buffer that hold data. + public var count: Int { + self.initializedCount + } + + /// The number of bytes that the buffer can hold. + public var capacity: Int { + unsafe self.memory.count + } + + /// Whether the buffer holds no data. + public var isEmpty: Bool { + self.initializedCount == 0 + } + + /// The bytes that the buffer holds. + public var bytes: RawSpan { + @_lifetime(borrow self) + borrowing get { + let span = unsafe RawSpan(_unsafeBytes: UnsafeRawBufferPointer(rebasing: self.memory[.. Void + ) { + precondition( + initializedCount >= 0 && initializedCount <= memory.count, + "The initialized count exceeds the memory" + ) + unsafe self.memory = memory + unsafe self.release = release + self.initializedCount = initializedCount + } + + /// A lease without any memory. + package static func empty() -> LeasedBuffer { + unsafe LeasedBuffer( + adopting: .init(start: nil, count: 0), + initializedCount: 0, + release: { _ in } + ) + } + + /// Arbitrarily edit the storage underlying this buffer by invoking a + /// user-supplied closure with a mutable `OutputSpan` view over it. + /// + /// - Parameter body: The closure to invoke with the span. + /// - Returns: Whatever is returned by `body`. + public mutating func edit( + _ body: (inout OutputRawSpan) -> Return + ) -> Return { + var span = unsafe OutputRawSpan(buffer: self.memory, initializedCount: self.initializedCount) + let result = body(&span) + self.initializedCount = span.byteCount + return result + } + + /// Gives the buffer back to where it came from. + public consuming func `return`() { + unsafe self.release(self.memory) + self.isReturned = true + } + + deinit { + if !self.isReturned { + fatalError("A LeasedBuffer was destroyed without being returned.") + } + } +} +#endif diff --git a/Tests/PlatformExecutorsTests/ProvidedBufferTests.swift b/Tests/PlatformExecutorsTests/ProvidedBufferTests.swift new file mode 100644 index 0000000..6f70728 --- /dev/null +++ b/Tests/PlatformExecutorsTests/ProvidedBufferTests.swift @@ -0,0 +1,67 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#if ExperimentalIO +#if os(Linux) || os(FreeBSD) || canImport(Darwin) + +import BasicContainers +import Synchronization +import Testing +@_spi(ExperimentalScheduling) @_spi(ConcurrencyExecutors) @_spi(ExperimentalCustomExecutors) import _Concurrency +@_spi(ExperimentalScheduling) @_spi(ConcurrencyExecutors) @_spi(ExperimentalCustomExecutors) import PlatformExecutors + +#if canImport(Glibc) +import Glibc +#elseif canImport(Darwin) +import Darwin +#endif + +/// Tests the operations that read into, and write from, buffers that the executor provides. +/// +/// With `io_uring` the kernel picks the buffers that reads fill, so these tests are about handing the buffers +/// out and taking them back: a lost buffer drains the ring, which shows as reads that fall back to transient +/// allocations. +@Suite +struct ProvidedBufferTests { + @Test + @available(anyAppleOS 27.0, *) + func aLeaseThatIsNotReturnedTraps() async { + await #expect(processExitsWith: .failure) { + _ = unsafe LeasedBuffer( + adopting: .allocate(byteCount: 16, alignment: 16), + initializedCount: 0, + release: { memory in unsafe memory.deallocate() } + ) + } + } + + @Test + @available(anyAppleOS 27.0, *) + func returningALeaseCallsTheReleaseClosureWithTheMemoryOnce() async { + let released = Mutex<[Int]>([]) + let memory = UnsafeMutableRawBufferPointer.allocate(byteCount: 16, alignment: 16) + defer { unsafe memory.deallocate() } + let buffer = unsafe LeasedBuffer( + adopting: memory, + initializedCount: 3, + release: { returned in + released.withLock { $0.append(returned.count) } + } + ) + #expect(buffer.count == 3) + #expect(buffer.capacity == 16) + buffer.return() + #expect(released.withLock { $0 } == [16]) + } +} +#endif +#endif