22 lines
772 B
Swift
22 lines
772 B
Swift
import Dispatch
|
|
|
|
extension Array {
|
|
@inlinable
|
|
func parallelCompactMap<T>(transform: (Element) -> T?) -> [T] {
|
|
return parallelMap(transform: transform).compactMap { $0 }
|
|
}
|
|
|
|
@inlinable
|
|
func parallelMap<T>(transform: (Element) -> T) -> [T] {
|
|
return [T](unsafeUninitializedCapacity: count) { buffer, initializedCount in
|
|
let baseAddress = buffer.baseAddress!
|
|
DispatchQueue.concurrentPerform(iterations: count) { index in
|
|
// Using buffer[index] does assignWithTake which tries
|
|
// to read the uninitialized value (to release it) and crashes
|
|
(baseAddress + index).initialize(to: transform(self[index]))
|
|
}
|
|
initializedCount = count
|
|
}
|
|
}
|
|
}
|