diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift index e035db46..3c9214e2 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift @@ -201,6 +201,57 @@ extension OrderedSet { } } +extension OrderedSet { + /// Replace the member at the given index with a new element. + /// + /// If `item` compares equal to the member currently at `index`, then it is + /// replaced in place, leaving the set's order unchanged (as in + /// `update(_:at:)`). Otherwise the original member is removed and `item` + /// takes over its position: + /// + /// var set: OrderedSet = [1, 2, 3] + /// let old = set.replace(4, at: 1) + /// // old == 2 + /// // set is now [1, 4, 3] + /// + /// Replacing a member with an element that is already in the set at a + /// different index triggers a runtime error, as that would introduce a + /// duplicate. + /// + /// - Parameter item: The element to place at `index`. It must not already be + /// a member of the set, unless it compares equal to the member currently + /// at `index`. + /// + /// - Parameter index: The index of the member to replace. It must be a valid + /// index below `endIndex`. + /// + /// - Returns: The original member that was replaced. + /// + /// - Complexity: Expected amortized O(1), if `Element` implements + /// high-quality hashing. + @inlinable + @discardableResult + public mutating func replace(_ item: Element, at index: Int) -> Element { + precondition(index >= 0 && index < count, "Index out of bounds") + defer { _checkInvariants() } + let (existing, bucket) = _find(item) + + // The new element compares equal to the one already at `index` — replace + // it in place. Its hash table bucket is unchanged, so no rehash is needed. + if existing == index { + return update(item, at: index) + } + + precondition(existing == nil, "Duplicate element") + + // Append the new element, swap it into the target position, and remove the + // old member from the end — each step is O(1). + _appendNew(item, in: bucket) + swapAt(index, count - 1) + return removeLast() + } +} + extension OrderedSet { /// Adds the given element to the set unconditionally, either appending it to /// the set, or replacing an existing value if it's already present. diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index c6811714..6c3c4b72 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -565,6 +565,56 @@ class OrderedSetTests: CollectionTestCase { } } + func test_replace_at() { + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + let count = layout.count + let contents = (0 ..< count).map { tracker.instance(for: $0) } + withEvery("offset", in: 0 ..< count) { offset in + var set = OrderedSet(layout: layout, contents: contents) + withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in + let new = tracker.instance(for: count + offset) // Not yet a member. + let old = set.replace(new, at: offset) + expectIdentical(old, contents[offset]) + expectIdentical(set[offset], new) + expectEqual(set.firstIndex(of: new), offset) + expectNil(set.firstIndex(of: contents[offset])) + // The other members keep their original positions and identities. + withEvery("j", in: 0 ..< count) { j in + if j != offset { expectIdentical(set[j], contents[j]) } + } + } + } + } + } + } + } + + func test_replace_at_equalElement() { + // Replacing a member with an equal element swaps the new instance into + // place, like `update(_:at:)`. + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + let count = layout.count + let contents = (0 ..< count).map { tracker.instance(for: $0) } + withEvery("offset", in: 0 ..< count) { offset in + var set = OrderedSet(layout: layout, contents: contents) + withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in + // Equal to `contents[offset]`, but a distinct instance. + let new = tracker.instance(for: offset) + let old = set.replace(new, at: offset) + expectIdentical(old, contents[offset]) + expectIdentical(set[offset], new) + expectEqualElements(set, contents) + } + } + } + } + } + } + func test_partition() { withOrderedSetLayouts(scales: [0, 5, 6]) { layout in withEvery("offset", in: 0 ... layout.count) { offset in