Skip to content

Commit d62421a

Browse files
author
Dave Abrahams
committed
[stdlib] _NSFastEnumeration generic traversal; NFC
1 parent 9eaa6f4 commit d62421a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

stdlib/public/core/ShadowProtocols.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,39 @@ public protocol _NSFastEnumeration : _ShadowProtocol {
3636
) -> Int
3737
}
3838

39+
extension _NSFastEnumeration {
40+
/// Divides the elements into contiguous batches and calls `processBatch` on
41+
/// each batch, in order.
42+
///
43+
/// To stop processing early, throw an error.
44+
func _forEachBatch(
45+
_ processBatch: (UnsafeBufferPointer<AnyObject>) throws -> Void
46+
) rethrows {
47+
typealias X = UnsafeRawPointer?
48+
typealias Storage = (X, X, X, X, X, X, X, X)
49+
50+
var bufferStorage: Storage
51+
let bufferCapacity = MemoryLayout<Storage>.size
52+
/ MemoryLayout<X>.stride
53+
54+
try withUnsafePointer(to: &bufferStorage) { p in
55+
try p.withMemoryRebound(
56+
to: AnyObject.self, capacity: bufferCapacity
57+
) { buffer in
58+
var s = _makeSwiftNSFastEnumerationState()
59+
var bufferCount = 0
60+
repeat {
61+
bufferCount = self.countByEnumerating(
62+
with: &s, objects: buffer, count: bufferCapacity)
63+
try processBatch(
64+
UnsafeBufferPointer(start: buffer, count: bufferCount))
65+
}
66+
while bufferCount != 0
67+
}
68+
}
69+
}
70+
}
71+
3972
/// A shadow for the `NSEnumerator` class.
4073
@objc
4174
public protocol _NSEnumerator : _ShadowProtocol {

0 commit comments

Comments
 (0)