|
| 1 | +import Foundation |
| 2 | + |
| 3 | +// MARK: - Concurrent Collection Processing |
| 4 | + |
| 5 | +extension Sequence where Element: Sendable { |
| 6 | + |
| 7 | + /// Concurrently maps elements with controlled parallelism using a sliding window pattern. |
| 8 | + /// |
| 9 | + /// This method processes elements concurrently while limiting the number of simultaneous |
| 10 | + /// operations to prevent resource exhaustion (file handles, memory, etc.). |
| 11 | + /// |
| 12 | + /// - Parameters: |
| 13 | + /// - maxConcurrency: Maximum number of concurrent operations (default: 50) |
| 14 | + /// - transform: Async throwing closure that transforms each element. Return `nil` to skip. |
| 15 | + /// - Returns: Array of non-nil transformed results |
| 16 | + /// - Throws: Rethrows any error from the transform closure |
| 17 | + /// |
| 18 | + /// ## Example |
| 19 | + /// |
| 20 | + /// ```swift |
| 21 | + /// let urls: [URL] = getFileURLs() |
| 22 | + /// let documents = try await urls.concurrentMap(maxConcurrency: 50) { url in |
| 23 | + /// try? JSONDecoder().decode(Document.self, from: Data(contentsOf: url)) |
| 24 | + /// } |
| 25 | + /// ``` |
| 26 | + /// |
| 27 | + /// ## Performance Characteristics |
| 28 | + /// |
| 29 | + /// - Maintains exactly `maxConcurrency` tasks running at any time |
| 30 | + /// - Uses structured concurrency with no semaphores or locks |
| 31 | + /// - Memory efficient: processes results as they complete |
| 32 | + @inlinable |
| 33 | + public func concurrentMap<T: Sendable>( |
| 34 | + maxConcurrency: Int = 50, |
| 35 | + _ transform: @Sendable @escaping (Element) async throws -> T? |
| 36 | + ) async rethrows -> [T] { |
| 37 | + try await withThrowingTaskGroup(of: T?.self) { group in |
| 38 | + var results: [T] = [] |
| 39 | + var iterator = makeIterator() |
| 40 | + |
| 41 | + // Seed initial batch of tasks up to maxConcurrency |
| 42 | + var activeCount = 0 |
| 43 | + while activeCount < maxConcurrency, let element = iterator.next() { |
| 44 | + group.addTask { try await transform(element) } |
| 45 | + activeCount += 1 |
| 46 | + } |
| 47 | + |
| 48 | + // As each task completes, add the next one (sliding window) |
| 49 | + while let result = try await group.next() { |
| 50 | + if let value = result { |
| 51 | + results.append(value) |
| 52 | + } |
| 53 | + |
| 54 | + // Add next task if elements remain |
| 55 | + if let element = iterator.next() { |
| 56 | + group.addTask { try await transform(element) } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return results |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + /// Concurrently maps elements with controlled parallelism (non-throwing version). |
| 65 | + /// |
| 66 | + /// - Parameters: |
| 67 | + /// - maxConcurrency: Maximum number of concurrent operations (default: 50) |
| 68 | + /// - transform: Async closure that transforms each element. Return `nil` to skip. |
| 69 | + /// - Returns: Array of non-nil transformed results |
| 70 | + @inlinable |
| 71 | + public func concurrentMap<T: Sendable>( |
| 72 | + maxConcurrency: Int = 50, |
| 73 | + _ transform: @Sendable @escaping (Element) async -> T? |
| 74 | + ) async -> [T] { |
| 75 | + await withTaskGroup(of: T?.self) { group in |
| 76 | + var results: [T] = [] |
| 77 | + var iterator = makeIterator() |
| 78 | + |
| 79 | + // Seed initial batch |
| 80 | + var activeCount = 0 |
| 81 | + while activeCount < maxConcurrency, let element = iterator.next() { |
| 82 | + group.addTask { await transform(element) } |
| 83 | + activeCount += 1 |
| 84 | + } |
| 85 | + |
| 86 | + // Sliding window: add new task as each completes |
| 87 | + for await result in group { |
| 88 | + if let value = result { |
| 89 | + results.append(value) |
| 90 | + } |
| 91 | + |
| 92 | + if let element = iterator.next() { |
| 93 | + group.addTask { await transform(element) } |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + return results |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + /// Concurrently executes a side-effect closure on each element with controlled parallelism. |
| 102 | + /// |
| 103 | + /// Use this when you need to perform async operations for their side effects |
| 104 | + /// (e.g., saving files, network requests) without collecting results. |
| 105 | + /// |
| 106 | + /// - Parameters: |
| 107 | + /// - maxConcurrency: Maximum number of concurrent operations (default: 50) |
| 108 | + /// - body: Async throwing closure to execute for each element |
| 109 | + /// - Throws: Rethrows the first error encountered |
| 110 | + /// |
| 111 | + /// ## Example |
| 112 | + /// |
| 113 | + /// ```swift |
| 114 | + /// try await documents.concurrentForEach(maxConcurrency: 20) { doc in |
| 115 | + /// try await storage.saveDocument(doc) |
| 116 | + /// } |
| 117 | + /// ``` |
| 118 | + @inlinable |
| 119 | + public func concurrentForEach( |
| 120 | + maxConcurrency: Int = 50, |
| 121 | + _ body: @Sendable @escaping (Element) async throws -> Void |
| 122 | + ) async throws { |
| 123 | + try await withThrowingTaskGroup(of: Void.self) { group in |
| 124 | + var iterator = makeIterator() |
| 125 | + |
| 126 | + // Seed initial batch |
| 127 | + var activeCount = 0 |
| 128 | + while activeCount < maxConcurrency, let element = iterator.next() { |
| 129 | + group.addTask { try await body(element) } |
| 130 | + activeCount += 1 |
| 131 | + } |
| 132 | + |
| 133 | + // Sliding window |
| 134 | + while try await group.next() != nil { |
| 135 | + if let element = iterator.next() { |
| 136 | + group.addTask { try await body(element) } |
| 137 | + } |
| 138 | + } |
| 139 | + } |
| 140 | + } |
| 141 | + |
| 142 | + /// Concurrently maps elements while preserving the original order. |
| 143 | + /// |
| 144 | + /// Unlike `concurrentMap`, this method guarantees that output order matches input order. |
| 145 | + /// Slightly higher memory overhead due to tracking indices. |
| 146 | + /// |
| 147 | + /// - Parameters: |
| 148 | + /// - maxConcurrency: Maximum number of concurrent operations (default: 50) |
| 149 | + /// - transform: Async throwing closure that transforms each element |
| 150 | + /// - Returns: Array of transformed results in the same order as input |
| 151 | + /// - Throws: Rethrows any error from the transform closure |
| 152 | + /// |
| 153 | + /// ## Example |
| 154 | + /// |
| 155 | + /// ```swift |
| 156 | + /// let urls = [url1, url2, url3] |
| 157 | + /// let data = try await urls.orderedConcurrentMap(maxConcurrency: 10) { url in |
| 158 | + /// try await fetchData(from: url) |
| 159 | + /// } |
| 160 | + /// // data[0] corresponds to url1, data[1] to url2, etc. |
| 161 | + /// ``` |
| 162 | + @inlinable |
| 163 | + public func orderedConcurrentMap<T: Sendable>( |
| 164 | + maxConcurrency: Int = 50, |
| 165 | + _ transform: @Sendable @escaping (Element) async throws -> T |
| 166 | + ) async rethrows -> [T] { |
| 167 | + let indexed = Array(self.enumerated()) |
| 168 | + |
| 169 | + let results = try await indexed.concurrentMap(maxConcurrency: maxConcurrency) { item -> (Int, T)? in |
| 170 | + let result = try await transform(item.element) |
| 171 | + return (item.offset, result) |
| 172 | + } |
| 173 | + |
| 174 | + // Sort by original index and extract values |
| 175 | + return results |
| 176 | + .sorted { $0.0 < $1.0 } |
| 177 | + .map(\.1) |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +// MARK: - Collection Chunking |
| 182 | + |
| 183 | +extension Collection { |
| 184 | + |
| 185 | + /// Splits the collection into chunks of the specified size. |
| 186 | + /// |
| 187 | + /// - Parameter size: Maximum size of each chunk |
| 188 | + /// - Returns: Array of array slices, each containing up to `size` elements |
| 189 | + /// |
| 190 | + /// ## Example |
| 191 | + /// |
| 192 | + /// ```swift |
| 193 | + /// let items = [1, 2, 3, 4, 5, 6, 7] |
| 194 | + /// let chunks = items.chunked(into: 3) |
| 195 | + /// // [[1, 2, 3], [4, 5, 6], [7]] |
| 196 | + /// ``` |
| 197 | + @inlinable |
| 198 | + public func chunked(into size: Int) -> [[Element]] { |
| 199 | + guard size > 0 else { return [] } |
| 200 | + |
| 201 | + return stride(from: 0, to: count, by: size).map { startOffset in |
| 202 | + let start = index(startIndex, offsetBy: startOffset) |
| 203 | + let end = index(start, offsetBy: size, limitedBy: endIndex) ?? endIndex |
| 204 | + return Array(self[start..<end]) |
| 205 | + } |
| 206 | + } |
| 207 | +} |
0 commit comments