From 310f801deb2e35d80e3cfb97703d9cb8674ff153 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sun, 18 Sep 2022 20:09:09 -0700 Subject: [PATCH] [Utilities] Add UInt16 rank utilities --- .../Node/_StorageHeader.swift | 4 +- .../Integer tricks.swift | 45 +++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/Sources/PersistentCollections/Node/_StorageHeader.swift b/Sources/PersistentCollections/Node/_StorageHeader.swift index 58da2e80..fd6c75c6 100644 --- a/Sources/PersistentCollections/Node/_StorageHeader.swift +++ b/Sources/PersistentCollections/Node/_StorageHeader.swift @@ -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 } } diff --git a/Sources/_CollectionsUtilities/Integer tricks.swift b/Sources/_CollectionsUtilities/Integer tricks.swift index c9041769..f081a87c 100644 --- a/Sources/_CollectionsUtilities/Integer tricks.swift +++ b/Sources/_CollectionsUtilities/Integer tricks.swift @@ -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) + } +}