Add a 2 and 3 arity version of chain (#9)

* Add a 2 and 3 arity version of chain

* Tests for cancellation of chain sequences

* Correct typo of missing [] in chain 3 test for cancellation

* Make chain 2/3 inlinable and frozen
This commit is contained in:
Philippe Hausler authored and GitHub committed 2022-01-18 11:50:25 -08:00
1 parent b2aad0be7d
commit 8a1078810c
4 files changed
+366

No files matched your search

@@ -0,0 +1,80 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Returns a new asynchronous sequence that iterates over the two given asynchronous sequences, one
/// followed by the other.
///
/// - Parameters:
/// - s1: The first asynchronous sequence.
/// - s2: The second asynchronous sequence.
/// - Returns: An asynchonous sequence that iterates first over the elements of `s1`, and
/// then over the elements of `s2`.
@inlinable
public func chain<Base1: AsyncSequence, Base2: AsyncSequence>(_ s1: Base1, _ s2: Base2) -> AsyncChain2Sequence<Base1, Base2> where Base1.Element == Base2.Element {
AsyncChain2Sequence(s1, s2)
}
/// A concatenation of two asynchronous sequences with the same element type.
@frozen
public struct AsyncChain2Sequence<Base1: AsyncSequence, Base2: AsyncSequence> where Base1.Element == Base2.Element {
@usableFromInline
let base1: Base1
@usableFromInline
let base2: Base2
@usableFromInline
init(_ base1: Base1, _ base2: Base2) {
self.base1 = base1
self.base2 = base2
}
}
extension AsyncChain2Sequence: AsyncSequence {
public typealias Element = Base1.Element
/// The iterator for a `AsyncChain2Sequence` instance.
@frozen
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var base1: Base1.AsyncIterator?
@usableFromInline
var base2: Base2.AsyncIterator?
@usableFromInline
init(_ base1: Base1.AsyncIterator, _ base2: Base2.AsyncIterator) {
self.base1 = base1
self.base2 = base2
}
@inlinable
public mutating func next() async rethrows -> Element? {
do {
if let value = try await base1?.next() {
return value
} else {
base1 = nil
}
return try await base2?.next()
} catch {
base1 = nil
base2 = nil
throw error
}
}
}
@inlinable
public func makeAsyncIterator() -> Iterator {
Iterator(base1.makeAsyncIterator(), base2.makeAsyncIterator())
}
}
@@ -0,0 +1,95 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Returns a new asynchronous sequence that iterates over the three given asynchronous sequences, one
/// followed by the other.
///
/// - Parameters:
/// - s1: The first asynchronous sequence.
/// - s2: The second asynchronous sequence.
/// - s3: The third asynchronous sequence.
/// - Returns: An asynchonous sequence that iterates first over the elements of `s1`, and
/// then over the elements of `s2`, and then over the elements of `s3`
@inlinable
public func chain<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence>(_ s1: Base1, _ s2: Base2, _ s3: Base3) -> AsyncChain3Sequence<Base1, Base2, Base3> {
AsyncChain3Sequence(s1, s2, s3)
}
/// A concatenation of three asynchronous sequences with the same element type.
@frozen
public struct AsyncChain3Sequence<Base1: AsyncSequence, Base2: AsyncSequence, Base3: AsyncSequence> where Base1.Element == Base2.Element, Base1.Element == Base3.Element {
@usableFromInline
let base1: Base1
@usableFromInline
let base2: Base2
@usableFromInline
let base3: Base3
@usableFromInline
init(_ base1: Base1, _ base2: Base2, _ base3: Base3) {
self.base1 = base1
self.base2 = base2
self.base3 = base3
}
}
extension AsyncChain3Sequence: AsyncSequence {
public typealias Element = Base1.Element
/// The iterator for a `AsyncChain3Sequence` instance.
@frozen
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var base1: Base1.AsyncIterator?
@usableFromInline
var base2: Base2.AsyncIterator?
@usableFromInline
var base3: Base3.AsyncIterator?
@usableFromInline
init(_ base1: Base1.AsyncIterator, _ base2: Base2.AsyncIterator, _ base3: Base3.AsyncIterator) {
self.base1 = base1
self.base2 = base2
self.base3 = base3
}
@inlinable
public mutating func next() async rethrows -> Element? {
do {
if let value = try await base1?.next() {
return value
} else {
base1 = nil
}
if let value = try await base2?.next() {
return value
} else {
base2 = nil
}
return try await base3?.next()
} catch {
base1 = nil
base2 = nil
base3 = nil
throw error
}
}
}
@inlinable
public func makeAsyncIterator() -> Iterator {
Iterator(base1.makeAsyncIterator(), base2.makeAsyncIterator(), base3.makeAsyncIterator())
}
}
+19
View File
@@ -0,0 +1,19 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2021 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 Failure: Error, Equatable { }
func throwOn<T: Equatable>(_ toThrowOn: T, _ value: T) throws -> T {
if value == toThrowOn {
throw Failure()
}
return value
}
+172
View File
@@ -0,0 +1,172 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2021 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 XCTest
import AsyncAlgorithms
final class TestChain2: XCTestCase {
func test_chain() async {
let chained = chain([1, 2, 3].async, [4, 5, 6].async)
var iterator = chained.makeAsyncIterator()
var actual = [Int]()
while let item = await iterator.next() {
actual.append(item)
}
XCTAssertEqual([1, 2, 3, 4, 5, 6], actual)
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throwing_first() async throws {
let chained = chain([1, 2, 3].async.map { try throwOn(3, $0) }, [4, 5, 6].async)
var iterator = chained.makeAsyncIterator()
var actual = [Int]()
do {
while let item = try await iterator.next() {
actual.append(item)
}
XCTFail()
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
XCTAssertEqual([1, 2], actual)
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throwing_second() async throws {
let chained = chain([1, 2, 3].async, [4, 5, 6].async.map { try throwOn(5, $0) })
var iterator = chained.makeAsyncIterator()
var actual = [Int]()
do {
while let item = try await iterator.next() {
actual.append(item)
}
XCTFail()
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
XCTAssertEqual([1, 2, 3, 4], actual)
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_cancellation() async {
let source = Indefinite(value: "test")
let sequence = chain(source.async, ["past indefinite"].async)
let finished = expectation(description: "finished")
let iterated = expectation(description: "iterated")
let task = Task {
var firstIteration = false
for await _ in sequence {
if !firstIteration {
firstIteration = true
iterated.fulfill()
}
}
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
}
}
final class TestChain3: XCTestCase {
func test_chain() async {
let chained = chain([1, 2, 3].async, [4, 5, 6].async, [7, 8, 9].async)
var iterator = chained.makeAsyncIterator()
var actual = [Int]()
while let item = await iterator.next() {
actual.append(item)
}
XCTAssertEqual([1, 2, 3, 4, 5, 6, 7, 8, 9], actual)
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throwing_first() async throws {
let chained = chain([1, 2, 3].async.map { try throwOn(3, $0) }, [4, 5, 6].async, [7, 8, 9].async)
var iterator = chained.makeAsyncIterator()
var actual = [Int]()
do {
while let item = try await iterator.next() {
actual.append(item)
}
XCTFail()
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
XCTAssertEqual([1, 2], actual)
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throwing_second() async throws {
let chained = chain([1, 2, 3].async, [4, 5, 6].async.map { try throwOn(5, $0) }, [7, 8, 9].async)
var iterator = chained.makeAsyncIterator()
var actual = [Int]()
do {
while let item = try await iterator.next() {
actual.append(item)
}
XCTFail()
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
XCTAssertEqual([1, 2, 3, 4], actual)
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throwing_third() async throws {
let chained = chain([1, 2, 3].async, [4, 5, 6].async, [7, 8, 9].async.map { try throwOn(8, $0) })
var iterator = chained.makeAsyncIterator()
var actual = [Int]()
do {
while let item = try await iterator.next() {
actual.append(item)
}
XCTFail()
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
XCTAssertEqual([1, 2, 3, 4, 5, 6, 7], actual)
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_cancellation() async {
let source = Indefinite(value: "test")
let sequence = chain(source.async, ["past indefinite"].async, ["and even further"].async)
let finished = expectation(description: "finished")
let iterated = expectation(description: "iterated")
let task = Task {
var firstIteration = false
for await _ in sequence {
if !firstIteration {
firstIteration = true
iterated.fulfill()
}
}
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
}
}