From c8cc9a7d4c7aef466ba646d2f4eba88b0baa4f18 Mon Sep 17 00:00:00 2001 From: Sandeep Vijayarao Date: Thu, 5 Nov 2026 17:50:49 -0800 Subject: [PATCH] [BasicContainers] Fix memoizedValue returning another key's value `RigidDictionary._insertNew` (and `RigidSet._insertNew`) returned the bucket reported by the hash table's `insertNew_Small`/`insertNew_Large`. That is where the *last displaced* item ends up, not the new item: small tables swap the new item into the middle and move the old middle item to the end, and hashed tables do Robin Hood swaps along the probe sequence. Whenever a swap happened, the returned bucket held some other entry. `memoizedValue(forKey:_:)` on `RigidDictionary` and `UniqueDictionary` returns a reference to the value at that bucket, so inserting a new key often returned the value of a different key. Track the first bucket the swapper writes the new item into, and return that (or the final bucket if nothing was swapped). The hash table's own return value is still used to initialize the displaced item, and its other user (rehashing in `migrateItems_Large`) is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../RigidDictionary+Insertions.swift | 17 +++++++++++++--- .../RigidSet/RigidSet+Insertions.swift | 17 +++++++++++++--- .../RigidDictionaryTests.swift | 20 +++++++++++++++++++ .../UniqueDictionaryTests.swift | 18 +++++++++++++++++ 4 files changed, 66 insertions(+), 6 deletions(-) diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Insertions.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Insertions.swift index dd303327..8dfb7ce1 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Insertions.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Insertions.swift @@ -15,6 +15,12 @@ @available(SwiftStdlib 5.0, *) extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { + /// Inserts a new key-value pair whose key isn't already in the dictionary, + /// and returns the bucket where the new pair ended up. + /// + /// Note that the insertion may displace existing items: the bucket returned + /// by the underlying hash table is where the _last displaced_ item went, + /// which is only the same as the new item's bucket if nothing was swapped. @inlinable @inline(__always) @discardableResult @@ -28,18 +34,20 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { let keys = unsafe _keyBuf let values = unsafe _valueBuf if self._keys._isSmall { + var newBucket: _Bucket? = nil let bucket = unsafe self._keys._table.insertNew_Small( swapper: { + if newBucket == nil { newBucket = $0 } unsafe swap(&key, &keys[$0]) unsafe swap(&value, &values[$0]) }) unsafe keys._initializeElement(at: bucket, to: key) unsafe values._initializeElement(at: bucket, to: value) - return bucket + return newBucket ?? bucket } return unsafe _insertNew_Large(key, hashValue: hashValue, value) } - + @_alwaysEmitIntoClient @inline(__always) @unsafe @@ -51,18 +59,21 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { let keys = unsafe _keyBuf let values = unsafe _valueBuf let seed = self._keys._seed + var newBucket: _Bucket? = nil let bucket = unsafe self._keys._table.insertNew_Large( hashValue: hashValue, hashGenerator: { unsafe keys[$0]._rawHashValue(seed: seed) }, swapper: { bucket in + // The first swap puts the new item in its final place. + if newBucket == nil { newBucket = bucket } unsafe swap(&key, &keys[bucket]) unsafe swap(&value, &values[bucket]) }) unsafe keys.initializeElement(at: bucket.offset, to: key) unsafe values.initializeElement(at: bucket.offset, to: value) - return bucket + return newBucket ?? bucket } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift index 9f0c0779..e168a93d 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift @@ -41,6 +41,12 @@ extension RigidSet where Element: ~Copyable { package var found: Bool { remnant != nil } } + /// Inserts a new item that isn't already in the set, and returns the bucket + /// where the new item ended up. + /// + /// Note that the insertion may displace existing items: the bucket returned + /// by the underlying hash table is where the _last displaced_ item went, + /// which is only the same as the new item's bucket if nothing was swapped. @inlinable @inline(__always) @discardableResult @@ -51,16 +57,18 @@ extension RigidSet where Element: ~Copyable { precondition(!isFull, "RigidSet capacity overflow") let storage = unsafe _memberBuf if _isSmall { + var newBucket: _Bucket? = nil let bucket = unsafe _table.insertNew_Small( swapper: { + if newBucket == nil { newBucket = $0 } unsafe swap(&item, &storage[$0]) }) unsafe storage._initializeElement(at: bucket, to: item) - return bucket + return newBucket ?? bucket } return _insertNew_Large(item, hashValue: hashValue) } - + @inlinable @discardableResult package mutating func _insertNew_Large( @@ -69,16 +77,19 @@ extension RigidSet where Element: ~Copyable { ) -> _Bucket { let storage = unsafe _memberBuf let seed = self._seed + var newBucket: _Bucket? = nil let bucket = unsafe _table.insertNew_Large( hashValue: hashValue, hashGenerator: { unsafe storage[$0]._rawHashValue(seed: seed) }, swapper: { + // The first swap puts the new item in its final place. + if newBucket == nil { newBucket = $0 } unsafe swap(&item, &storage[$0]) }) unsafe storage.initializeElement(at: bucket.offset, to: item) - return bucket + return newBucket ?? bucket } /// Inserts the given element into the set unconditionally. If the set already diff --git a/Tests/BasicContainersTests/RigidDictionaryTests.swift b/Tests/BasicContainersTests/RigidDictionaryTests.swift index 50805a36..5c438995 100644 --- a/Tests/BasicContainersTests/RigidDictionaryTests.swift +++ b/Tests/BasicContainersTests/RigidDictionaryTests.swift @@ -274,6 +274,26 @@ class RigidDictionaryTests: CollectionTestCase { } } + 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 + // return the value that was just inserted. + withEvery("capacity", in: [1, 2, 5, 7, 8, 20, 100]) { capacity in + var d = RigidDictionary(capacity: capacity) + withEvery("key", in: 0 ..< capacity) { key in + let v = d.memoizedValue(forKey: key) { "\($0)" } + expectEqual(v.value, "\(key)") + } + withEvery("key", in: 0 ..< capacity) { key in + let v = d.memoizedValue(forKey: key) { _ in + expectFailure("Cached value not found") + return "" + } + expectEqual(v.value, "\(key)") + } + } + } + func test_keys() { typealias Key = LifetimeTracked typealias Value = LifetimeTracked diff --git a/Tests/BasicContainersTests/UniqueDictionaryTests.swift b/Tests/BasicContainersTests/UniqueDictionaryTests.swift index f4f4aff4..14dbba8f 100644 --- a/Tests/BasicContainersTests/UniqueDictionaryTests.swift +++ b/Tests/BasicContainersTests/UniqueDictionaryTests.swift @@ -364,6 +364,24 @@ class UniqueDictionaryTests: CollectionTestCase { } } + 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 + // return the value that was just inserted. + var d = UniqueDictionary() + withEvery("key", in: 0 ..< 200) { key in + let v = d.memoizedValue(forKey: key) { "\($0)" } + expectEqual(v.value, "\(key)") + } + withEvery("key", in: 0 ..< 200) { key in + let v = d.memoizedValue(forKey: key) { _ in + expectFailure("Cached value not found") + return "" + } + expectEqual(v.value, "\(key)") + } + } + func test_removeAll() { typealias Key = LifetimeTracked typealias Value = LifetimeTracked