diff --git a/Sources/AsyncAlgorithms/AsyncChain2Sequence.swift b/Sources/AsyncAlgorithms/AsyncChain2Sequence.swift new file mode 100644 index 0000000..a0db085 --- /dev/null +++ b/Sources/AsyncAlgorithms/AsyncChain2Sequence.swift @@ -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(_ s1: Base1, _ s2: Base2) -> AsyncChain2Sequence where Base1.Element == Base2.Element { + AsyncChain2Sequence(s1, s2) +} + +/// A concatenation of two asynchronous sequences with the same element type. +@frozen +public struct AsyncChain2Sequence 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()) + } +} diff --git a/Sources/AsyncAlgorithms/AsyncChain3Sequence.swift b/Sources/AsyncAlgorithms/AsyncChain3Sequence.swift new file mode 100644 index 0000000..ad361c3 --- /dev/null +++ b/Sources/AsyncAlgorithms/AsyncChain3Sequence.swift @@ -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(_ s1: Base1, _ s2: Base2, _ s3: Base3) -> AsyncChain3Sequence { + AsyncChain3Sequence(s1, s2, s3) +} + +/// A concatenation of three asynchronous sequences with the same element type. +@frozen +public struct AsyncChain3Sequence 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()) + } +} diff --git a/Tests/AsyncAlgorithmsTests/Failure.swift b/Tests/AsyncAlgorithmsTests/Failure.swift new file mode 100644 index 0000000..1333164 --- /dev/null +++ b/Tests/AsyncAlgorithmsTests/Failure.swift @@ -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(_ toThrowOn: T, _ value: T) throws -> T { + if value == toThrowOn { + throw Failure() + } + return value +} diff --git a/Tests/AsyncAlgorithmsTests/TestChain.swift b/Tests/AsyncAlgorithmsTests/TestChain.swift new file mode 100644 index 0000000..dbdc089 --- /dev/null +++ b/Tests/AsyncAlgorithmsTests/TestChain.swift @@ -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) + } +}