File tree Expand file tree Collapse file tree 1 file changed +78
-0
lines changed Expand file tree Collapse file tree 1 file changed +78
-0
lines changed Original file line number Diff line number Diff line change 1+ //
2+ // File.swift
3+ //
4+ //
5+ // Created by Matthew Judy on 12/21/23.
6+ //
7+ // TODO: Use the implementation found in swift-async-algorithms when this PR is merged:
8+ // https://github.com/apple/swift-async-algorithms/pull/261
9+ //
10+
11+
12+
13+ /// An enumeration of the elements of an AsyncSequence.
14+ ///
15+ /// `AsyncEnumeratedSequence` generates a sequence of pairs (*n*, *x*), where *n*s are
16+ /// consecutive `Int` values starting at zero, and *x*s are the elements from an
17+ /// base AsyncSequence.
18+ ///
19+ /// To create an instance of `EnumeratedSequence`, call `enumerated()` on an
20+ /// AsyncSequence.
21+ public struct AsyncEnumeratedSequence < Base: AsyncSequence >
22+ {
23+ @usableFromInline
24+ let base : Base
25+
26+ @usableFromInline
27+ init ( _ base: Base )
28+ {
29+ self . base = base
30+ }
31+ }
32+
33+
34+ extension AsyncEnumeratedSequence : AsyncSequence
35+ {
36+ public typealias Element = ( Int , Base . Element )
37+
38+ public struct AsyncIterator : AsyncIteratorProtocol
39+ {
40+ @usableFromInline
41+ var baseIterator : Base . AsyncIterator
42+ @usableFromInline
43+ var index : Int
44+
45+ @usableFromInline
46+ init ( baseIterator: Base . AsyncIterator )
47+ {
48+ self . baseIterator = baseIterator
49+ self . index = 0
50+ }
51+
52+ @inlinable
53+ public mutating func next( ) async rethrows -> AsyncEnumeratedSequence . Element ?
54+ {
55+ let value = try await self . baseIterator. next ( ) . map { ( self . index, $0) }
56+ self . index += 1
57+ return value
58+ }
59+ }
60+
61+ @inlinable
62+ public __consuming func makeAsyncIterator( ) -> AsyncIterator
63+ {
64+ return . init( baseIterator: self . base. makeAsyncIterator ( ) )
65+ }
66+ }
67+
68+
69+ extension AsyncEnumeratedSequence : Sendable where Base: Sendable { }
70+
71+
72+ extension AsyncSequence
73+ {
74+ /// Return an enumaterated AsyncSequence
75+ public func enumerated( ) -> AsyncEnumeratedSequence < Self > { return AsyncEnumeratedSequence ( self ) }
76+ }
77+
78+
You can’t perform that action at this time.
0 commit comments