diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift index efedd274..9a584e8f 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Elements.swift @@ -393,6 +393,55 @@ 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 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 + /// ] + /// 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] + /// + /// - 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. 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. + /// + /// - 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..bbeadd48 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift @@ -29,6 +29,83 @@ 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 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 + /// ] + /// let old = dict.replaceElement(at: 1, withKey: "d", value: 4) + /// // old == (key: "b", value: 2) + /// // dict is now ["a": 1, "d": 4, "c": 3] + /// + /// - 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. 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. + /// + /// - 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) + + // 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) + _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..62fc5abe 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -995,6 +995,61 @@ 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_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 3db7d455..d1e8d77a 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Elements Tests.swift @@ -177,6 +177,61 @@ 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_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