mirror of
https://github.com/apple/swift-async-algorithms
synced 2026-11-24 04:17:52 +00:00
Rework Task.first to a better name/behavior of Task.select (#21)
* Rework Task.first to a better name/behavior of Task.select * Downgrade UnsafeResumption to internal
This commit is contained in:
1 parent
b015c5e49e
commit
21520e710c
6 files changed
+124
-138
No files matched your search
@@ -45,7 +45,7 @@ where
|
||||
}
|
||||
|
||||
mutating func apply(_ task1: Task<Partial, Never>?, _ task2: Task<Partial, Never>?) async rethrows -> Element? {
|
||||
switch await Task.first([task1, task2].compactMap { $0 }) {
|
||||
switch await Task.select([task1, task2].compactMap { $0 }).value {
|
||||
case .first(let result, let iterator):
|
||||
do {
|
||||
guard let value = try state.0.resolve(result, iterator) else {
|
||||
|
||||
@@ -48,7 +48,7 @@ where
|
||||
}
|
||||
|
||||
mutating func apply(_ task1: Task<Partial, Never>?, _ task2: Task<Partial, Never>?, _ task3: Task<Partial, Never>?) async rethrows -> Element? {
|
||||
switch await Task.first([task1, task2, task3].compactMap { $0 }) {
|
||||
switch await Task.select([task1, task2, task3].compactMap { $0 }).value {
|
||||
case .first(let result, let iterator):
|
||||
do {
|
||||
guard let value = try state.0.resolve(result, iterator) else {
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Async Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2022 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
struct TaskFirstState<Success: Sendable, Failure: Error>: Sendable {
|
||||
var continuation: UnsafeContinuation<Success, Failure>?
|
||||
var tasks: [Task<Success, Failure>]? = []
|
||||
|
||||
mutating func add(_ task: Task<Success, Failure>) -> Task<Success, Failure>? {
|
||||
if var tasks = tasks {
|
||||
tasks.append(task)
|
||||
self.tasks = tasks
|
||||
return nil
|
||||
} else {
|
||||
return task
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Task {
|
||||
/// Determine the first result of a sequence of tasks.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - tasks: The running tasks to obtain a result from
|
||||
/// - Returns: The first result or thrown error from the running tasks
|
||||
static func first<Tasks: Sequence>(
|
||||
_ tasks: Tasks
|
||||
) async throws -> Success
|
||||
where Tasks.Element == Task<Success, Failure>, Failure == Error {
|
||||
let state = ManagedCriticalState(TaskFirstState<Success, Failure>())
|
||||
return try await withTaskCancellationHandler {
|
||||
let tasks = state.withCriticalRegion { state -> [Task<Success, Failure>] in
|
||||
defer { state.tasks = nil }
|
||||
return state.tasks ?? []
|
||||
}
|
||||
for task in tasks {
|
||||
task.cancel()
|
||||
}
|
||||
} operation: {
|
||||
try await withUnsafeThrowingContinuation { continuation in
|
||||
state.withCriticalRegion { state in
|
||||
state.continuation = continuation
|
||||
}
|
||||
for task in tasks {
|
||||
Task<Void, Never> {
|
||||
let result = await task.result
|
||||
state.withCriticalRegion { state -> UnsafeContinuation<Success, Failure>? in
|
||||
defer { state.continuation = nil }
|
||||
return state.continuation
|
||||
}?.resume(with: result)
|
||||
}
|
||||
state.withCriticalRegion { state in
|
||||
state.add(task)
|
||||
}?.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Determine the first result of a list of tasks.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - tasks: The running tasks to obtain a result from
|
||||
/// - Returns: The first result or thrown error from the running tasks
|
||||
static func first(
|
||||
_ tasks: Task<Success, Failure>...
|
||||
) async throws -> Success where Failure == Error {
|
||||
try await first(tasks)
|
||||
}
|
||||
}
|
||||
|
||||
extension Task where Failure == Never {
|
||||
/// Determine the first result of a sequence of tasks.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - tasks: The running tasks to obtain a result from
|
||||
/// - Returns: The first result from the running tasks
|
||||
static func first<Tasks: Sequence>(
|
||||
_ tasks: Tasks
|
||||
) async -> Success
|
||||
where Tasks.Element == Task<Success, Never> {
|
||||
let state = ManagedCriticalState(TaskFirstState<Success, Failure>())
|
||||
return await withTaskCancellationHandler {
|
||||
let tasks = state.withCriticalRegion { state -> [Task<Success, Failure>] in
|
||||
defer { state.tasks = nil }
|
||||
return state.tasks ?? []
|
||||
}
|
||||
for task in tasks {
|
||||
task.cancel()
|
||||
}
|
||||
} operation: {
|
||||
await withUnsafeContinuation { continuation in
|
||||
state.withCriticalRegion { state in
|
||||
state.continuation = continuation
|
||||
}
|
||||
for task in tasks {
|
||||
Task<Void, Never> {
|
||||
let result = await task.result
|
||||
state.withCriticalRegion { state -> UnsafeContinuation<Success, Failure>? in
|
||||
defer { state.continuation = nil }
|
||||
return state.continuation
|
||||
}?.resume(with: result)
|
||||
}
|
||||
state.withCriticalRegion { state in
|
||||
state.add(task)
|
||||
}?.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Determine the first result of a list of tasks.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - tasks: The running tasks to obtain a result from
|
||||
/// - Returns: The first result from the running tasks
|
||||
static func first(
|
||||
_ tasks: Task<Success, Never>...
|
||||
) async -> Success {
|
||||
await first(tasks)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Async Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2022 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
struct TaskSelectState<Success: Sendable, Failure: Error>: Sendable {
|
||||
var continuation: UnsafeContinuation<Task<Success, Failure>, Never>?
|
||||
var tasks: [Task<Success, Failure>]? = []
|
||||
|
||||
mutating func add(_ task: Task<Success, Failure>) -> Task<Success, Failure>? {
|
||||
if var tasks = tasks {
|
||||
tasks.append(task)
|
||||
self.tasks = tasks
|
||||
return nil
|
||||
} else {
|
||||
return task
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Task {
|
||||
/// Determine the first task to complete of a sequence of tasks.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - tasks: The running tasks to obtain a result from
|
||||
/// - Returns: The first task to complete from the running tasks
|
||||
public static func select<Tasks: Sequence>(
|
||||
_ tasks: Tasks
|
||||
) async -> Task<Success, Failure>
|
||||
where Tasks.Element == Task<Success, Failure> {
|
||||
let state = ManagedCriticalState(TaskSelectState<Success, Failure>())
|
||||
return await withTaskCancellationHandler {
|
||||
let tasks = state.withCriticalRegion { state -> [Task<Success, Failure>] in
|
||||
defer { state.tasks = nil }
|
||||
return state.tasks ?? []
|
||||
}
|
||||
for task in tasks {
|
||||
task.cancel()
|
||||
}
|
||||
} operation: {
|
||||
await withUnsafeContinuation { continuation in
|
||||
state.withCriticalRegion { state in
|
||||
state.continuation = continuation
|
||||
}
|
||||
for task in tasks {
|
||||
Task<Void, Never> {
|
||||
_ = await task.result
|
||||
state.withCriticalRegion { state -> UnsafeResumption<Task<Success, Failure>, Never>? in
|
||||
defer { state.continuation = nil }
|
||||
return state.continuation.map { UnsafeResumption(continuation: $0, success: task) }
|
||||
}?.resume()
|
||||
}
|
||||
state.withCriticalRegion { state in
|
||||
state.add(task)
|
||||
}?.cancel()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Determine the first task to complete of a list of tasks.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - tasks: The running tasks to obtain a result from
|
||||
/// - Returns: The first task to complete from the running tasks
|
||||
public static func select(
|
||||
_ tasks: Task<Success, Failure>...
|
||||
) async -> Task<Success, Failure> {
|
||||
await select(tasks)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
struct UnsafeResumption<Success, Failure: Error> {
|
||||
let continuation: UnsafeContinuation<Success, Failure>
|
||||
let result: Result<Success, Failure>
|
||||
|
||||
init(continuation: UnsafeContinuation<Success, Failure>, result: Result<Success, Failure>) {
|
||||
self.continuation = continuation
|
||||
self.result = result
|
||||
}
|
||||
|
||||
init(continuation: UnsafeContinuation<Success, Failure>, success: Success) {
|
||||
self.init(continuation: continuation, result: .success(success))
|
||||
}
|
||||
|
||||
init(continuation: UnsafeContinuation<Success, Failure>, failure: Failure) {
|
||||
self.init(continuation: continuation, result: .failure(failure))
|
||||
}
|
||||
|
||||
func resume() {
|
||||
continuation.resume(with: result)
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeResumption where Failure == Error {
|
||||
init(continuation: UnsafeContinuation<Success, Failure>, catching body: () throws -> Success) {
|
||||
self.init(continuation: continuation, result: Result(catching: body))
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeResumption where Success == Void {
|
||||
init(continuation: UnsafeContinuation<Success, Failure>) {
|
||||
self.init(continuation: continuation, result: .success(()))
|
||||
}
|
||||
}
|
||||
|
||||
extension UnsafeResumption: Sendable where Success: Sendable { }
|
||||
|
||||
|
||||
@@ -14,33 +14,33 @@ import XCTest
|
||||
|
||||
final class TestTaskFirst: XCTestCase {
|
||||
func test_first() async {
|
||||
let firstValue = await Task.first(Task {
|
||||
let firstValue = await Task.select(Task {
|
||||
return 1
|
||||
}, Task {
|
||||
try! await Task.sleep(nanoseconds: NSEC_PER_SEC * 2)
|
||||
return 2
|
||||
})
|
||||
}).value
|
||||
XCTAssertEqual(firstValue, 1)
|
||||
}
|
||||
|
||||
func test_second() async {
|
||||
let firstValue = await Task.first(Task {
|
||||
let firstValue = await Task.select(Task {
|
||||
try! await Task.sleep(nanoseconds: NSEC_PER_SEC * 2)
|
||||
return 1
|
||||
}, Task {
|
||||
return 2
|
||||
})
|
||||
}).value
|
||||
XCTAssertEqual(firstValue, 2)
|
||||
}
|
||||
|
||||
func test_throwing() async {
|
||||
do {
|
||||
_ = try await Task.first(Task { () async throws -> Int in
|
||||
_ = try await Task.select(Task { () async throws -> Int in
|
||||
try await Task.sleep(nanoseconds: NSEC_PER_SEC * 2)
|
||||
return 1
|
||||
}, Task { () async throws -> Int in
|
||||
throw NSError(domain: NSCocoaErrorDomain, code: -1, userInfo: nil)
|
||||
})
|
||||
}).value
|
||||
XCTFail()
|
||||
} catch {
|
||||
XCTAssertEqual((error as NSError).code, -1)
|
||||
@@ -53,7 +53,7 @@ final class TestTaskFirst: XCTestCase {
|
||||
let firstCancelled = expectation(description: "first cancelled")
|
||||
let secondCancelled = expectation(description: "second cancelled")
|
||||
let task = Task {
|
||||
_ = await Task.first(Task {
|
||||
_ = await Task.select(Task {
|
||||
await withTaskCancellationHandler {
|
||||
firstCancelled.fulfill()
|
||||
} operation: { () -> Int in
|
||||
|
||||
Reference in new issue
Block a user