Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
main ▾

xtool.git / Sources / XUtils / Stdlib+Utils.swift

Stdlib+Utils.swift66 lines · 2.7 KiBRaw
1extension Sequence where Element: Sendable {
2 /// Like `map`, but runs transformations concurrently.
3 ///
4 /// - Parameter maxConcurrency: The maximum number of transforms to run concurrently.
5 /// If `nil`, we choose a reasonable default value. Use `.max` to run all at once.
6 ///
7 /// - Parameter transform: The transformation to apply to each element.
8 ///
9 /// - Returns: Transformed elements in the same order as the original sequence.
10 public nonisolated(nonsending) func concurrentMap<T: Sendable, E: Error>(
11 maxConcurrency: Int? = nil,
12 _ transform: @escaping @Sendable @isolated(any) (Element) async throws(E) -> T,
13 ) async throws(E) -> [T] {
14 try await _concurrentMap(
15 maxConcurrency: maxConcurrency ?? 10,
16 transform,
17 willWaitForNext: nil,
18 )
19 }
20
21 nonisolated(nonsending) func _concurrentMap<T: Sendable, E: Error>(
22 maxConcurrency: Int,
23 _ transform: @escaping @Sendable @isolated(any) (Element) async throws(E) -> T,
24 willWaitForNext: (() -> Void)?, // hook for testing
25 ) async throws(E) -> [T] {
26 precondition(maxConcurrency > 0, "maxConcurrency must be > 0")
27
28 return try await withTaskGroup(of: (Int, Result<T, E>).self) { group -> Result<[T], E> in
29 var results: [T?] = []
30 results.reserveCapacity(self.underestimatedCount)
31 var iterator = makeIterator()
32 var exhausted = false
33 var inFlight = 0
34 while true {
35 while !exhausted && inFlight < maxConcurrency {
36 guard let element = iterator.next() else {
37 exhausted = true
38 break
39 }
40 let index = results.count
41 results.append(nil)
42 group.addTask {
43 let result = await Result { () async throws(E) in
44 try await transform(element)
45 }
46 return (index, result)
47 }
48 inFlight += 1
49 }
50 willWaitForNext?()
51 guard let (index, result) = await group.next() else { break }
52 inFlight -= 1
53 switch result {
54 case .success(let value):
55 results[index] = value
56 case .failure(let error):
57 group.cancelAll()
58 return .failure(error)
59 }
60 }
61 // we can't use `as! [T]` because it breaks nested optionals (Foo??)
62 return .success(results.map { $0! })
63 }
64 .get()
65 }
66}