diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index 8f669ce5..9a584e8f 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift @@ -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. diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift index c9aefeab..bbeadd48 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift @@ -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) diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index a39967d7..62fc5abe 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -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 diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift index 0edd24c1..d1e8d77a 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift @@ -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