-
Notifications
You must be signed in to change notification settings - Fork 162
/
Copy pathAsyncRace.swift
57 lines (52 loc) · 2.1 KB
/
AsyncRace.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2025 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
//
//===----------------------------------------------------------------------===//
/// Returns the value or throws an error, from the first completed or failed operation.
public func race(_ operations: (@Sendable () async throws -> Void)...) async throws {
try await race(operations)
}
/// Returns the value or throws an error, from the first completed or failed operation.
public func race<T: Sendable>(_ operations: (@Sendable () async throws -> T)...) async throws -> T? {
try await race(operations)
}
/// Returns the value or throws an error, from the first completed or failed operation.
public func race<T: Sendable>(_ operations: [@Sendable () async throws -> T]) async throws -> T? {
try await withThrowingTaskGroup(of: T.self) { group in
operations.forEach { operation in
group.addTask { try await operation() }
}
defer {
group.cancelAll()
}
return try await group.next()
}
}
/// Returns the value or throws an error, from the first completed or failed operation.
public func race<T: Sendable>(_ operations: (@Sendable () async throws -> T?)...) async throws -> T? {
try await race(operations)
}
/// Returns the value or throws an error, from the first completed or failed operation.
public func race<T: Sendable>(_ operations: [@Sendable () async throws -> T?]) async throws -> T? {
try await withThrowingTaskGroup(of: T?.self) { group in
operations.forEach { operation in
group.addTask { try await operation() }
}
defer {
group.cancelAll()
}
let value = try await group.next()
switch value {
case .none:
return nil
case let .some(value):
return value
}
}
}