mirror of
https://github.com/apple/swift-async-algorithms
synced 2026-11-22 04:10:40 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2971dd5d9f | ||
|
|
103f5e5bea | ||
|
|
b8006a9de0 | ||
|
|
2de50036f6 | ||
|
|
ba540240d3 | ||
|
|
65ed06871b | ||
|
|
d98a48b8c2 |
No files matched your search
@@ -15,7 +15,6 @@ jobs:
|
||||
linux_exclude_swift_versions: "[{\"swift_version\": \"5.9\"}, {\"swift_version\": \"5.10\"}]]"
|
||||
windows_exclude_swift_versions: "[{\"swift_version\": \"5.9\"}]"
|
||||
enable_wasm_sdk_build: true
|
||||
wasm_sdk_build_command: swift build -Xcc -D_WASI_EMULATED_PTHREAD
|
||||
|
||||
soundness:
|
||||
name: Soundness
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
# Map Error
|
||||
|
||||
* Proposal: [SAA-NNNN](NNNN-map-error.md)
|
||||
* Authors: [Clive Liu](https://github.com/clive819) [Philippe Hausler](https://github.com/phausler)
|
||||
* Review Manager: TBD
|
||||
* Status: **Awaiting review**
|
||||
|
||||
## Introduction
|
||||
|
||||
Asynchronous sequences often particpate in carefully crafted systems of algorithms spliced together. Some of those algorithms require that both the element type and the failure type are the same as each-other. In order to line those types up for the element we have the map algorithm today, however there are other times at which when using more specific APIs that transforming the Failure type is needed.
|
||||
|
||||
## Motivation
|
||||
|
||||
The `mapError` function empowers developers to elegantly transform errors within asynchronous sequences, enhancing code readability and maintainability.
|
||||
|
||||
Building failure-type-safe versions of zip or other algorithms will need to require that the associated Failure types are the same. Having an effecient and easy to use transformation routine to adjust the failure-types is then key to delivering or interfacing with those failure-type-safe algorithms.
|
||||
|
||||
## Proposed solution
|
||||
|
||||
A new extension and type will be added to transform the failure-types of AsyncSequences.
|
||||
|
||||
## Detailed design
|
||||
|
||||
The method will be applied to all AsyncSequences via an extension with the function name of `mapError`. This is spiritually related to the `mapError` method on `Result` and similar in functionality to other frameworks' methods of the similar naming. This will not return an opaque result since the type needs to be refined for `Sendable`; in that the `AsyncMapERrorSequence` is only `Sendable` when the base `AsyncSequence` is `Sendable`.
|
||||
|
||||
```swift
|
||||
extension AsyncSequence {
|
||||
public func mapError<MappedFailure: Error>(_ transform: @Sendable @escaping (Failure) async -> MappedFailure) -> AsyncMapErrorSequence<Element, MappedFailure>
|
||||
}
|
||||
|
||||
public struct AsyncMapErrorSequence<Base: AsyncSequence, TransformedFailure: Error>: AsyncSequence { }
|
||||
|
||||
extension AsyncMapErrorSequence: Sendable where Base: Sendable { }
|
||||
|
||||
@available(*, unavailable)
|
||||
extension AsyncMapErrorSequence.Iterator: Sendable {}
|
||||
```
|
||||
|
||||
## Effect on API resilience
|
||||
|
||||
This cannot be back-deployed to 1.0 since it has a base requirement for the associated `Failure` and requires typed throws.
|
||||
|
||||
## Naming
|
||||
|
||||
The naming follows to current method naming of the Combine [mapError](https://developer.apple.com/documentation/combine/publisher/maperror(_:)) method and similarly the name of the method on `Result`
|
||||
|
||||
## Alternatives considered
|
||||
|
||||
It was initially considered that the return type would be opaque, however the only way to refine that as Sendable would be to have a disfavored overload; this ended up creating more ambiguity than it seemed worth.
|
||||
@@ -7,8 +7,11 @@ let AsyncAlgorithms_v1_0 = "AvailabilityMacro=AsyncAlgorithms 1.0:macOS 10.15, i
|
||||
#if compiler(>=6.0) && swift(>=6.0) // 5.10 doesnt support visionOS availability
|
||||
let AsyncAlgorithms_v1_1 =
|
||||
"AvailabilityMacro=AsyncAlgorithms 1.1:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0"
|
||||
let AsyncAlgorithms_v1_2 =
|
||||
"AvailabilityMacro=AsyncAlgorithms 1.2:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0"
|
||||
#else
|
||||
let AsyncAlgorithms_v1_1 = "AvailabilityMacro=AsyncAlgorithms 1.1:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0"
|
||||
let AsyncAlgorithms_v1_2 = "AvailabilityMacro=AsyncAlgorithms 1.2:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0"
|
||||
#endif
|
||||
|
||||
let availabilityMacros: [SwiftSetting] = [
|
||||
@@ -18,6 +21,9 @@ let availabilityMacros: [SwiftSetting] = [
|
||||
.enableExperimentalFeature(
|
||||
AsyncAlgorithms_v1_1
|
||||
),
|
||||
.enableExperimentalFeature(
|
||||
AsyncAlgorithms_v1_2
|
||||
),
|
||||
]
|
||||
|
||||
let package = Package(
|
||||
@@ -66,6 +72,7 @@ let package = Package(
|
||||
.macCatalyst,
|
||||
.android,
|
||||
.linux,
|
||||
.custom("freebsd"),
|
||||
.openbsd,
|
||||
.wasi,
|
||||
])
|
||||
@@ -81,6 +88,7 @@ let package = Package(
|
||||
.macCatalyst,
|
||||
.android,
|
||||
.linux,
|
||||
.custom("freebsd"),
|
||||
.openbsd,
|
||||
.wasi,
|
||||
])
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// swift-tools-version: 5.6
|
||||
// swift-tools-version: 5.7
|
||||
|
||||
import PackageDescription
|
||||
|
||||
|
||||
@@ -12,6 +12,9 @@ let availabilityMacros: [SwiftSetting] = [
|
||||
.enableExperimentalFeature(
|
||||
"AvailabilityMacro=AsyncAlgorithms 1.1:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0"
|
||||
),
|
||||
.enableExperimentalFeature(
|
||||
"AvailabilityMacro=AsyncAlgorithms 1.2:macOS 15.0, iOS 18.0, tvOS 18.0, watchOS 11.0, visionOS 2.0"
|
||||
),
|
||||
]
|
||||
|
||||
let package = Package(
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if compiler(>=6.0)
|
||||
@available(AsyncAlgorithms 1.2, *)
|
||||
extension AsyncSequence {
|
||||
|
||||
/// Converts any failure into a new error.
|
||||
///
|
||||
/// - Parameter transform: A closure that takes the failure as a parameter and returns a new error.
|
||||
/// - Returns: An asynchronous sequence that maps the error thrown into the one produced by the transform closure.
|
||||
///
|
||||
/// Use the ``mapError(_:)`` operator when you need to replace one error type with another.
|
||||
@available(AsyncAlgorithms 1.2, *)
|
||||
public func mapError<MappedError: Error>(
|
||||
_ transform: @Sendable @escaping (Self.Failure) -> MappedError
|
||||
) -> some AsyncSequence<Self.Element, MappedError> {
|
||||
AsyncMapErrorSequence(base: self, transform: transform)
|
||||
}
|
||||
|
||||
/// Converts any failure into a new error.
|
||||
///
|
||||
/// - Parameter transform: A closure that takes the failure as a parameter and returns a new error.
|
||||
/// - Returns: An asynchronous sequence that maps the error thrown into the one produced by the transform closure.
|
||||
///
|
||||
/// Use the ``mapError(_:)`` operator when you need to replace one error type with another.
|
||||
@available(AsyncAlgorithms 1.2, *)
|
||||
public func mapError<MappedError: Error>(
|
||||
_ transform: @Sendable @escaping (Self.Failure) -> MappedError
|
||||
) -> (some AsyncSequence<Self.Element, MappedError> & Sendable) where Self: Sendable, Self.Element: Sendable {
|
||||
AsyncMapErrorSequence(base: self, transform: transform)
|
||||
}
|
||||
}
|
||||
|
||||
/// An asynchronous sequence that converts any failure into a new error.
|
||||
@available(AsyncAlgorithms 1.2, *)
|
||||
struct AsyncMapErrorSequence<Base: AsyncSequence, MappedError: Error> {
|
||||
typealias Element = Base.Element
|
||||
typealias Failure = MappedError
|
||||
|
||||
private let base: Base
|
||||
private let transform: @Sendable (Base.Failure) async -> MappedError
|
||||
|
||||
init(
|
||||
base: Base,
|
||||
transform: @Sendable @escaping (Base.Failure) async -> MappedError
|
||||
) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
}
|
||||
}
|
||||
|
||||
@available(AsyncAlgorithms 1.2, *)
|
||||
extension AsyncMapErrorSequence: AsyncSequence {
|
||||
|
||||
/// The iterator that produces elements of the map sequence.
|
||||
struct Iterator: AsyncIteratorProtocol {
|
||||
typealias Element = Base.Element
|
||||
|
||||
private var base: Base.AsyncIterator
|
||||
|
||||
private let transform: @Sendable (Base.Failure) async -> MappedError
|
||||
|
||||
init(
|
||||
base: Base.AsyncIterator,
|
||||
transform: @Sendable @escaping (Base.Failure) async -> MappedError
|
||||
) {
|
||||
self.base = base
|
||||
self.transform = transform
|
||||
}
|
||||
|
||||
mutating func next() async throws(MappedError) -> Element? {
|
||||
try await self.next(isolation: nil)
|
||||
}
|
||||
|
||||
mutating func next(isolation actor: isolated (any Actor)?) async throws(MappedError) -> Element? {
|
||||
do {
|
||||
return try await base.next(isolation: actor)
|
||||
} catch {
|
||||
throw await transform(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func makeAsyncIterator() -> Iterator {
|
||||
Iterator(
|
||||
base: base.makeAsyncIterator(),
|
||||
transform: transform
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@available(AsyncAlgorithms 1.2, *)
|
||||
extension AsyncMapErrorSequence: Sendable where Base: Sendable, Base.Element: Sendable {}
|
||||
|
||||
@available(*, unavailable)
|
||||
extension AsyncMapErrorSequence.Iterator: Sendable {}
|
||||
#endif
|
||||
@@ -423,7 +423,7 @@ where Base.Element: Sendable, Base: SendableMetatype, Base.AsyncIterator: Sendab
|
||||
}
|
||||
|
||||
func iterate() async -> Bool {
|
||||
if let limit {
|
||||
if let limit, limit > 0 {
|
||||
let cancelled = await withUnsafeContinuation { (continuation: UnsafeContinuation<Bool, Never>) in
|
||||
let (resume, cancelled) = state.withLock { state -> (UnsafeContinuation<Bool, Never>?, Bool) in
|
||||
guard state.buffer.count >= limit else {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Async Algorithms open source project
|
||||
//
|
||||
// Copyright (c) 2026 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
#if compiler(>=6.1)
|
||||
// This is a helper type to move a non-Sendable value across isolation regions.
|
||||
@usableFromInline
|
||||
struct Disconnected<Value: ~Copyable>: ~Copyable, Sendable {
|
||||
// This is safe since we take the value as sending and take consumes it
|
||||
// and returns it as sending.
|
||||
private nonisolated(unsafe) var value: Value?
|
||||
|
||||
@usableFromInline
|
||||
init(value: consuming sending Value) {
|
||||
self.value = .some(value)
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
consuming func take() -> sending Value {
|
||||
nonisolated(unsafe) let value = self.value.take()!
|
||||
return value
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
mutating func swap(newValue: consuming sending Value) -> sending Value {
|
||||
nonisolated(unsafe) let value = self.value.take()!
|
||||
self.value = consume newValue
|
||||
return value
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -21,6 +21,11 @@ import WinSDK
|
||||
import Bionic
|
||||
#elseif canImport(wasi_pthread)
|
||||
import wasi_pthread
|
||||
#elseif canImport(WASILibc)
|
||||
// Here, we can not import wasi_pthread, but we can import WASILibc. So
|
||||
// this is a variation of WASILibc without pthread support. As such, the
|
||||
// platform does not have locks or mechanisms to become multi-threaded,
|
||||
// so no locks are needed.
|
||||
#else
|
||||
#error("Unsupported platform")
|
||||
#endif
|
||||
@@ -29,7 +34,13 @@ internal struct Lock {
|
||||
#if canImport(Darwin)
|
||||
typealias Primitive = os_unfair_lock
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic) || canImport(wasi_pthread)
|
||||
#if os(FreeBSD) || os(OpenBSD)
|
||||
typealias Primitive = pthread_mutex_t?
|
||||
#else
|
||||
typealias Primitive = pthread_mutex_t
|
||||
#endif
|
||||
#elseif canImport(WASILibc)
|
||||
// This WASILibc variation is single threaded, provides no locks
|
||||
#elseif canImport(WinSDK)
|
||||
typealias Primitive = SRWLOCK
|
||||
#else
|
||||
@@ -49,6 +60,11 @@ internal struct Lock {
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic) || canImport(wasi_pthread)
|
||||
let result = pthread_mutex_init(platformLock, nil)
|
||||
precondition(result == 0, "pthread_mutex_init failed")
|
||||
#elseif canImport(WASILibc)
|
||||
// Here, we can not import wasi_pthread, but we can import WASILibc. So
|
||||
// this is a variation of WASILibc without pthread support. As such, the
|
||||
// platform does not have locks or mechanisms to become multi-threaded,
|
||||
// so no locks are needed.
|
||||
#elseif canImport(WinSDK)
|
||||
InitializeSRWLock(platformLock)
|
||||
#else
|
||||
@@ -69,6 +85,12 @@ internal struct Lock {
|
||||
os_unfair_lock_lock(platformLock)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic) || canImport(wasi_pthread)
|
||||
pthread_mutex_lock(platformLock)
|
||||
#elseif canImport(WASILibc)
|
||||
// Here, we can not import wasi_pthread, but we can import WASILibc. So
|
||||
// this is a variation of WASILibc without pthread support. As such, the
|
||||
// platform does not have locks or mechanisms to become multi-threaded,
|
||||
// so no locks are needed.
|
||||
return
|
||||
#elseif canImport(WinSDK)
|
||||
AcquireSRWLockExclusive(platformLock)
|
||||
#else
|
||||
@@ -82,6 +104,12 @@ internal struct Lock {
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic) || canImport(wasi_pthread)
|
||||
let result = pthread_mutex_unlock(platformLock)
|
||||
precondition(result == 0, "pthread_mutex_unlock failed")
|
||||
#elseif canImport(WASILibc)
|
||||
// Here, we can not import wasi_pthread, but we can import WASILibc. So
|
||||
// this is a variation of WASILibc without pthread support. As such, the
|
||||
// platform does not have locks or mechanisms to become multi-threaded,
|
||||
// so no locks are needed.
|
||||
return
|
||||
#elseif canImport(WinSDK)
|
||||
ReleaseSRWLockExclusive(platformLock)
|
||||
#else
|
||||
|
||||
+7
-15
@@ -261,9 +261,9 @@ extension MultiProducerSingleConsumerAsyncChannel {
|
||||
) throws -> MultiProducerSingleConsumerAsyncChannel<Element, Failure>.Source.SendResult {
|
||||
// We need to move the value into an optional since we don't have call-once
|
||||
// closures in the Swift yet.
|
||||
var optionalSequence = Optional(sequence)
|
||||
var optionalSequence = Disconnected(value: Optional(sequence))
|
||||
let action = self._stateMachine.withLock {
|
||||
let sequence = optionalSequence.takeSending()!
|
||||
let sequence = optionalSequence.swap(newValue: nil)!
|
||||
return $0.send(sequence)
|
||||
}
|
||||
|
||||
@@ -313,11 +313,11 @@ extension MultiProducerSingleConsumerAsyncChannel {
|
||||
callbackToken: UInt64,
|
||||
onProduceMore: sending @escaping (Result<Void, Error>) -> Void
|
||||
) {
|
||||
// We need to move the value into an optional since we don't have call-once
|
||||
// We need to move the value into a disconnected since we don't have call-once
|
||||
// closures in the Swift yet.
|
||||
var optionalOnProduceMore = Optional(onProduceMore)
|
||||
var optionalOnProduceMore = Disconnected(value: Optional(onProduceMore))
|
||||
let action = self._stateMachine.withLock {
|
||||
let onProduceMore = optionalOnProduceMore.takeSending()!
|
||||
let onProduceMore = optionalOnProduceMore.swap(newValue: nil)!
|
||||
return $0.enqueueProducer(callbackToken: callbackToken, onProduceMore: onProduceMore)
|
||||
}
|
||||
|
||||
@@ -1720,15 +1720,6 @@ enum _MultiProducerSingleConsumerSuspendedProducer {
|
||||
case continuation(UnsafeContinuation<Void, Error>)
|
||||
}
|
||||
|
||||
extension Optional where Wrapped: ~Copyable {
|
||||
@usableFromInline
|
||||
mutating func takeSending() -> sending Self {
|
||||
let result = consume self
|
||||
self = nil
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
struct SendableConsumeOnceBox<Wrapped> {
|
||||
@usableFromInline
|
||||
@@ -1741,7 +1732,8 @@ struct SendableConsumeOnceBox<Wrapped> {
|
||||
|
||||
@inlinable
|
||||
consuming func take() -> sending Wrapped {
|
||||
return self.wrapped.takeSending()!
|
||||
nonisolated(unsafe) let value = self.wrapped.take()!
|
||||
return value
|
||||
}
|
||||
}
|
||||
#endif
|
||||
+5
-4
@@ -138,23 +138,24 @@ public struct MultiProducerSingleConsumerAsyncChannel<Element, Failure: Error>:
|
||||
public struct ChannelAndStream: ~Copyable {
|
||||
/// The channel.
|
||||
@usableFromInline
|
||||
var channel: MultiProducerSingleConsumerAsyncChannel?
|
||||
var channel: Disconnected<MultiProducerSingleConsumerAsyncChannel?>
|
||||
|
||||
/// Takes and returns the channel.
|
||||
///
|
||||
/// - Important: If this is called more than once it will result in a runtime crash.
|
||||
@inlinable
|
||||
public mutating func takeChannel() -> sending MultiProducerSingleConsumerAsyncChannel {
|
||||
return self.channel.takeSending()!
|
||||
var channel = self.channel.swap(newValue: nil)
|
||||
return channel.take()!
|
||||
}
|
||||
/// The source.
|
||||
public var source: Source
|
||||
|
||||
init(
|
||||
channel: consuming MultiProducerSingleConsumerAsyncChannel,
|
||||
channel: consuming sending MultiProducerSingleConsumerAsyncChannel,
|
||||
source: consuming Source
|
||||
) {
|
||||
self.channel = .some(channel)
|
||||
self.channel = Disconnected(value: channel)
|
||||
self.source = source
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,8 @@ final class TaskDriver: Sendable {
|
||||
let queue: WorkQueue
|
||||
#if canImport(Darwin) || canImport(wasi_pthread)
|
||||
nonisolated(unsafe) var thread: pthread_t?
|
||||
#elseif os(FreeBSD)
|
||||
nonisolated(unsafe) var thread = pthread_t(bitPattern: 0)
|
||||
#elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic)
|
||||
nonisolated(unsafe) var thread = pthread_t()
|
||||
#elseif canImport(WinSDK)
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import AsyncAlgorithms
|
||||
import XCTest
|
||||
|
||||
#if compiler(>=6.0)
|
||||
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
|
||||
final class TestMapError: XCTestCase {
|
||||
|
||||
func test_mapError() async throws {
|
||||
let array: [Any] = [1, 2, 3, MyAwesomeError.originalError, 4, 5, 6]
|
||||
let sequence = array.async
|
||||
.map {
|
||||
if let error = $0 as? Error {
|
||||
throw error
|
||||
} else {
|
||||
$0 as! Int
|
||||
}
|
||||
}
|
||||
.mapError { _ in
|
||||
MyAwesomeError.mappedError
|
||||
}
|
||||
|
||||
var results: [Int] = []
|
||||
|
||||
do {
|
||||
for try await number in sequence {
|
||||
results.append(number)
|
||||
}
|
||||
XCTFail("sequence should throw")
|
||||
} catch {
|
||||
XCTAssertEqual(error, .mappedError)
|
||||
}
|
||||
|
||||
XCTAssertEqual(results, [1, 2, 3])
|
||||
}
|
||||
|
||||
func test_mapError_cancellation() async throws {
|
||||
let value = "test"
|
||||
let source = Indefinite(value: value).async
|
||||
let sequence =
|
||||
source
|
||||
.map {
|
||||
if $0 == "just to trick compiler that this may throw" {
|
||||
throw MyAwesomeError.originalError
|
||||
} else {
|
||||
$0
|
||||
}
|
||||
}
|
||||
.mapError { _ in
|
||||
MyAwesomeError.mappedError
|
||||
}
|
||||
|
||||
let finished = expectation(description: "finished")
|
||||
let iterated = expectation(description: "iterated")
|
||||
|
||||
let task = Task {
|
||||
var firstIteration = false
|
||||
for try await el in sequence {
|
||||
XCTAssertEqual(el, value)
|
||||
|
||||
if !firstIteration {
|
||||
firstIteration = true
|
||||
iterated.fulfill()
|
||||
}
|
||||
}
|
||||
finished.fulfill()
|
||||
}
|
||||
|
||||
// ensure the other task actually starts
|
||||
await fulfillment(of: [iterated], timeout: 1.0)
|
||||
// cancellation should ensure the loop finishes
|
||||
// without regards to the remaining underlying sequence
|
||||
task.cancel()
|
||||
await fulfillment(of: [finished], timeout: 1.0)
|
||||
}
|
||||
|
||||
func test_mapError_empty() async throws {
|
||||
let array: [String] = []
|
||||
let sequence = array.async
|
||||
.map {
|
||||
if $0 == "just to trick compiler that this may throw" {
|
||||
throw MyAwesomeError.originalError
|
||||
} else {
|
||||
$0
|
||||
}
|
||||
}
|
||||
.mapError { _ in
|
||||
MyAwesomeError.mappedError
|
||||
}
|
||||
|
||||
var results: [String] = []
|
||||
for try await value in sequence {
|
||||
results.append(value)
|
||||
}
|
||||
XCTAssert(results.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
|
||||
extension TestMapError {
|
||||
|
||||
fileprivate enum MyAwesomeError: Error {
|
||||
case originalError
|
||||
case mappedError
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -130,6 +130,55 @@ final class TestShare: XCTestCase {
|
||||
XCTAssertEqual(results2.withLock { $0 }.sorted(), [1, 2, 3, 4, 5])
|
||||
}
|
||||
|
||||
func test_share_with_no_buffering() async {
|
||||
let shared = [1, 2, 3, 4, 5].async.share(bufferingPolicy: .bounded(0))
|
||||
|
||||
let expectation1 = XCTestExpectation(description: "Consumer 1 finished looping")
|
||||
let expectation2 = XCTestExpectation(description: "Consumer 2 finished looping")
|
||||
|
||||
let results1 = Mutex([Int]())
|
||||
let results2 = Mutex([Int]())
|
||||
let gate1 = Gate()
|
||||
let gate2 = Gate()
|
||||
|
||||
let consumer1 = Task {
|
||||
var iterator = shared.makeAsyncIterator()
|
||||
gate2.open()
|
||||
await gate1.enter()
|
||||
while let value = await iterator.next(isolation: nil) {
|
||||
results1.withLock { $0.append(value) }
|
||||
// Add some delay to consumer 1
|
||||
try? await Task.sleep(for: .milliseconds(1))
|
||||
}
|
||||
expectation1.fulfill()
|
||||
}
|
||||
|
||||
let consumer2 = Task {
|
||||
var iterator = shared.makeAsyncIterator()
|
||||
gate1.open()
|
||||
await gate2.enter()
|
||||
while let value = await iterator.next(isolation: nil) {
|
||||
results2.withLock { $0.append(value) }
|
||||
}
|
||||
expectation2.fulfill()
|
||||
}
|
||||
|
||||
await fulfillment(of: [expectation1, expectation2], timeout: 5)
|
||||
|
||||
await consumer1.value
|
||||
await consumer2.value
|
||||
|
||||
// Both consumers should receive all elements
|
||||
XCTAssertEqual(results1.withLock { $0 }.sorted(), [1, 2, 3, 4, 5])
|
||||
XCTAssertEqual(results2.withLock { $0 }.sorted(), [1, 2, 3, 4, 5])
|
||||
}
|
||||
|
||||
func test_share_with_no_buffering_multiple() async {
|
||||
for _ in 0..<10 {
|
||||
await test_share_with_no_buffering()
|
||||
}
|
||||
}
|
||||
|
||||
func test_share_with_unbounded_buffering() async {
|
||||
let source = [1, 2, 3, 4, 5]
|
||||
let shared = source.async.share(bufferingPolicy: .unbounded)
|
||||
|
||||
Reference in new issue
Block a user