diff --git a/Sources/BasicContainers/HashTable/_HTable+Find.swift b/Sources/BasicContainers/HashTable/_HTable+Find.swift index a8662343..89448a43 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Find.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Find.swift @@ -35,6 +35,7 @@ extension _HTable { tester: (Bucket) -> Bool, ) -> Bucket? { assert(!isSmall) +#if COLLECTIONS_NO_ROBIN_HOOD_HASHING // Naive find let start = idealBucket(forHashValue: hashValue) var it = makeBucketIterator(from: start) @@ -45,6 +46,19 @@ extension _HTable { it.wrapToNextBit() } return nil +#else + let start = idealBucket(forHashValue: hashValue) + var it = makeBucketIterator(from: start) + var i = 0 + while it.isOccupied, i <= _maxProbeLength { + if tester(it.currentBucket) { + return it.currentBucket + } + it.wrapToNextBit() + i &+= 1 + } + return nil +#endif } } #endif diff --git a/Sources/BasicContainers/HashTable/_HTable+Insert.swift b/Sources/BasicContainers/HashTable/_HTable+Insert.swift index d89d4f70..ee44ea75 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Insert.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Insert.swift @@ -19,6 +19,8 @@ extension _HTable { // FIXME: Scramble order by swapping things in some way let r = Bucket(offset: _count) _count &+= 1 + _totalProbeLength += _count + _maxProbeLength = _count return r } @@ -34,9 +36,13 @@ extension _HTable { #if COLLECTIONS_NO_ROBIN_HOOD_HASHING let ideal = idealBucket(forHashValue: hashValue) - let actual = _bitmap.firstUnoccupiedBucket(from: b) - _totalProbeLength += probeLength(from: ideal, to: actual) - _bitmap.setOccupied(actual) + let bitmap = self.bitmap + let actual = bitmap.firstUnoccupiedBucket(from: ideal) + bitmap.setOccupied(actual) + let probeLength = self.probeLength(from: ideal, to: actual) + _totalProbeLength += probeLength + _maxProbeLength = Swift.max(_maxProbeLength, probeLength) + _count &+= 1 return actual #else var b = idealBucket(forHashValue: hashValue) @@ -50,13 +56,19 @@ extension _HTable { in: b) if probeLength > oldProbeLength { swapper(b) + if probeLength > _maxProbeLength { + _maxProbeLength = probeLength + } probeLength = oldProbeLength } self.wrapBucket(after: &b) } - _totalProbeLength &+= 1 bitmap.setOccupied(b) _count &+= 1 + if probeLength > _maxProbeLength { + _maxProbeLength = probeLength + } + _totalProbeLength &+= 1 return b #endif } diff --git a/Sources/BasicContainers/HashTable/_HTable+Sizing.swift b/Sources/BasicContainers/HashTable/_HTable+Sizing.swift index a43d2649..72c71427 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Sizing.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Sizing.swift @@ -17,7 +17,7 @@ import InternalCollectionsUtilities extension _HTable { /// The minimum hash table scale. @_alwaysEmitIntoClient - internal static var minimumScale: UInt8 { + package static var minimumScale: UInt8 { @_effects(readnone) @_transparent get { @@ -27,7 +27,7 @@ extension _HTable { /// The maximum hash table scale. @_alwaysEmitIntoClient - internal static var maximumScale: UInt8 { + package static var maximumScale: UInt8 { @_effects(readnone) @_transparent get { @@ -37,7 +37,7 @@ extension _HTable { /// The maximum number of items for which we do not create a hash table. @usableFromInline - internal static var maximumUnhashedCount: Int { + package static var maximumUnhashedCount: Int { @_effects(readnone) get { maximumCapacity(forScale: 0) @@ -53,17 +53,26 @@ extension _HTable { } /// The numerator of the maximum hash table load factor. - @_alwaysEmitIntoClient @_transparent - internal static var _maxLFNum: UInt { 7 } + internal static var _maxLFNum: UInt { +#if COLLECTIONS_NO_ROBIN_HOOD_HASHING + 3 +#else + 7 +#endif + } /// The denominator of the maximum hash table load factor. - @_alwaysEmitIntoClient @_transparent - internal static var _maxLFDenom: UInt { 8 } + internal static var _maxLFDenom: UInt { +#if COLLECTIONS_NO_ROBIN_HOOD_HASHING + 4 +#else + 8 +#endif + } /// The numerator of the minimum hash table load factor. - @_alwaysEmitIntoClient @_transparent internal static var _minLFNum: UInt { 1 } @@ -75,7 +84,7 @@ extension _HTable { /// The minimum number of items that can be held in a hash table of the given scale. @usableFromInline @_effects(readnone) - internal static func minimumCapacity(forScale scale: UInt8) -> Int { + package static func minimumCapacity(forScale scale: UInt8) -> Int { guard scale >= minimumScale else { return 0 } precondition(scale <= maximumScale) let bucketCount: UInt = 1 &<< scale @@ -85,7 +94,7 @@ extension _HTable { /// The maximum number of items that can be held in a hash table of the given scale. @usableFromInline @_effects(readnone) - internal static func maximumCapacity(forScale scale: UInt8) -> Int { + package static func maximumCapacity(forScale scale: UInt8) -> Int { let scale = Swift.max(scale, minimumScale &- 1) let bucketCount: UInt = 1 &<< scale return Int(bucketCount * _maxLFNum / _maxLFDenom) @@ -95,7 +104,7 @@ extension _HTable { /// The minimum hash table scale that can hold the specified number of elements. @usableFromInline @_effects(readnone) - internal static func minimumScale(forCapacity capacity: Int) -> UInt8 { + package static func minimumScale(forCapacity capacity: Int) -> UInt8 { guard capacity > maximumUnhashedCount else { return 0 } let capacity = UInt(truncatingIfNeeded: Swift.max(capacity, 1)) // Calculate the minimum number of entries we need to allocate to satisfy @@ -115,7 +124,7 @@ extension _HTable { @usableFromInline @_effects(readnone) - internal static func dynamicStorageParameters( + package static func dynamicStorageParameters( minimumCapacity: Int ) -> (scale: UInt8, capacity: Int) { let maximumUnhashedCount = self.maximumUnhashedCount diff --git a/Sources/BasicContainers/HashTable/_HTable.swift b/Sources/BasicContainers/HashTable/_HTable.swift index 51ebcc63..e1cb63d4 100644 --- a/Sources/BasicContainers/HashTable/_HTable.swift +++ b/Sources/BasicContainers/HashTable/_HTable.swift @@ -32,6 +32,9 @@ package struct _HTable: ~Copyable { @_alwaysEmitIntoClient package var _totalProbeLength: Int + @_alwaysEmitIntoClient + package var _maxProbeLength: Int + @_alwaysEmitIntoClient package let scale: UInt8 @@ -46,6 +49,7 @@ package struct _HTable: ~Copyable { self._count = 0 self._capacity = _capacity self._totalProbeLength = 0 + self._maxProbeLength = 0 self.scale = scale if scale == 0 { self._bitmap = nil diff --git a/Sources/BasicContainers/HashTable/_Htable+Debugging.swift b/Sources/BasicContainers/HashTable/_Htable+Debugging.swift index 4a4cb846..52f3ee53 100644 --- a/Sources/BasicContainers/HashTable/_Htable+Debugging.swift +++ b/Sources/BasicContainers/HashTable/_Htable+Debugging.swift @@ -15,39 +15,73 @@ import InternalCollectionsUtilities #if compiler(>=6.2) extension _HTable { - package var description: String { - let multiline = self.endBucket.offset > Word.capacity + package func maxOccupiedRun() -> Int { + if isSmall { + return self.count + } + var maxOccupiedRun = 0 + var it = self.makeBucketIterator() + var first = true + var wrap = 0 + while let next = it.nextOccupiedRegion() { + if first, next.lowerBound.offset == 0 { + wrap = next._offsets.count + } + first = false + var c = next._offsets.count + if next.upperBound == self.endBucket { + c += wrap + } + maxOccupiedRun = max(maxOccupiedRun, c) + } + return maxOccupiedRun + } - var buckets = "" + package var _bitmapDescription: String { + let multiline = self.endBucket.offset > Word.capacity + var str = "" if !self.isSmall { let lastWord = self.endBucket.bit > 0 ? self.endBucket.word : self.endBucket.word - 1 var it = self.makeBucketIterator() while !it.isAtEnd { if it.currentBucket.isOnWordBoundary { if multiline { - buckets += "\n " - buckets += it.currentBucket.word == lastWord ? "└╴" : "├╴" - buckets += "[" + String(it.currentBucket.offset).lpad(8, with: "0") + "] " + str += "\n " + str += it.currentBucket.word == lastWord ? "└╴" : "├╴" + str += "[" + String(it.currentBucket.offset).lpad(8, with: "0") + "] " } else { - buckets += " " + str += " " } } else if it.currentBucket.bit % 8 == 0 { - buckets += "∙" + str += "∙" } - buckets.append(it.isOccupied ? "■" : "□") + str.append(it.isOccupied ? "■" : "□") it.advanceToNextBit() } } - + return str + } + + package func describe( + bitmap: Bool = false, + ) -> String { + let bitmapDesc = bitmap ? self._bitmapDescription : "" + let multiline = bitmapDesc.unicodeScalars.contains("\n") var s = "⌗ \(scale == 0 ? "small" : "large@\(scale)")" - s += "\(multiline ? "" : buckets) " - s += "\(count)/\(capacity), " - s += "totalProbeLength: \(_totalProbeLength)" + s += "\(multiline ? "" : bitmapDesc) " + s += "\(count)/\(capacity)/\(bucketCount), " + s += "maxProbeLength: \(_maxProbeLength), " + s += "totalProbeLength: \(_totalProbeLength), " + s += "maxOccupiedRun: \(maxOccupiedRun())" if !self.isSmall, multiline { - s += buckets + s += bitmapDesc } return s } + + package var description: String { + describe() + } } #endif diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift b/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift index 64724958..9c6f6e15 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift @@ -13,8 +13,106 @@ @available(SwiftStdlib 5.0, *) extension RigidSet where Element: ~Copyable { - public func _dump() { - print(_table.description) + public func _describe( + bitmap: Bool = false, + chains: Bool = false, + ) -> String { + var s = _table.describe(bitmap: bitmap) + if chains { + s += "\n" + s += _chainDescription + } + return s + } + + public func _dump( + bitmap: Bool = false, + chains: Bool = false, + ) { + print(self._describe(bitmap: bitmap, chains: chains)) + } + + public func _probeLengthCounts() -> (successful: [Int], unsuccessful: [Int]) { + var positiveLengths: [Int: Int] = [:] + var negativeLengths: [Int: Int] = [:] + var it = self._table.makeBucketIterator() + var prev = self._table.startBucket + while let next = it.nextOccupiedRegion() { + negativeLengths[0, default: 0] += next.lowerBound.offset - prev.offset + var b = next.lowerBound + while b != next.upperBound { + let hashValue = self._hashValue(at: b) + let pl = _table.probeLength(forHashValue: hashValue, in: b) + positiveLengths[pl, default: 0] += 1 + + var nl = next.upperBound.offset - b.offset +#if !COLLECTIONS_NO_ROBIN_HOOD_HASHING + nl = Swift.min(nl, _table._maxProbeLength) +#endif + negativeLengths[nl, default: 0] += 1 + _table.formBucket(after: &b) + } + prev = next.upperBound + } + var successful = Array(repeating: 0, count: positiveLengths.keys.max() ?? 0) + assert(positiveLengths[0] == nil) + var totalChainLength = 0 + var totalCount = 0 + for (length, count) in positiveLengths { + successful[length - 1] = count + totalChainLength += length * count + totalCount += count + } + assert(totalCount == self.count) + + var unsuccessful = Array( + repeating: 0, + count: 1 + (negativeLengths.keys.max() ?? 0)) + for (length, count) in negativeLengths { + unsuccessful[length] = count + } + //assert(totalChainLength == _table._totalProbeLength) + return (successful, unsuccessful) + } + + package var _chainDescription: String { + let data = self._probeLengthCounts() + var str = "" + do { + str += "Chain length distribution (for successful lookups):\n" + let max = data.successful.max() ?? 1 + var sum = 0 + var histogram = "" + for length in data.successful.indices { + let count = data.successful[length] + histogram += "\(String(length + 1).lpad(6)): " + let dotCount = (75 * count + max) / max + histogram += String(repeating: "*", count: dotCount) + histogram += " \(count)\n" + sum += (length + 1) * count + } + let avg = Double((sum * 1000 + 500) / _table.count) / 1000.0 + str += " AVG: \(avg)\n" + str += histogram + } + do { + str += "Chain length distribution (for unsuccessful lookups):\n" + let max = data.unsuccessful.max() ?? 1 + var sum = 0 + var histogram = "" + for length in data.unsuccessful.indices { + let count = data.unsuccessful[length] + histogram += "\(String(length).lpad(6)): " + let dotCount = (75 * count + max) / max + histogram += String(repeating: "*", count: dotCount) + histogram += " \(count)\n" + sum += length * count + } + let avg = Double((sum * 1000 + 500) / _table.storageCapacity) / 1000.0 + str += " AVG: \(avg)\n" + str += histogram + } + return str } } diff --git a/Sources/BasicContainers/RigidSet/RigidSet.swift b/Sources/BasicContainers/RigidSet/RigidSet.swift index 12a57d43..b3afd12e 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet.swift @@ -123,7 +123,7 @@ extension RigidSet where Element: ~Copyable { internal borrowing func _hashValue( at bucket: _HTable.Bucket ) -> Int { - assert(bucket.offset >= 0 && bucket.offset < capacity) + assert(bucket.offset >= 0 && bucket.offset < _table.storageCapacity) return _hashValue(for: _members.unsafelyUnwrapped[bucket.offset]) } diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Debugging.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Debugging.swift index 3d76ca50..d01b58ef 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Debugging.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Debugging.swift @@ -13,8 +13,18 @@ @available(SwiftStdlib 5.0, *) extension UniqueSet where Element: ~Copyable { - public func _dump() { - _storage._dump() + public func _describe( + bitmap: Bool = false, + chains: Bool = false, + ) -> String { + _storage._describe(bitmap: bitmap, chains: chains) + } + + public func _dump( + bitmap: Bool = false, + chains: Bool = false, + ) { + _storage._dump(bitmap: bitmap, chains: chains) } } diff --git a/Tests/BasicContainersTests/RigidSetTests.swift b/Tests/BasicContainersTests/RigidSetTests.swift index 9073da04..66392b51 100644 --- a/Tests/BasicContainersTests/RigidSetTests.swift +++ b/Tests/BasicContainersTests/RigidSetTests.swift @@ -110,7 +110,7 @@ class RigidSetTests: CollectionTestCase { } func test_update_full() { - withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 200, 201, 202, 203, 1000]) { capacity in + withEvery("capacity", in: [0, 1, 2, 10, 100, 200, 1000]) { capacity in withLifetimeTracking { tracker in var s = RigidSet>(capacity: capacity) for i in 0 ..< capacity { @@ -146,7 +146,7 @@ class RigidSetTests: CollectionTestCase { } func test_bucketIterator_consistency() { - withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 1000]) { capacity in + withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 200]) { capacity in withEvery("maximumCount", in: [1, 2, 3, Int.max]) { maximumCount in withLifetimeTracking { tracker in var s = RigidSet>(capacity: capacity) @@ -184,6 +184,18 @@ class RigidSetTests: CollectionTestCase { } } } + + func test_probeLengths() { + // FIXME: This isn't really testing anything; figure out how to handle this + let c1 = 1000 + let scale = _HTable.minimumScale(forCapacity: c1) + let c2 = _HTable.maximumCapacity(forScale: scale) + var set = RigidSet(capacity: c2) + for i in 0 ..< 1536 { + set.insert(i) + } + set._dump(chains: true) + } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW func test_iterate() {