Merge pull request #836 from sandeepvijayarao09/fix-unique-dictionary-closure-removal

[BasicContainers] Fix double destroy in UniqueDictionary.updateValue(forKey:with:)
This commit is contained in:
Karoy Lorentey authored and GitHub committed 2026-11-05 18:50:36 -08:00
commit 9b328ecb94
3 files changed
+50 -1

No files matched your search

@@ -93,7 +93,8 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
if let value = value.take() { // Simple update
unsafe _storage._valuePtr(at: bucket).initialize(to: value)
} else { // Removal
_ = unsafe _removeValue(at: bucket)
// The value has already been moved out of its slot above.
unsafe _removeEntry(withMovedValueAt: bucket)
}
} else if let value = value.take() {
// Insertion.
@@ -34,6 +34,21 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
_resize(minimumCapacity: self.count)
return result
}
/// Remove the entry at `bucket`, assuming its value slot has already been
/// moved out (e.g., by `updateValue(forKey:with:)`). Shrinks storage the
/// same way as `_removeValue(at:)`.
@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)
}
}
@inlinable
@inline(__always)
@@ -364,6 +364,39 @@ class UniqueDictionaryTests: CollectionTestCase {
}
}
func test_updateValue_closure_removal() {
// Removing an entry by setting the value to nil in
// `updateValue(forKey:with:)` must not destroy the (already moved-out)
// value a second time. Removing everything also exercises shrinking.
typealias Key = LifetimeTracked<Int>
typealias Value = LifetimeTracked<String>
withEvery("count", in: [1, 2, 10, 100, 200]) { count in
withLifetimeTracking { tracker in
var d = UniqueDictionary<Key, Value>()
for i in 0 ..< count {
d.insertValue(tracker.instance(for: "\(i)"), forKey: tracker.instance(for: i))
}
withEvery("key", in: 0 ..< count) { key in
let old = d.updateValue(forKey: tracker.instance(for: key)) { value in
let old = value?.payload
value = nil
return old
}
expectEqual(old, "\(key)")
expectEqual(d.count, count - key - 1)
expectTrue(d._checkInvariants())
for other in key + 1 ..< count {
expectEqual(
d.withValue(forKey: tracker.instance(for: other)) { $0.payload },
"\(other)")
}
}
expectEqual(d.count, 0)
expectEqual(tracker.instances, 0)
}
}
}
func test_memoizedValue_returnsNewlyInsertedValue() {
// Inserting a new key can displace existing entries (by swapping them
// around in both small and hashed storage); `memoizedValue` must still