mirror of
https://github.com/apple/swift-collections
synced 2026-11-26 04:47:48 +00:00
[Capsule] Add bitmap to sequence converters
This commit is contained in:
1 parent
c7905a5153
commit
0c192fd2e6
2 files changed
+53
No files matched your search
@@ -15,6 +15,37 @@ func computeHash<T: Hashable>(_ value: T) -> Int {
|
||||
|
||||
typealias Bitmap = UInt32
|
||||
|
||||
extension Bitmap {
|
||||
public func nonzeroBits() -> NonzeroBits<Self> {
|
||||
return NonzeroBits(from: self)
|
||||
}
|
||||
|
||||
public func zeroBits() -> NonzeroBits<Self> {
|
||||
return NonzeroBits(from: ~self)
|
||||
}
|
||||
}
|
||||
|
||||
public struct NonzeroBits<Bitmap>: Sequence, IteratorProtocol, CustomStringConvertible where Bitmap: BinaryInteger {
|
||||
var bitmap: Bitmap
|
||||
|
||||
init(from bitmap: Bitmap) {
|
||||
self.bitmap = bitmap
|
||||
}
|
||||
|
||||
public mutating func next() -> Int? {
|
||||
guard bitmap != 0 else { return nil }
|
||||
|
||||
let index = bitmap.trailingZeroBitCount
|
||||
bitmap ^= 1 << index
|
||||
|
||||
return index
|
||||
}
|
||||
|
||||
public var description: String {
|
||||
"[\(self.map { $0.description }.joined(separator: ", "))]"
|
||||
}
|
||||
}
|
||||
|
||||
let bitPartitionSize: Int = 5
|
||||
|
||||
let bitPartitionMask: Int = (1 << bitPartitionSize) - 1
|
||||
|
||||
@@ -441,4 +441,26 @@ final class BitmapSmokeTests: CollectionTestCase {
|
||||
func test_Capacity_isValid() {
|
||||
expectTrue(Int(2 << bitPartitionSize) <= Int(Capacity.max))
|
||||
}
|
||||
|
||||
func test_Bitmap_nonzeroBits() {
|
||||
let bitmap: Bitmap = 0b0100_0000_0000_1011
|
||||
|
||||
expectEqual(Array(bitmap.nonzeroBits()), [0, 1, 3, 14])
|
||||
expectEqual(Array(bitmap.zeroBits()), (0 ..< Bitmap.bitWidth).filter { ![0, 1, 3, 14].contains($0) })
|
||||
}
|
||||
|
||||
func test_Bitmap_nonzeroBitsToArray() {
|
||||
let bitmap: Bitmap = 0b0100_0000_0000_1011
|
||||
|
||||
let counts = bitmap.nonzeroBits().reduce(
|
||||
into: Array(repeating: 0, count: Bitmap.bitWidth), { counts, index in counts[index] = 1 })
|
||||
|
||||
expectEqual(counts.count, Bitmap.bitWidth)
|
||||
expectEqual(counts.reduce(0, +), bitmap.nonzeroBitCount)
|
||||
expectEqual(counts.reduce(0, +), 4)
|
||||
expectEqual(counts[0], 1)
|
||||
expectEqual(counts[1], 1)
|
||||
expectEqual(counts[3], 1)
|
||||
expectEqual(counts[14], 1)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user