[Utilities] Add UInt16 rank utilities

This commit is contained in:
Karoy Lorentey committed 2022-09-19 21:25:07 -07:00
1 parent a2491aac45
commit 310f801deb
2 files changed
+47 -2

No files matched your search

@@ -105,8 +105,8 @@ extension _StorageHeader {
}
set {
assert(isCollisionNode || childMap.isEmpty)
assert(newValue > 0 && newValue < UInt32.max)
itemMap._value = UInt32(truncatingIfNeeded: newValue)
assert(newValue > 0 && newValue < _Bitmap.Value.max)
itemMap._value = _Bitmap.Value(truncatingIfNeeded: newValue)
childMap = itemMap
}
}
@@ -69,3 +69,48 @@ extension UInt32 {
return UInt(truncatingIfNeeded: shift)
}
}
extension UInt16 {
@inlinable @inline(__always)
internal var _nonzeroBitCount: Self {
Self(truncatingIfNeeded: nonzeroBitCount)
}
@inlinable @inline(__always)
public func _rank(ofBit bit: UInt) -> Int {
assert(bit < Self.bitWidth)
let mask: Self = (1 &<< bit) &- 1
return (self & mask).nonzeroBitCount
}
// Returns the position of the `n`th set bit in `self`, i.e., the bit with
// rank `n`.
@_effects(releasenone)
public func _bit(ranked n: Int) -> UInt? {
assert(n >= 0 && n < Self.bitWidth)
var shift: Self = 0
var n: Self = UInt16(truncatingIfNeeded: n)
let c8 = ((self &>> shift) & 0xFF)._nonzeroBitCount
if n >= c8 {
shift &+= 8
n -= c8
}
let c4 = ((self &>> shift) & 0xF)._nonzeroBitCount
if n >= c4 {
shift &+= 4
n -= c4
}
let c2 = ((self &>> shift) & 0x3)._nonzeroBitCount
if n >= c2 {
shift &+= 2
n -= c2
}
let c1 = (self &>> shift) & 0x1
if n >= c1 {
shift &+= 1
n -= c1
}
guard n == 0, (self &>> shift) & 0x1 == 1 else { return nil }
return UInt(truncatingIfNeeded: shift)
}
}