From 9426246879a2f08a9186ba9cc5d6e612b949d0cc Mon Sep 17 00:00:00 2001 From: inju2403 <56947879+inju2403@users.noreply.github.com> Date: Fri, 3 Apr 2026 16:55:14 +0900 Subject: [PATCH 1/2] [OrderedCollections] Add OrderedDictionary.replaceElement(at:withKey:value:) --- .../OrderedDictionary+Elements.swift | 39 +++++++++++++ ...Dictionary+Partial MutableCollection.swift | 56 +++++++++++++++++++ .../OrderedDictionary Tests.swift | 27 +++++++++ .../OrderedDictionary+Elements Tests.swift | 27 +++++++++ 4 files changed, 149 insertions(+) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index efedd274..8f669ce5 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift @@ -393,6 +393,45 @@ extension OrderedDictionary.Elements { _base.swapAt(i, j) } + /// 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. + /// + /// var dict: OrderedDictionary = [ + /// "a": 1, "b": 2, "c": 3 + /// ] + /// let old = dict.elements.replaceElement(at: 1, withKey: "d", value: 4) + /// // 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. + /// - value: The value of the new element. + /// + /// - Returns: The original key-value pair that was replaced. + /// + /// - Complexity: Expected amortized O(1), if `Key` implements + /// high-quality hashing. + @inlinable + @inline(__always) + @discardableResult + public mutating func replaceElement( + at index: Int, + withKey key: Key, + value: Value + ) -> Element { + _base.replaceElement(at: index, withKey: key, value: value) + } + /// Reorders the elements of the dictionary such that all the elements that /// match the given predicate are after all the elements that don't match. /// diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift index 4cdd46ec..c9aefeab 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift @@ -29,6 +29,62 @@ extension OrderedDictionary { _values.swapAt(i, j) } + /// 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. + /// + /// var dict: OrderedDictionary = [ + /// "a": 1, "b": 2, "c": 3 + /// ] + /// let old = dict.replaceElement(at: 1, withKey: "d", value: 4) + /// // 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. + /// - value: The value of the new element. + /// + /// - Returns: The original key-value pair that was replaced. + /// + /// - Complexity: Expected amortized O(1), if `Key` implements + /// high-quality hashing. + @inlinable + @discardableResult + public mutating func replaceElement( + at index: Int, + withKey key: Key, + value: Value + ) -> Element { + precondition(index >= 0 && index < count, "Index out of range") + + let (existingIndex, bucket) = _keys._find(key) + precondition(existingIndex == nil, "Duplicate key: '\(key)'") + + // Append the new key-value pair at the end — amortized O(1) + _keys._appendNew(key, in: bucket) + _values.append(value) + + // Swap the new element into the target position — O(1) + _keys.swapAt(index, count - 1) + _values.swapAt(index, count - 1) + + // Remove the old element from the end — O(1) + let oldKey = _keys.removeLast() + let oldValue = _values.removeLast() + + _checkInvariants() + return (oldKey, oldValue) + } + /// Reorders the elements of the dictionary such that all the elements that /// match the given predicate are after all the elements that don't match. /// diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index ecf57f03..a39967d7 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -995,6 +995,33 @@ class OrderedDictionaryTests: CollectionTestCase { } } + func test_replaceElement() { + 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) + let newKey = tracker.instance(for: count) + 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) + expectNil(d[expectedOld.key]) + } + } + } + } + } + } + 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 3db7d455..0edd24c1 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift @@ -177,6 +177,33 @@ class OrderedDictionaryElementsTests: CollectionTestCase { } } + func test_replaceElement() { + 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) + let newKey = tracker.instance(for: count) + 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) + expectNil(d[expectedOld.key]) + } + } + } + } + } + } + func test_partition() { withEvery("seed", in: 0 ..< 10) { seed in withEvery("count", in: 0 ..< 30) { count in From 8c5830ee4604f2bbeece3520adce7cf011c8734a Mon Sep 17 00:00:00 2001 From: inju2403 <56947879+inju2403@users.noreply.github.com> Date: Thu, 23 Apr 2026 21:38:11 +0900 Subject: [PATCH 2/2] [OrderedCollections] OrderedDictionary.replaceElement: allow the new key to equal the key at index MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- .../OrderedDictionary+Elements.swift | 26 +++++++++---- ...Dictionary+Partial MutableCollection.swift | 37 +++++++++++++++---- .../OrderedDictionary Tests.swift | 28 ++++++++++++++ .../OrderedDictionary+Elements Tests.swift | 28 ++++++++++++++ 4 files changed, 103 insertions(+), 16 deletions(-) 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