[OrderedCollections] OrderedDictionary.replaceElement: allow the new key to equal the key at index

Per review feedback, relax the precondition so that the new key may compare equal to the key currently stored at index. This enables replacing an existing key with an equal-but-not-identical instance — for example, swapping a decomposed Unicode string with its precomposed equivalent — without an inefficient remove/insert workaround.

When the new key matches the one being replaced, the pair is updated in place via OrderedSet.update(_:at:) and the hash table is left untouched, preserving the expected amortized O(1) complexity.

Add a test_replaceElement_sameKey test on both OrderedDictionary and its Elements view that exercises the new path with LifetimeTracked keys carrying equal payloads but distinct instances.
This commit is contained in:
inju2403 committed 2026-04-23 21:38:11 +09:00
1 parent 9426246879
commit 8c5830ee46
4 files changed
+103 -16

No files matched your search

@@ -396,7 +396,22 @@ extension OrderedDictionary.Elements {
/// Replaces the key-value pair at the specified index with a new pair,
/// returning the original element.
///
/// The new key must not already exist in the dictionary.
/// The new key must either not already exist in the dictionary, or be
/// equal to the key currently stored at `index`. The latter form is
/// useful when equal keys can be distinguished by identity or some other
/// means — for example, replacing a decomposed Unicode string with its
/// precomposed equivalent:
///
/// var dict: OrderedDictionary = [
/// "a": 1, "e\u{301}": 2, "c": 3
/// ]
/// dict.elements.replaceElement(at: 1, withKey: "é", value: 2)
/// // dict is now ["a": 1, "é": 2, "c": 3]
///
/// In the general case, the new pair is appended, swapped into position,
/// and the old element is removed from the end — each step is O(1).
/// When the new key compares equal to the one being replaced, the pair
/// is updated in place and the hash table is left untouched.
///
/// var dict: OrderedDictionary = [
/// "a": 1, "b": 2, "c": 3
@@ -405,16 +420,11 @@ extension OrderedDictionary.Elements {
/// // old == (key: "b", value: 2)
/// // dict is now ["a": 1, "d": 4, "c": 3]
///
/// This method appends the new pair, swaps it into position, and removes
/// the old element from the end, achieving expected amortized O(1)
/// performance — unlike `remove(at:)` followed by an insertion, which
/// would be O(`count`).
///
/// - Parameters:
/// - index: The index of the element to replace. `index` must be a valid
/// index of the dictionary.
/// - key: The key of the new element. The dictionary must not already
/// contain this key.
/// - key: The key of the new element. If the dictionary already contains
/// this key, it must be at `index`.
/// - value: The value of the new element.
///
/// - Returns: The original key-value pair that was replaced.
@@ -32,7 +32,22 @@ extension OrderedDictionary {
/// Replaces the key-value pair at the specified index with a new pair,
/// returning the original element.
///
/// The new key must not already exist in the dictionary.
/// The new key must either not already exist in the dictionary, or be
/// equal to the key currently stored at `index`. The latter form is
/// useful when equal keys can be distinguished by identity or some other
/// means — for example, replacing a decomposed Unicode string with its
/// precomposed equivalent:
///
/// var dict: OrderedDictionary = [
/// "a": 1, "e\u{301}": 2, "c": 3
/// ]
/// dict.replaceElement(at: 1, withKey: "é", value: 2)
/// // dict is now ["a": 1, "é": 2, "c": 3]
///
/// In the general case, the new pair is appended, swapped into position,
/// and the old element is removed from the end — each step is O(1).
/// When the new key compares equal to the one being replaced, the pair
/// is updated in place and the hash table is left untouched.
///
/// var dict: OrderedDictionary = [
/// "a": 1, "b": 2, "c": 3
@@ -41,16 +56,11 @@ extension OrderedDictionary {
/// // old == (key: "b", value: 2)
/// // dict is now ["a": 1, "d": 4, "c": 3]
///
/// This method appends the new pair, swaps it into position, and removes
/// the old element from the end, achieving expected amortized O(1)
/// performance — unlike `remove(at:)` followed by an insertion, which
/// would be O(`count`).
///
/// - Parameters:
/// - index: The index of the element to replace. `index` must be a valid
/// index of the dictionary.
/// - key: The key of the new element. The dictionary must not already
/// contain this key.
/// - key: The key of the new element. If the dictionary already contains
/// this key, it must be at `index`.
/// - value: The value of the new element.
///
/// - Returns: The original key-value pair that was replaced.
@@ -67,6 +77,17 @@ extension OrderedDictionary {
precondition(index >= 0 && index < count, "Index out of range")
let (existingIndex, bucket) = _keys._find(key)
// The new key compares equal to the one already at `index` — replace
// in place. The hash bucket is unchanged, so no rehash is needed.
if existingIndex == index {
let oldKey = _keys.update(key, at: index)
let oldValue = _values[index]
_values[index] = value
_checkInvariants()
return (oldKey, oldValue)
}
precondition(existingIndex == nil, "Duplicate key: '\(key)'")
// Append the new key-value pair at the end — amortized O(1)
@@ -1022,6 +1022,34 @@ class OrderedDictionaryTests: CollectionTestCase {
}
}
func test_replaceElement_sameKey() {
withEvery("count", in: 1 ..< 20) { count in
withEvery("index", in: 0 ..< count) { index in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
// Same payload as the existing key at `index` — equal but a
// distinct instance, exercising the in-place replacement path.
let newKey = tracker.instance(for: index)
let newValue = tracker.instance(for: count + 100)
let expectedOld = reference[index]
reference[index] = (key: newKey, value: newValue)
withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let old = d.replaceElement(
at: index, withKey: newKey, value: newValue)
expectEqual(old.key, expectedOld.key)
expectEqual(old.value, expectedOld.value)
expectEquivalentElements(
d, reference,
by: { $0.key == $1.key && $0.value == $1.value })
expectEqual(d[newKey], newValue)
}
}
}
}
}
}
func test_partition() {
withEvery("seed", in: 0 ..< 10) { seed in
withEvery("count", in: 0 ..< 30) { count in
@@ -204,6 +204,34 @@ class OrderedDictionaryElementsTests: CollectionTestCase {
}
}
func test_replaceElement_sameKey() {
withEvery("count", in: 1 ..< 20) { count in
withEvery("index", in: 0 ..< count) { index in
withEvery("isShared", in: [false, true]) { isShared in
withLifetimeTracking { tracker in
var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count)
// Same payload as the existing key at `index` — equal but a
// distinct instance, exercising the in-place replacement path.
let newKey = tracker.instance(for: index)
let newValue = tracker.instance(for: count + 100)
let expectedOld = reference[index]
reference[index] = (key: newKey, value: newValue)
withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in
let old = d.elements.replaceElement(
at: index, withKey: newKey, value: newValue)
expectEqual(old.key, expectedOld.key)
expectEqual(old.value, expectedOld.value)
expectEquivalentElements(
d, reference,
by: { $0.key == $1.key && $0.value == $1.value })
expectEqual(d[newKey], newValue)
}
}
}
}
}
}
func test_partition() {
withEvery("seed", in: 0 ..< 10) { seed in
withEvery("count", in: 0 ..< 30) { count in