Skip to content
Merged
Show file tree
Hide file tree
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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
.DS_Store
Package.resolved
/.build
.build*/
/Packages
xcuserdata/
DerivedData/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,12 +60,73 @@ public protocol FileOperationScheduler<FileHandle>: OperationScheduler {
at offset: Int64
) async throws(IOError) -> Int

/// Reads once from the given offset of a file into a buffer that the scheduler provides.
///
/// - Parameters:
/// - file: The file to read from.
/// - offset: The offset in the file to read from.
/// - Returns: The buffer with the bytes that were read, which the caller has to return. It holds no bytes if the
/// offset is at or behind the end of the file.
func read(file: borrowing FileHandle, at offset: Int64) async throws(IOError) -> LeasedBuffer

/// Closes a file.
///
/// - Parameter file: The file to close.
func close(file: consuming FileHandle) async throws(IOError)
}

@available(anyAppleOS 27.0, *)
extension FileOperationScheduler {
/// Reads once from the given offset of a file and hands the bytes that were read to the closure.
///
/// - Parameters:
/// - file: The file to read from.
/// - offset: The offset in the file to read from.
/// - body: The closure to invoke with the bytes that were read. Its span is empty if the offset is at or
/// behind the end of the file.
/// - Returns: Whatever is returned by `body`.
// TODO: This closure should become throwing by adopting EitherError
public func read<Return: ~Copyable>(
file: borrowing FileHandle,
at offset: Int64,
body: (inout OutputRawSpan) async -> Return
) async throws(IOError) -> Return {
var buffer = try await self.read(file: file, at: offset)
let result = await buffer.edit(body)
buffer.return()
return result
}

/// Writes the bytes that the closure appends to the given offset of a file.
///
/// - Parameters:
/// - file: The file to write to.
/// - offset: The offset in the file to write to.
/// - body: The closure to invoke with the empty span of a buffer to fill.
/// - Returns: Whatever is returned by `body`.
// TODO: This closure should become throwing by adopting EitherError
public func write<Return: ~Copyable>(
file: borrowing FileHandle,
at offset: Int64,
body: (inout OutputRawSpan) async -> Return
) async throws(IOError) -> Return {
var buffer = self.leaseBuffer()
let result = await buffer.edit(body)
do throws(IOError) {
var written = 0
while written < buffer.count {
let bytes = buffer.bytes.extracting(droppingFirst: written)
written += try await self.write(file: file, from: bytes, at: offset + Int64(written))
}
} catch {
buffer.return()
throw error
}
buffer.return()
return result
}
}

/// How a scheduler opens a file.
///
/// The high-level file types turn their open options into this, so a scheduler only deals with one
Expand Down
15 changes: 15 additions & 0 deletions Sources/PlatformExecutors/IO/LowLevel/LeasedBuffer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
//
//===----------------------------------------------------------------------===//

// swift-format-ignore-file: AmbiguousTrailingClosureOverload
#if ExperimentalIO
/// A leased buffer that must be manually returned when you are done using it.
///
Expand Down Expand Up @@ -118,6 +119,20 @@ public struct LeasedBuffer: ~Copyable, @unchecked Sendable {
return result
}

/// 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<Return: ~Copyable>(
_ body: (inout OutputRawSpan) async -> Return
) async -> Return {
var span = unsafe OutputRawSpan(buffer: self.memory, initializedCount: self.initializedCount)
let result = await 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,11 @@
/// A scheduler cancels an operation when the calling task is cancelled, and escalates the priority of an
/// operation when the priority of the calling task is escalated, if the platform supports it.
@available(anyAppleOS 27.0, *)
public protocol OperationScheduler: AnyObject, Sendable {}
public protocol OperationScheduler: AnyObject, Sendable {
/// Leases out an empty buffer of the scheduler.
///
/// - Returns: An empty buffer.
// TODO: Revisit if this should belong here or onto a `BufferPool` protocol.
func leaseBuffer() -> LeasedBuffer
}
#endif
29 changes: 29 additions & 0 deletions Sources/PlatformExecutors/IO/LowLevel/ReceivedDatagram.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//===----------------------------------------------------------------------===//
//
// 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 datagram that a scheduler received into one of its buffers.
@available(anyAppleOS 27.0, *)
@frozen
public struct ReceivedDatagram: ~Copyable, Sendable {
/// The buffer with the bytes of the datagram, which has to be returned.
public var buffer: LeasedBuffer

/// The address of the sender.
public var sender: SocketAddress

public init(buffer: consuming LeasedBuffer, sender: SocketAddress) {
self.buffer = buffer
self.sender = sender
}
}
#endif
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,13 @@ public protocol TCPSocketOperationScheduler<TCPListener, TCPConnection>: Operati
/// - Returns: The number of bytes written. This can be less than the number of bytes in the buffer.
func write(connection: borrowing TCPConnection, from buffer: RawSpan) async throws(IOError) -> Int

/// Reads once from a socket into a buffer that the scheduler provides.
///
/// - Parameter connection: The socket to read from.
/// - Returns: The buffer with the bytes that were read, which the caller has to return. It holds no bytes if the
/// peer closed its side of the connection.
func read(connection: borrowing TCPConnection) async throws(IOError) -> LeasedBuffer

/// Shuts down one or both directions of a socket.
///
/// Shutting down the write direction sends a `FIN` to the peer, which
Expand Down Expand Up @@ -110,4 +117,51 @@ public protocol TCPSocketOperationScheduler<TCPListener, TCPConnection>: Operati
/// - Returns: The address that the listening socket is bound to.
func localAddress(of listener: borrowing TCPListener) throws(IOError) -> SocketAddress
}

@available(anyAppleOS 27.0, *)
extension TCPSocketOperationScheduler {
/// Reads once from a socket and hands the bytes that were read to the closure.
///
/// - Parameters:
/// - connection: The socket to read from.
/// - body: The closure to invoke with the bytes that were read. Its span is empty if the peer closed its
/// side of the connection.
/// - Returns: Whatever is returned by `body`.
// TODO: This closure should become throwing by adopting EitherError
public func read<Return: ~Copyable>(
connection: borrowing TCPConnection,
body: (inout OutputRawSpan) async -> Return
) async throws(IOError) -> Return {
var buffer = try await self.read(connection: connection)
let result = await buffer.edit(body)
buffer.return()
return result
}

/// Writes the bytes that the closure appends to a socket.
///
/// - Parameters:
/// - connection: The socket to write to.
/// - body: The closure to invoke with the empty span of a buffer to fill.
/// - Returns: Whatever is returned by `body`.
// TODO: This closure should become throwing by adopting EitherError
public func write<Return: ~Copyable>(
connection: borrowing TCPConnection,
body: (inout OutputRawSpan) async -> Return
) async throws(IOError) -> Return {
var buffer = self.leaseBuffer()
let result = await buffer.edit(body)
do throws(IOError) {
var written = 0
while written < buffer.count {
written += try await self.write(connection: connection, from: buffer.bytes.extracting(droppingFirst: written))
}
} catch {
buffer.return()
throw error
}
buffer.return()
return result
}
}
#endif
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,18 @@ public protocol UDPSocketOperationScheduler<UDPSocket>: OperationScheduler {
/// - Returns: The number of bytes sent.
func write(socket: borrowing UDPSocket, from buffer: RawSpan) async throws(IOError) -> Int

/// Receives one datagram into a buffer that the scheduler provides.
///
/// - Parameter socket: The socket to receive from.
/// - Returns: The datagram, whose buffer the caller has to return.
func receive(socket: borrowing UDPSocket) async throws(IOError) -> ReceivedDatagram

/// Receives one datagram from the peer of a connected socket into a buffer that the scheduler provides.
///
/// - Parameter socket: The connected socket to read from.
/// - Returns: The buffer with the bytes of the datagram, which the caller has to return.
func read(socket: borrowing UDPSocket) async throws(IOError) -> LeasedBuffer

/// Closes a socket.
///
/// - Parameter socket: The socket to close.
Expand All @@ -106,4 +118,96 @@ public protocol UDPSocketOperationScheduler<UDPSocket>: OperationScheduler {
/// - Returns: The address of the peer.
func remoteAddress(of socket: borrowing UDPSocket) throws(IOError) -> SocketAddress
}

@available(anyAppleOS 27.0, *)
extension UDPSocketOperationScheduler {
/// Receives one datagram and hands its bytes and the address of the sender to the closure.
///
/// - Parameters:
/// - socket: The socket to receive from.
/// - body: The closure to invoke with the bytes of the datagram and the address of the sender.
/// - Returns: Whatever is returned by `body`.
// TODO: This closure should become throwing by adopting EitherError
public func receive<Return: ~Copyable>(
socket: borrowing UDPSocket,
body: (inout OutputRawSpan, SocketAddress) async -> Return
) async throws(IOError) -> Return {
var datagram = try await self.receive(socket: socket)
let sender = datagram.sender
let result = await datagram.buffer.edit { span in await body(&span, sender) }
datagram.buffer.return()
return result
}

/// Sends the datagram that the closure appends to the given address. Nothing is sent if the closure appends
/// nothing.
///
/// - Parameters:
/// - socket: The socket to send from.
/// - address: The address to send the datagram to.
/// - body: The closure to invoke with the empty span of a buffer to fill.
/// - Returns: Whatever is returned by `body`.
// TODO: This closure should become throwing by adopting EitherError
public func send<Return: ~Copyable>(
socket: borrowing UDPSocket,
to address: SocketAddress,
body: (inout OutputRawSpan) async -> Return
) async throws(IOError) -> Return {
var buffer = self.leaseBuffer()
let result = await buffer.edit(body)
do throws(IOError) {
if !buffer.isEmpty {
_ = try await self.send(socket: socket, from: buffer.bytes, to: address)
}
} catch {
buffer.return()
throw error
}
buffer.return()
return result
}

/// Reads one datagram from the peer of a connected socket and hands its bytes to the closure.
///
/// - Parameters:
/// - socket: The connected socket to read from.
/// - body: The closure to invoke with the bytes of the datagram.
/// - Returns: Whatever is returned by `body`.
// TODO: This closure should become throwing by adopting EitherError
public func read<Return: ~Copyable>(
socket: borrowing UDPSocket,
body: (inout OutputRawSpan) async -> Return
) async throws(IOError) -> Return {
var buffer = try await self.read(socket: socket)
let result = await buffer.edit(body)
buffer.return()
return result
}

/// Sends the datagram that the closure appends to the peer of a connected socket. Nothing is sent if the
/// closure appends nothing.
///
/// - Parameters:
/// - socket: The connected socket to write to.
/// - body: The closure to invoke with the empty span of a buffer to fill.
/// - Returns: Whatever is returned by `body`.
// TODO: This closure should become throwing by adopting EitherError
public func write<Return: ~Copyable>(
socket: borrowing UDPSocket,
body: (inout OutputRawSpan) async -> Return
) async throws(IOError) -> Return {
var buffer = self.leaseBuffer()
let result = await buffer.edit(body)
do throws(IOError) {
if !buffer.isEmpty {
_ = try await self.write(socket: socket, from: buffer.bytes)
}
} catch {
buffer.return()
throw error
}
buffer.return()
return result
}
}
#endif
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,15 @@ extension PThreadExecutor: TCPSocketOperationScheduler {
}
}

// TODO: Implement the operations that lease buffers.
package func leaseBuffer() -> LeasedBuffer {
fatalError("Leasing buffers is not implemented yet")
}

package func read(connection: borrowing TCPConnection) async throws(IOError) -> LeasedBuffer {
fatalError("Leasing buffers is not implemented yet")
}

package func shutdown(
connection: borrowing TCPConnection,
direction: SocketShutdownDirection
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,15 @@ extension PThreadExecutor: UDPSocketOperationScheduler {
}
}

// TODO: Implement the operations that lease buffers.
package func receive(socket: borrowing UDPSocket) async throws(IOError) -> ReceivedDatagram {
fatalError("Leasing buffers is not implemented yet")
}

package func read(socket: borrowing UDPSocket) async throws(IOError) -> LeasedBuffer {
fatalError("Leasing buffers is not implemented yet")
}

package func close(socket: consuming UDPSocket) async throws(IOError) {
let fileDescriptor = socket.takeFileDescriptor()
try await unsafe self.perform(.close(fileDescriptor: fileDescriptor)) { continuation in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@ extension PThreadTaskExecutor: FileOperationScheduler {
)
}

// TODO: Implement the operations that lease buffers.
public func read(file: borrowing FileHandle, at offset: Int64) async throws(IOError) -> LeasedBuffer {
fatalError("Leasing buffers is not implemented yet")
}

public func close(file: consuming FileHandle) async throws(IOError) {
if self.performsFileOperations {
return try await self.current().closeFile(file)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,15 @@ extension PThreadTaskExecutor: TCPSocketOperationScheduler {
try await self.current().write(connection: connection, from: buffer)
}

// TODO: Implement the operations that lease buffers.
public func leaseBuffer() -> LeasedBuffer {
fatalError("Leasing buffers is not implemented yet")
}

public func read(connection: borrowing TCPConnection) async throws(IOError) -> LeasedBuffer {
fatalError("Leasing buffers is not implemented yet")
}

public func shutdown(
connection: borrowing TCPConnection,
direction: SocketShutdownDirection
Expand Down
Loading
Loading