Skip to content

Commit d7ec177

Browse files
Added AnyReadableSequence
1 parent 5a882f1 commit d7ec177

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
//
2+
// AnyReadableSequence.swift
3+
// AsyncSequenceReader
4+
//
5+
// Created by Dimitri Bouniol on 2023-06-26.
6+
// Copyright © 2021-23 Mochi Development, Inc. All rights reserved.
7+
//
8+
9+
/// A type-erased convenience type to normalize synchronous and asynchronous sequences into a common async type.
10+
public struct AnyReadableSequence<Element>: AsyncSequence {
11+
@usableFromInline
12+
let makeUnderlyingIterator: () -> () async throws -> Element?
13+
14+
public struct AsyncIterator: AsyncIteratorProtocol {
15+
@usableFromInline
16+
let makeUnderlyingNext: () async throws -> Element?
17+
18+
@inlinable
19+
init(_ makeUnderlyingNext: @escaping () async throws -> Element?) {
20+
self.makeUnderlyingNext = makeUnderlyingNext
21+
}
22+
23+
@inlinable
24+
public mutating func next() async throws -> Element? {
25+
try await makeUnderlyingNext()
26+
}
27+
}
28+
29+
@inlinable
30+
public func makeAsyncIterator() -> AsyncIterator {
31+
AsyncIterator(makeUnderlyingIterator())
32+
}
33+
34+
@inlinable
35+
init(_ makeUnderlyingIterator: @escaping () -> () async throws -> Element?) {
36+
self.makeUnderlyingIterator = makeUnderlyingIterator
37+
}
38+
39+
/// Initialize ``AnyReadableSequence`` with a sequence.
40+
@inlinable
41+
public init<S: Sequence>(_ sequence: S) where S.Element == Element {
42+
self.init {
43+
var iterator = sequence.makeIterator()
44+
45+
return { iterator.next() }
46+
}
47+
}
48+
49+
/// Initialize ``AnyReadableSequence`` with an async sequence.
50+
@inlinable
51+
public init<S: AsyncSequence>(_ sequence: S) where S.Element == Element {
52+
self.init {
53+
var iterator = sequence.makeAsyncIterator()
54+
55+
return { try await iterator.next() }
56+
}
57+
}
58+
}
59+

0 commit comments

Comments
 (0)