Skip to content

Commit 04fd217

Browse files
committed
AsyncSocketPool loop
1 parent 608fac2 commit 04fd217

File tree

1 file changed

+25
-26
lines changed

1 file changed

+25
-26
lines changed

Sources/Socket/AsyncSocket.swift

Lines changed: 25 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -49,28 +49,16 @@ struct AsyncSocket: Sendable {
4949
}
5050

5151
func accept() async throws -> AsyncSocket {
52-
while true {
53-
do {
54-
let file = try socket.accept().file
55-
let socket = Socket(file: file)
56-
return try AsyncSocket(socket: socket, pool: pool)
57-
} catch SocketError.blocked {
58-
try await pool.suspendUntilReady(for: [.read, .write], on: socket)
59-
} catch {
60-
throw error
61-
}
52+
try await pool.loopUntilReady(for: [.read, .write], on: socket) {
53+
let file = try socket.accept().file
54+
let socket = Socket(file: file)
55+
return try AsyncSocket(socket: socket, pool: pool)
6256
}
6357
}
6458

6559
func read() async throws -> UInt8 {
66-
while true {
67-
do {
68-
return try socket.read()
69-
} catch SocketError.blocked {
70-
try await pool.suspendUntilReady(for: .read, on: socket)
71-
} catch {
72-
throw error
73-
}
60+
try await pool.loopUntilReady(for: .read, on: socket) {
61+
try socket.read()
7462
}
7563
}
7664

@@ -99,14 +87,8 @@ struct AsyncSocket: Sendable {
9987
}
10088

10189
private func write(_ data: Data, from index: Data.Index) async throws -> Data.Index {
102-
while true {
103-
do {
104-
return try socket.write(data, from: index)
105-
} catch SocketError.blocked {
106-
try await pool.suspendUntilReady(for: .write, on: socket)
107-
} catch {
108-
throw error
109-
}
90+
try await pool.loopUntilReady(for: .write, on: socket) {
91+
try socket.write(data, from: index)
11092
}
11193
}
11294

@@ -123,6 +105,23 @@ struct AsyncSocket: Sendable {
123105
}
124106
}
125107

108+
private extension AsyncSocketPool {
109+
110+
func loopUntilReady<T>(for events: Socket.Events, on socket: Socket, body: () throws -> T) async throws -> T {
111+
var result: T?
112+
repeat {
113+
do {
114+
result = try body()
115+
} catch SocketError.blocked {
116+
try await suspendUntilReady(for: events, on: socket)
117+
} catch {
118+
throw error
119+
}
120+
} while result == nil
121+
return result!
122+
}
123+
}
124+
126125
struct ByteSequence: ChunkedAsyncSequence, ChunkedAsyncIteratorProtocol {
127126
typealias Element = UInt8
128127

0 commit comments

Comments
 (0)