-
Notifications
You must be signed in to change notification settings - Fork 26
/
AsyncPrependSequence.swift
81 lines (70 loc) · 2.05 KB
/
AsyncPrependSequence.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// AsyncPrependSequence.swift
//
//
// Created by Thibault Wittemberg on 31/12/2021.
//
public extension AsyncSequence {
/// Prepends an element to the upstream async sequence.
///
/// ```
/// let sourceSequence = AsyncLazySequence([1, 2, 3])
/// let prependSequence = sourceSequence.prepend(0)
///
/// for try await element in prependSequence {
/// print(element)
/// }
///
/// // will print:
/// // Element is 0
/// // Element is 1
/// // Element is 2
/// // Element is 3
/// ```
///
/// - Parameter element: The element to prepend.
/// - Returns: The async sequence prepended with the element.
func prepend(_ element: @Sendable @autoclosure @escaping () -> Element) -> AsyncPrependSequence<Self> {
AsyncPrependSequence(self, prependElement: element())
}
}
public struct AsyncPrependSequence<Base: AsyncSequence>: AsyncSequence {
public typealias Element = Base.Element
public typealias AsyncIterator = Iterator
private var base: Base
private var prependElement: @Sendable () -> Element
public init(
_ base: Base,
prependElement: @Sendable @autoclosure @escaping () -> Element
) {
self.base = base
self.prependElement = prependElement
}
public func makeAsyncIterator() -> AsyncIterator {
Iterator(
base: self.base.makeAsyncIterator(),
prependElement: self.prependElement
)
}
public struct Iterator: AsyncIteratorProtocol {
var base: Base.AsyncIterator
var prependElement: () async throws -> Element
var hasBeenDelivered = false
public init(
base: Base.AsyncIterator,
prependElement: @escaping () async throws -> Element
) {
self.base = base
self.prependElement = prependElement
}
public mutating func next() async throws -> Element? {
guard !Task.isCancelled else { return nil }
if !self.hasBeenDelivered {
self.hasBeenDelivered = true
return try await prependElement()
}
return try await self.base.next()
}
}
}
extension AsyncPrependSequence: Sendable where Base: Sendable {}