|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift Async Algorithms open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2022 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// |
| 10 | +//===----------------------------------------------------------------------===// |
| 11 | + |
| 12 | +/// Creates an asynchronous sequence that concurrently awaits values from two `AsyncSequence` types |
| 13 | +/// and emits a tuple of the values. |
| 14 | +public func zip<Base1: AsyncSequence, Base2: AsyncSequence>( |
| 15 | + _ base1: Base1, |
| 16 | + _ base2: Base2 |
| 17 | +) -> AsyncZip2Sequence<Base1, Base2> { |
| 18 | + AsyncZip2Sequence(base1, base2) |
| 19 | +} |
| 20 | + |
| 21 | +/// An asynchronous sequence that concurrently awaits values from two `AsyncSequence` types |
| 22 | +/// and emits a tuple of the values. |
| 23 | +public struct AsyncZip2Sequence<Base1: AsyncSequence, Base2: AsyncSequence>: AsyncSequence |
| 24 | +where Base1: Sendable, Base1.Element: Sendable, Base2: Sendable, Base2.Element: Sendable { |
| 25 | + public typealias Element = (Base1.Element, Base2.Element) |
| 26 | + public typealias AsyncIterator = Iterator |
| 27 | + |
| 28 | + let base1: Base1 |
| 29 | + let base2: Base2 |
| 30 | + |
| 31 | + init(_ base1: Base1, _ base2: Base2) { |
| 32 | + self.base1 = base1 |
| 33 | + self.base2 = base2 |
| 34 | + } |
| 35 | + |
| 36 | + public func makeAsyncIterator() -> AsyncIterator { |
| 37 | + Iterator( |
| 38 | + base1, |
| 39 | + base2 |
| 40 | + ) |
| 41 | + } |
| 42 | + |
| 43 | + public struct Iterator: AsyncIteratorProtocol { |
| 44 | + let runtime: Zip2Runtime<Base1, Base2> |
| 45 | + |
| 46 | + init(_ base1: Base1, _ base2: Base2) { |
| 47 | + self.runtime = Zip2Runtime(base1, base2) |
| 48 | + } |
| 49 | + |
| 50 | + public mutating func next() async rethrows -> Element? { |
| 51 | + try await self.runtime.next() |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments