|
| 1 | +//===----------------------------------------------------------------------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift Async Algorithms open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2026 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 | +#if UnstableAsyncStreaming && compiler(>=6.4) || true |
| 13 | + |
| 14 | +public import ContainersPreview |
| 15 | +import BasicContainers |
| 16 | + |
| 17 | +@available(macOS 26.2, iOS 26.2, watchOS 26.2, tvOS 26.2, visionOS 26.2, *) |
| 18 | +extension AsyncReader where Self: ~Copyable, Self: ~Escapable, ReadElement: ~Copyable { |
| 19 | + /// Collects elements from the reader up to a specified limit and processes them with a body function. |
| 20 | + /// |
| 21 | + /// This method continuously reads elements from the async reader, accumulating them in a buffer |
| 22 | + /// until either it reaches the end of the stream (indicated by an empty `Span`) or reaches |
| 23 | + /// the specified limit. Once collection completes, it passes the accumulated elements to the |
| 24 | + /// provided body function as a `Span` for processing. |
| 25 | + /// |
| 26 | + /// - Parameters: |
| 27 | + /// - limit: The maximum number of elements to collect. This prevents unbounded memory |
| 28 | + /// growth when reading from potentially infinite streams. |
| 29 | + /// - body: A closure that receives a `Span` containing all collected elements and returns |
| 30 | + /// a result of type `Result`. The method calls this closure once after collecting all |
| 31 | + /// elements successfully. |
| 32 | + /// |
| 33 | + /// - Returns: The value returned by the body closure after processing the collected elements. |
| 34 | + /// |
| 35 | + /// - Throws: An `EitherError` containing either a `ReadFailure` from the read operation |
| 36 | + /// or a `Failure` from the body closure. |
| 37 | + /// |
| 38 | + /// ## Example |
| 39 | + /// |
| 40 | + /// ```swift |
| 41 | + /// var reader: SomeAsyncReader = ... |
| 42 | + /// |
| 43 | + /// let processedData = try await reader.collect(upTo: 1000) { span in |
| 44 | + /// // Process all collected elements |
| 45 | + /// } |
| 46 | + /// ``` |
| 47 | + /// |
| 48 | + /// ## Memory Considerations |
| 49 | + /// |
| 50 | + /// Since this method buffers all elements in memory before processing, it should be used |
| 51 | + /// with caution on large datasets. The `limit` parameter serves as a safety mechanism |
| 52 | + /// to prevent excessive memory usage. |
| 53 | + public mutating func collect<Result, Failure: Error>( |
| 54 | + upTo limit: Int, |
| 55 | + body: (consuming InputSpan<ReadElement>) async throws(Failure) -> Result |
| 56 | + ) async throws(EitherError<ReadFailure, Failure>) -> Result { |
| 57 | + // TODO: In the future we might want to use a temporary allocation instead |
| 58 | + // but those don't support async closures yet. |
| 59 | + var buffer = UniqueArray<ReadElement>() |
| 60 | + var shouldContinue = true |
| 61 | + do { |
| 62 | + while shouldContinue { |
| 63 | + try await self.read( |
| 64 | + maximumCount: limit - buffer.count |
| 65 | + ) { (span: consuming InputSpan<ReadElement>) in |
| 66 | + guard span.count > 0 else { |
| 67 | + shouldContinue = false |
| 68 | + return |
| 69 | + } |
| 70 | + precondition(span.count <= limit - buffer.count) |
| 71 | + while let element = span.popFirst() { |
| 72 | + buffer.append(element) |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | + } catch { |
| 77 | + switch error { |
| 78 | + case .first(let error): |
| 79 | + throw .first(error) |
| 80 | + case .second: |
| 81 | + fatalError() |
| 82 | + } |
| 83 | + } |
| 84 | + do { |
| 85 | + var consumer = buffer.consumeAll() |
| 86 | + return try await body(consumer.drainNext()) |
| 87 | + } catch { |
| 88 | + throw .second(error) |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + /// Collects elements from the reader up to a specified limit and processes them with a body function. |
| 93 | + /// |
| 94 | + /// This method continuously reads elements from the async reader, accumulating them in a buffer |
| 95 | + /// until either it reaches the end of the stream (indicated by an empty `Span`) or reaches |
| 96 | + /// the specified limit. Once collection completes, it passes the accumulated elements to the |
| 97 | + /// provided body function as a `Span` for processing. |
| 98 | + /// |
| 99 | + /// - Parameters: |
| 100 | + /// - limit: The maximum number of elements to collect. This prevents unbounded memory |
| 101 | + /// growth when reading from potentially infinite streams. |
| 102 | + /// - body: A closure that receives a `Span` containing all collected elements and returns |
| 103 | + /// a result of type `Result`. The method calls this closure once after collecting all |
| 104 | + /// elements successfully. |
| 105 | + /// |
| 106 | + /// - Returns: The value returned by the body closure after processing the collected elements. |
| 107 | + /// |
| 108 | + /// ## Example |
| 109 | + /// |
| 110 | + /// ```swift |
| 111 | + /// var reader: SomeAsyncReader = ... |
| 112 | + /// |
| 113 | + /// let processedData = try await reader.collect(upTo: 1000) { span in |
| 114 | + /// // Process all collected elements |
| 115 | + /// } |
| 116 | + /// ``` |
| 117 | + /// |
| 118 | + /// ## Memory Considerations |
| 119 | + /// |
| 120 | + /// Since this method buffers all elements in memory before processing, it should be used |
| 121 | + /// with caution on large datasets. The `limit` parameter serves as a safety mechanism |
| 122 | + /// to prevent excessive memory usage. |
| 123 | + public mutating func collect<Result>( |
| 124 | + upTo limit: Int, |
| 125 | + body: (consuming InputSpan<ReadElement>) async -> Result |
| 126 | + ) async -> Result where ReadFailure == Never { |
| 127 | + // TODO: In the future we might want to use a temporary allocation instead |
| 128 | + // but those don't support async closures yet. |
| 129 | + var buffer = UniqueArray<ReadElement>() |
| 130 | + var shouldContinue = true |
| 131 | + while limit - buffer.count > 0 && shouldContinue { |
| 132 | + // This force-try is safe since neither read nor the closure are throwing |
| 133 | + try! await self.read( |
| 134 | + maximumCount: limit - buffer.count |
| 135 | + ) { (span: consuming InputSpan<ReadElement>) in |
| 136 | + precondition(span.count <= limit - buffer.count) |
| 137 | + guard span.count > 0 else { |
| 138 | + // This means the underlying reader is finished and we can return |
| 139 | + shouldContinue = false |
| 140 | + return |
| 141 | + } |
| 142 | + while let element = span.popFirst() { |
| 143 | + buffer.append(element) |
| 144 | + } |
| 145 | + } |
| 146 | + } |
| 147 | + var consumer = buffer.consumeAll() |
| 148 | + return await body(consumer.drainNext()) |
| 149 | + } |
| 150 | + |
| 151 | + /// Collects elements from the reader into an output span until the span is full. |
| 152 | + /// |
| 153 | + /// This method continuously reads elements from the async reader and appends them to the |
| 154 | + /// provided output span until the span reaches its capacity. This provides an efficient |
| 155 | + /// way to fill a pre-allocated buffer with elements from the reader. |
| 156 | + /// |
| 157 | + /// - Parameter outputSpan: An `OutputSpan` to append read elements into. The method continues |
| 158 | + /// reading until this span is full. |
| 159 | + /// |
| 160 | + /// - Throws: An error of type `ReadFailure` if any read operation fails. |
| 161 | + /// |
| 162 | + /// ## Example |
| 163 | + /// |
| 164 | + /// ```swift |
| 165 | + /// var reader: SomeAsyncReader = ... |
| 166 | + /// var buffer = [Int](repeating: 0, count: 100) |
| 167 | + /// |
| 168 | + /// try await buffer.withOutputSpan { outputSpan in |
| 169 | + /// try await reader.collect(into: &outputSpan) |
| 170 | + /// } |
| 171 | + /// ``` |
| 172 | + public mutating func collect( |
| 173 | + into outputSpan: inout OutputSpan<ReadElement> |
| 174 | + ) async throws(ReadFailure) { |
| 175 | + while !outputSpan.isFull { |
| 176 | + do { |
| 177 | + try await self.read(maximumCount: outputSpan.freeCapacity) { (span: consuming InputSpan<ReadElement>) in |
| 178 | + while let element = span.popFirst() { |
| 179 | + outputSpan.append(element) |
| 180 | + } |
| 181 | + } |
| 182 | + } catch { |
| 183 | + switch error { |
| 184 | + case .first(let error): |
| 185 | + throw error |
| 186 | + case .second: |
| 187 | + fatalError() |
| 188 | + } |
| 189 | + } |
| 190 | + } |
| 191 | + } |
| 192 | +} |
| 193 | + |
| 194 | +#endif |
0 commit comments