Skip to content

Commit

Permalink
awaitingAll{Read,Written} to socket API
Browse files Browse the repository at this point in the history
make it clear whether socket APIs need to handle short reads/writes
  • Loading branch information
lhoward committed Jan 12, 2024
1 parent 51df783 commit cee72cb
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 19 deletions.
2 changes: 1 addition & 1 deletion Examples/IORingTCPEcho/IORingTCPEcho.swift
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public struct IORingTCPEcho {
var buffer = [UInt8](repeating: 0, count: 1)
more = try await client.read(into: &buffer, count: 1) == 1
if more {
guard try await client.write(buffer, count: 1) == 1 else {
guard try await client.write(buffer, count: 1, awaitingAllWritten: false) == 1 else {
break
}
}
Expand Down
42 changes: 24 additions & 18 deletions Sources/IORingUtils/Socket.swift
Original file line number Diff line number Diff line change
Expand Up @@ -191,30 +191,36 @@ public struct Socket: CustomStringConvertible, Equatable, Hashable, Sendable {

public func read(into buffer: inout [UInt8], count: Int) async throws -> Int {
guard let fileHandle else { throw Errno.badFileDescriptor }
return try await ring.read(
into: &buffer,
count: count,
offset: -1,
from: fileHandle
)

return try await ring.read(into: &buffer, count: count, from: fileHandle)
}

public func read(count: Int) async throws -> [UInt8] {
public func read(count: Int, awaitingAllRead: Bool) async throws -> [UInt8] {
guard let fileHandle else { throw Errno.badFileDescriptor }
return try await ring.read(
count: count,
from: fileHandle
)

var buffer = [UInt8]()

repeat {
buffer += try await ring.read(count: count, from: fileHandle)
} while awaitingAllRead && buffer.count < count

return buffer
}

public func write(_ buffer: [UInt8], count: Int) async throws -> Int {
public func write(_ buffer: [UInt8], count: Int, awaitingAllWritten: Bool) async throws -> Int {
guard let fileHandle else { throw Errno.badFileDescriptor }
return try await ring.write(
buffer,
count: count,
offset: -1,
to: fileHandle
)

var nwritten = 0

repeat {
nwritten += try await ring.write(
Array(buffer[nwritten..<count]),
count: count - nwritten,
to: fileHandle
)
} while awaitingAllWritten && nwritten < count

return nwritten
}

public func receive(count: Int) async throws -> [UInt8] {
Expand Down

0 comments on commit cee72cb

Please sign in to comment.