[OrderedCollections] Add OrderedSet.replace(_:at:)

`OrderedSet` already offers index-based mutations -- `update(_:at:)`, `insert(_:at:)`, `swapAt`, `remove(at:)` -- but no way to replace the member at an index with a *different* element. `update(_:at:)` looks like it should, but it requires the replacement to compare equal to the existing member.

Add `replace(_:at:)`, which replaces the member at a given index with a new element in expected amortized O(1) time. If the new element compares equal to the member at `index`, it is replaced in place via `update(_:at:)`; otherwise it is appended, swapped into position, and the old member is removed from the end -- each step O(1). Replacing a member with an element already present at a different index traps, as that would introduce a duplicate.

This is the OrderedSet counterpart of `OrderedDictionary.replaceElement(at:withKey:value:)` (#616), which already implements this dance on its keys' OrderedSet internally.
This commit is contained in:
inju2403 committed 2026-06-14 19:38:01 +09:00
1 parent af174fe447
commit 95d8afe88f
2 files changed
+101

No files matched your search

@@ -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.
@@ -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