diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Removals.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Removals.swift index 3b012f57..5fbdcacf 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Removals.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Removals.swift @@ -60,11 +60,23 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable @unsafe package mutating func _punchHole(at bucket: _Bucket) -> Value { + assert(unsafe self._keys._table.isOccupied(bucket)) + let oldValue = unsafe self._valuePtr(at: bucket).move() + unsafe _punchHole(withMovedValueAt: bucket) + return oldValue + } + + /// Like `_punchHole(at:)`, but assumes the value slot at `bucket` has + /// already been moved out (e.g., by `updateValue(forKey:with:)`). + /// + /// This operation is intended to be used just before resizing the table. + @inlinable + @unsafe + package mutating func _punchHole(withMovedValueAt bucket: _Bucket) { assert(unsafe self._keys._table.isOccupied(bucket)) unsafe self._keys._table.createHole(at: bucket) unsafe self._keyPtr(at: bucket).deinitialize(count: 1) - let oldValue = unsafe self._valuePtr(at: bucket).move() let keys = unsafe self._keys._members.unsafelyUnwrapped unsafe self._keys._table.finalizeHole( at: bucket, @@ -72,7 +84,6 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { unsafe (keys + $1.offset).initialize(to: (keys + $0.offset).move()) unsafe (_values + $1.offset).initialize(to: (_values + $0.offset).move()) }) - return oldValue } @inlinable diff --git a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Removals.swift b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Removals.swift index 0d871718..29d0506c 100644 --- a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Removals.swift +++ b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Removals.swift @@ -41,13 +41,16 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable @unsafe package mutating func _removeEntry(withMovedValueAt bucket: _Bucket) { - let shrink = self.count <= _HTable.minimumCapacity(forScale: self._scale) - unsafe _storage._keyPtr(at: bucket).deinitialize(count: 1) - // FIXME: Avoid fully resolving the hole when `shrink` is true -- see `_punchHole` - unsafe _storage._resolveHole(at: bucket) - if shrink { - _resize(minimumCapacity: self.count) + guard self.count <= _HTable.minimumCapacity(forScale: self._scale) else { + unsafe _storage._keyPtr(at: bucket).deinitialize(count: 1) + unsafe _storage._resolveHole(at: bucket) + return } + + // Shrink storage. There is no need to restore hash table invariants first, + // as resizing rehashes every item anyway. + unsafe _storage._punchHole(withMovedValueAt: bucket) + _resize(minimumCapacity: self.count) } @inlinable