[BasicContainers] Implement removals on RigidSet and UniqueSet

Dictionaries are still to be done.
This commit is contained in:
Karoy Lorentey committed 2026-02-20 18:19:51 -08:00
1 parent d318a65867
commit 3941dab5b0
23 files changed
+513 -104

No files matched your search

@@ -19,7 +19,6 @@ extension _HTable {
// FIXME: Scramble order by swapping things in some way
let r = Bucket(offset: _count)
_count &+= 1
_totalProbeLength += _count
_maxProbeLength = _count
return r
}
@@ -40,7 +39,6 @@ extension _HTable {
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
@@ -49,7 +47,6 @@ extension _HTable {
var probeLength = 0
while bitmap.isOccupied(b) {
probeLength &+= 1
_totalProbeLength &+= 1
let oldHashValue = hashGenerator(b)
let oldProbeLength = self.probeLength(
forHashValue: oldHashValue,
@@ -68,7 +65,6 @@ extension _HTable {
if probeLength > _maxProbeLength {
_maxProbeLength = probeLength
}
_totalProbeLength &+= 1
return b
#endif
}
@@ -0,0 +1,103 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if compiler(>=6.2)
extension _HTable {
/// Create a hole at the specified occupied bucket without marking it as
/// unoccupied ot restoring the hash table's other invariants. After a hole
/// is created, the table remains in an inconsistent state until one of
/// `resolveHole` or `finalizeHole` is called on the same bucket.
@usableFromInline
package mutating func createHole(
at bucket: Bucket
) {
assert(isOccupied(bucket))
_count &-= 1
}
/// Restore hash table invariants after a hole was created by `createHole`.
/// This works by swapping items as needed to move the hole forward until we
/// reach the end of the affected chain of occupied buckets.
@usableFromInline
@discardableResult
package mutating func resolveHole(
at bucket: Bucket,
hashGenerator: (Bucket) -> Int,
mover: (Bucket, Bucket) -> Void,
) -> Bucket {
if isSmall {
return finalizeHole(at: bucket, mover: mover)
}
assert(isOccupied(bucket))
// Our hash table does not have tombstones, so the holes that are left
// behind when an element is removed need to be immediately filled by the
// next item in the same chain that can now take that position. The process
// then repeats with the new hole thus created, until we reach the end of
// the chain. This is only possible because we're using linear probing;
// otherwise the same bucket would be part of a large number of diverging
// chains, and such compacting would require a full rehashing.
// Note: _maxProbeLength is not updated here, and so it may get out of
// sync with reality. It will get reset at the next rehashing, but if the
// table gets stuck at this size, this parameter may get significantly
// larger than it should be. The hope is that it won't so much larger that
// it would materially affect the performance of negative lookups.
var hole = bucket
var candidate = bucket
wrapBucket(after: &candidate)
while isOccupied(candidate) {
let hashValue = hashGenerator(candidate)
let ideal = self.idealBucket(forHashValue: hashValue)
// Does this element belong in some bucket at or below `hole`?
// If so, move it to the hole. We need two separate tests depending on
// whether `[hole, candidate]` wraps around the end of the storage.
let c0 = ideal <= hole
let c1 = ideal > candidate
if hole < candidate ? (c0 || c1) : (c0 && c1) {
mover(candidate, hole)
hole = candidate
}
wrapBucket(after: &candidate)
}
bitmap.clearOccupied(hole)
return hole
}
/// Finalize the hole at the given bucket, by moving it to some other position
/// (if needed), then marking it as unoccupied.
///
/// This does not fully restore the hash table to a usable state, but it
/// does enough to allow the hash table to get resized.
@discardableResult
@usableFromInline
package mutating func finalizeHole(
at bucket: Bucket,
mover: (Bucket, Bucket) -> Void,
) -> Bucket {
assert(isValid(bucket))
if isSmall {
let last = Bucket(offset: _count) // Note: _count was decreased by createHole
guard bucket < last else { return bucket }
mover(last, bucket)
return last
}
bitmap.clearOccupied(bucket)
return bucket
}
}
#endif
@@ -26,14 +26,16 @@ extension _HTable {
// ordered container.
let c = source.count
self._count = c
self._totalProbeLength = c * (c + 1) / 2
self._maxProbeLength = c
var dst = Bucket(offset: 0)
var src = Bucket(offset: c)
while src._offset > 0 {
src._offset &-= 1
migrator(src, dst)
dst._offset &+= 1
var dst = Bucket(offset: c)
var it = source.makeBucketIterator()
while let next = it.nextOccupiedRegion() {
var src = next.lowerBound
while src != next.upperBound {
dst._offset &-= 1
migrator(src, dst)
src._offset &+= 1
}
}
source.clear()
}
@@ -51,6 +51,25 @@ extension _HTable {
let shift = Swift.max(UInt(scale), Word.wordShift) - Word.wordShift
return 1 &<< shift
}
// These specific parameters result in the following capacity ranges:
//
// Scale Capacity range
// 4 2 ... 14
// 5 4 ... 28
// 6 8 ... 56
// 7 16 ... 112
// 8 32 ... 224
// 9 64 ... 448
// 10 128 ... 896
// 11 256 ... 1792
// 12 512 ... 3584
// etc.
//
// Note how neighboring intervals overlap significantly, as far as two steps
// away. This provides hysteresis for storage capacities, preventing hash
// tables from repeatedly shrinking/growing when only a handful of items are
// added/removed in a loop.
/// The numerator of the maximum hash table load factor.
@_transparent
@@ -29,14 +29,13 @@ package struct _HTable: ~Copyable {
@_alwaysEmitIntoClient
package let _bitmap: UnsafeMutablePointer<Word>?
@_alwaysEmitIntoClient
package var _totalProbeLength: Int
@_alwaysEmitIntoClient
package var _maxProbeLength: Int
@_alwaysEmitIntoClient
package let scale: UInt8
// FIXME: Add a reservedScale for UniqueSet/UniqueDictonary
@inlinable
internal init(
@@ -48,7 +47,6 @@ package struct _HTable: ~Copyable {
&& _capacity <= Self.maximumCapacity(forScale: scale))
self._count = 0
self._capacity = _capacity
self._totalProbeLength = 0
self._maxProbeLength = 0
self.scale = scale
if scale == 0 {
@@ -222,7 +220,6 @@ extension _HTable {
package mutating func clear() {
self._count = 0
self.bitmap.clearAll()
self._totalProbeLength = 0
self._maxProbeLength = 0
}
}
@@ -16,9 +16,7 @@ import InternalCollectionsUtilities
#if compiler(>=6.2)
extension _HTable {
package func maxOccupiedRun() -> Int {
if isSmall {
return self.count
}
if isSmall { return self.count }
var maxOccupiedRun = 0
var it = self.makeBucketIterator()
var first = true
@@ -48,7 +46,7 @@ extension _HTable {
if multiline {
str += "\n "
str += it.currentBucket.word == lastWord ? "└╴" : "├╴"
str += "[" + String(it.currentBucket.offset).lpad(8, with: "0") + "] "
str += "[" + String(it.currentBucket.offset)._lpad(8, with: "0") + "] "
} else {
str += " "
}
@@ -71,7 +69,6 @@ extension _HTable {
s += "\(multiline ? "" : bitmapDesc) "
s += "\(count)/\(capacity)/\(bucketCount), "
s += "maxProbeLength: \(_maxProbeLength), "
s += "totalProbeLength: \(_totalProbeLength), "
s += "maxOccupiedRun: \(maxOccupiedRun())"
if !self.isSmall, multiline {