diff --git a/Sources/AsyncAlgorithms/AsyncMerge2Sequence.swift b/Sources/AsyncAlgorithms/AsyncMerge2Sequence.swift index 4f93251..5685e7e 100644 --- a/Sources/AsyncAlgorithms/AsyncMerge2Sequence.swift +++ b/Sources/AsyncAlgorithms/AsyncMerge2Sequence.swift @@ -45,7 +45,7 @@ where } mutating func apply(_ task1: Task?, _ task2: Task?) 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 { diff --git a/Sources/AsyncAlgorithms/AsyncMerge3Sequence.swift b/Sources/AsyncAlgorithms/AsyncMerge3Sequence.swift index 71a3c82..2b67558 100644 --- a/Sources/AsyncAlgorithms/AsyncMerge3Sequence.swift +++ b/Sources/AsyncAlgorithms/AsyncMerge3Sequence.swift @@ -48,7 +48,7 @@ where } mutating func apply(_ task1: Task?, _ task2: Task?, _ task3: Task?) 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 { diff --git a/Sources/AsyncAlgorithms/TaskFirst.swift b/Sources/AsyncAlgorithms/TaskFirst.swift deleted file mode 100644 index b1abf34..0000000 --- a/Sources/AsyncAlgorithms/TaskFirst.swift +++ /dev/null @@ -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: Sendable { - var continuation: UnsafeContinuation? - var tasks: [Task]? = [] - - mutating func add(_ task: Task) -> Task? { - 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: Tasks - ) async throws -> Success - where Tasks.Element == Task, Failure == Error { - let state = ManagedCriticalState(TaskFirstState()) - return try await withTaskCancellationHandler { - let tasks = state.withCriticalRegion { state -> [Task] 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 { - let result = await task.result - state.withCriticalRegion { state -> UnsafeContinuation? 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... - ) 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: Tasks - ) async -> Success - where Tasks.Element == Task { - let state = ManagedCriticalState(TaskFirstState()) - return await withTaskCancellationHandler { - let tasks = state.withCriticalRegion { state -> [Task] 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 { - let result = await task.result - state.withCriticalRegion { state -> UnsafeContinuation? 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... - ) async -> Success { - await first(tasks) - } -} diff --git a/Sources/AsyncAlgorithms/TaskSelect.swift b/Sources/AsyncAlgorithms/TaskSelect.swift new file mode 100644 index 0000000..922d27a --- /dev/null +++ b/Sources/AsyncAlgorithms/TaskSelect.swift @@ -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: Sendable { + var continuation: UnsafeContinuation, Never>? + var tasks: [Task]? = [] + + mutating func add(_ task: Task) -> Task? { + 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: Tasks + ) async -> Task + where Tasks.Element == Task { + let state = ManagedCriticalState(TaskSelectState()) + return await withTaskCancellationHandler { + let tasks = state.withCriticalRegion { state -> [Task] 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 { + _ = await task.result + state.withCriticalRegion { state -> UnsafeResumption, 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... + ) async -> Task { + await select(tasks) + } +} + diff --git a/Sources/AsyncAlgorithms/UnsafeResumption.swift b/Sources/AsyncAlgorithms/UnsafeResumption.swift new file mode 100644 index 0000000..9eb28c5 --- /dev/null +++ b/Sources/AsyncAlgorithms/UnsafeResumption.swift @@ -0,0 +1,37 @@ +struct UnsafeResumption { + let continuation: UnsafeContinuation + let result: Result + + init(continuation: UnsafeContinuation, result: Result) { + self.continuation = continuation + self.result = result + } + + init(continuation: UnsafeContinuation, success: Success) { + self.init(continuation: continuation, result: .success(success)) + } + + init(continuation: UnsafeContinuation, failure: Failure) { + self.init(continuation: continuation, result: .failure(failure)) + } + + func resume() { + continuation.resume(with: result) + } +} + +extension UnsafeResumption where Failure == Error { + init(continuation: UnsafeContinuation, catching body: () throws -> Success) { + self.init(continuation: continuation, result: Result(catching: body)) + } +} + +extension UnsafeResumption where Success == Void { + init(continuation: UnsafeContinuation) { + self.init(continuation: continuation, result: .success(())) + } +} + +extension UnsafeResumption: Sendable where Success: Sendable { } + + diff --git a/Tests/AsyncAlgorithmsTests/TestTaskFirst.swift b/Tests/AsyncAlgorithmsTests/TestTaskFirst.swift index da3dc3e..921b636 100644 --- a/Tests/AsyncAlgorithmsTests/TestTaskFirst.swift +++ b/Tests/AsyncAlgorithmsTests/TestTaskFirst.swift @@ -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