From 508f36f48d23a429a9cb01f571edc8bd1601b43e Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Mon, 25 May 2026 22:49:14 -0700 Subject: [PATCH 1/4] [OrderedSet] Add move(_:toOffset:) Adds two overloads for relocating elements within an `OrderedSet`: one taking a contiguous `Range`, and one taking a `Sequence`. The moved elements occupy consecutive positions starting at the destination, in the order they appear in the input. The hot path runs in O(*d* + *k*) time, where *d* is the distance moved and *k* is the number of elements moved; the implementation falls back to O(`count`) for large moves. --- .../Benchmarks/OrderedSetBenchmarks.swift | 220 ++++++++ .../Extensions/OrderedSet.md | 2 + .../OrderedSet/OrderedSet+Move.swift | 526 ++++++++++++++++++ .../OrderedSet/OrderedSetTests.swift | 296 +++++++++- 4 files changed, 1043 insertions(+), 1 deletion(-) create mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift diff --git a/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift b/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift index 9e51e2a9..19cd5a5f 100644 --- a/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift +++ b/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift @@ -610,5 +610,225 @@ extension Benchmark { } } + self.add( + title: "OrderedSet move(sequence) 1 trailing, to front", + input: Int.self + ) { size in + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move([size - 1], toOffset: 0) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(sequence) 1 trailing, to middle", + input: Int.self + ) { size in + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move([size - 1], toOffset: size / 2) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(sequence) 10% trailing, to front", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let toMove = Array((size - k) ..< size) + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move(toMove, toOffset: 0) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(sequence) 10% trailing, to middle", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let toMove = Array((size - k) ..< size) + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move(toMove, toOffset: size / 2) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(sequence) 50% evens, to front", + input: Int.self + ) { size in + let toMove = Array(stride(from: 0, to: size, by: 2)) + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move(toMove, toOffset: 0) + } + precondition(set.count == size) + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(sequence) 10% scattered, to middle", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let toMove = Array(stride(from: 0, to: size, by: Swift.max(size / k, 1)).prefix(k)) + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move(toMove, toOffset: size / 2) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(sequence) 1 mid, back by 5", + input: Int.self + ) { size in + guard size > 10 else { return nil } + let src = size / 2 + let dst = src - 5 + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move([src], toOffset: dst) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(sequence) 10 contiguous, back by 5", + input: Int.self + ) { size in + guard size > 20 else { return nil } + let start = size / 2 + let toMove = Array(start ..< start + 10) + let dst = start - 5 + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move(toMove, toOffset: dst) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(sequence) 10% contiguous, to front", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let start = size / 2 + let toMove = Array(start ..< Swift.min(start + k, size)) + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move(toMove, toOffset: 0) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(sequence) 10% contiguous, back by 5", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let start = size / 2 + let end = Swift.min(start + k, size) + let toMove = Array(start ..< end) + let dst = Swift.max(start - 5, 0) + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move(toMove, toOffset: dst) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(range) 10% mid, to front", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let start = size / 2 + let src = start ..< Swift.min(start + k, size) + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move(src, toOffset: 0) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(range) 10 mid, back by 5", + input: Int.self + ) { size in + guard size > 20 else { return nil } + let start = size / 2 + let src = start ..< start + 10 + let dst = start - 5 + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move(src, toOffset: dst) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(sequence) 10% contiguous reversed, to front", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let start = size / 2 + let end = Swift.min(start + k, size) + let toMove = Array((start ..< end).reversed()) + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move(toMove, toOffset: 0) + } + blackHole(set) + } + } + + self.add( + title: "OrderedSet move(sequence) 10 scattered in narrow window, local dest", + input: Int.self + ) { size in + guard size > 60 else { return nil } + let start = size / 2 + let toMove = Array(stride(from: start, to: start + 20, by: 2)) + let dst = start + 20 + return { timer in + var set = OrderedSet(0 ..< size) + timer.measure { + set.move(toMove, toOffset: dst) + } + blackHole(set) + } + } + } } diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md index a7d38994..a36adfef 100644 --- a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md @@ -129,6 +129,8 @@ - ``shuffle()`` - ``shuffle(using:)`` - ``partition(by:)`` +- ``move(_:toOffset:)-(Range,_)`` +- ``move(_:toOffset:)-(_,_)`` ### Creating and Applying Differences diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift new file mode 100644 index 00000000..9f93d153 --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift @@ -0,0 +1,526 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +// Reordering implementation. +// +// Both `move` overloads relocate elements to a new offset, preserving the +// order they appear in the input. The work splits into two concerns: +// +// 1. Rearrange `_elements` so the moved values are contiguous at the +// destination, with the surrounding elements compacted around them. +// 2. Update `_table` so each element's hash bucket points at its new +// offset. +// +// The implementation dispatches to one of three buffer strategies depending +// on the input shape: +// +// * Contiguous range source -> `_moveRange`: a three-reverse rotation of +// `_elements`. O(*d* + *k*) element moves, where *d* is the distance +// between source and destination and *k* is the source count. +// +// * Contiguous range source in a different order -> `_moveContiguousReordered`: +// rotation, followed by a cycle-following in-place permutation to +// reorder the moved block. +// +// * Scattered sources -> `_moveScattered`: a two-pointer compact-and-place +// pass that removes the source positions and writes the moved values +// into the resulting gap. O(*n*) element moves. +// +// For the hash table, each strategy further chooses between targeted +// per-element bucket updates and a coarse fallback (full-table scan in +// `_moveRange`, full rebuild in `_moveScattered`). The fallback is faster +// once the affected region grows beyond roughly a third of the table; see +// the `targetedUpdateLimit` comments at each branch. + +extension OrderedSet { + /// Moves the elements in the given range to the given offset, preserving + /// their relative order. + /// + /// var set: OrderedSet = [0, 1, 2, 3, 4, 5, 6] + /// set.move(4 ..< 6, toOffset: 1) + /// // set is now [0, 4, 5, 1, 2, 3, 6] + /// + /// - Parameters: + /// - range: The index range of elements to move. + /// - destination: The offset where the moved elements should start in + /// the resulting set. Must be in the range `0 ... count - range.count`. + /// + /// - Complexity: O(*d* + *k*) where *d* is the distance between the source + /// and destination, and *k* is the number of elements moved. Falls back + /// to O(`count`) for large moves. + @inlinable + public mutating func move( + _ range: Range, + toOffset destination: Int + ) { + let c = range.count + guard c > 0 else { return } + _failEarlyRangeCheck(range, bounds: startIndex ..< endIndex) + precondition( + destination >= 0 && destination <= count - c, + "Destination offset \(destination) out of range 0 ... \(count - c)") + guard range.lowerBound != destination else { return } + _moveRange(range.lowerBound, count: c, toOffset: destination) + _checkInvariants() + } + + @inlinable + internal mutating func _moveRange( + _ src: Int, + count: Int, + toOffset destination: Int + ) { + _elements.withUnsafeMutableBufferPointer { buffer in + buffer._moveSubrange(src ..< src + count, toOffset: destination) + } + + guard _table != nil else { return } + + _ensureUnique() + + let distance: Int = destination < src ? src - destination : destination - src + + _table!.update { hashTable in + // Targeted bucket updates touch O(count + distance) buckets, while a + // full scan touches all of `hashTable.capacity`. With a 3/4 load + // factor, scanning becomes cheaper once the affected region grows + // beyond roughly a third of the table. + let targetedUpdateLimit = hashTable.capacity / 3 + + if count <= targetedUpdateLimit && distance <= targetedUpdateLimit { + if destination < src { + for newPos in destination ..< destination + count { + var it = hashTable.bucketIterator(for: _elements[newPos]) + it.advance(until: newPos + distance) + it.currentValue = newPos + } + for newPos in destination + count ..< src + count { + var it = hashTable.bucketIterator(for: _elements[newPos]) + it.advance(until: newPos - count) + it.currentValue = newPos + } + } else { + for newPos in src ..< destination { + var it = hashTable.bucketIterator(for: _elements[newPos]) + it.advance(until: newPos + count) + it.currentValue = newPos + } + for newPos in destination ..< destination + count { + var it = hashTable.bucketIterator(for: _elements[newPos]) + it.advance(until: newPos - distance) + it.currentValue = newPos + } + } + } else { + var it = hashTable.bucketIterator( + startingAt: _Bucket(offset: 0)) + repeat { + if let value = it.currentValue { + if value >= src && value < src + count { + it.currentValue = destination < src + ? value - distance : value + distance + } else if destination < src + && value >= destination && value < src { + it.currentValue = value + count + } else if destination > src + && value >= src + count && value < destination + count { + it.currentValue = value - count + } + } + it.advance() + } while it.currentBucket.offset != 0 + } + } + } +} + +extension OrderedSet { + /// Moves the specified elements to the given offset, keeping them in the + /// order they appear in `elements`. + /// + /// Every value in `elements` must be a member of the set, and `elements` + /// must not contain duplicates. + /// + /// var set: OrderedSet = [0, 1, 2, 3, 4, 5, 6] + /// set.move([4, 1], toOffset: 2) + /// // set is now [0, 2, 4, 1, 3, 5, 6] + /// + /// - Parameters: + /// - elements: The elements to move. + /// - destination: The offset where the moved elements should start in + /// the resulting set. Must be in the range `0 ... count - k`, where + /// `k` is the number of elements being moved. + /// + /// - Complexity: O(`count`) in the worst case. When the elements form a + /// contiguous range or are moved a short distance, the operation is + /// proportional to the distance moved. + @inlinable + public mutating func move( + _ elements: some Sequence, + toOffset destination: Int + ) { + let toMove = ContiguousArray(elements) + let c = toMove.count + guard c > 0 else { return } + precondition( + destination >= 0 && destination <= count - c, + "Destination offset \(destination) out of range 0 ... \(count - c)") + + withUnsafeTemporaryAllocation(of: Int.self, capacity: c) { sourceOffsets in + var isContiguousRange = true + var isSorted = true + for i in 0 ..< c { + guard let index = _find(toMove[i]).index else { + preconditionFailure( + "Attempted to move an element that is not a member of the set") + } + if i > 0 { + let prev = sourceOffsets[i - 1] + if index <= prev { + isSorted = false + isContiguousRange = false + } else if index != prev + 1 { + isContiguousRange = false + } + } + sourceOffsets[i] = index + } + + var isNoOp = true + for i in 0 ..< c { + if sourceOffsets[i] != destination + i { + isNoOp = false + break + } + } + guard !isNoOp else { return } + + if isContiguousRange { + _moveRange(sourceOffsets[0], count: c, toOffset: destination) + _checkInvariants() + return + } + + _moveScattered( + sourceOffsets: sourceOffsets, + isSorted: isSorted, + count: c, + toOffset: destination) + } + } + + @inlinable + internal mutating func _moveScattered( + sourceOffsets: UnsafeMutableBufferPointer, + isSorted: Bool, + count: Int, + toOffset destination: Int + ) { + let totalCount = self.count + + withUnsafeTemporaryAllocation(of: Int.self, capacity: count) { sortedCopy in + if !isSorted { + for i in 0 ..< count { sortedCopy[i] = sourceOffsets[i] } + var mutableSortedCopy = sortedCopy + mutableSortedCopy.sort() + } + let sortedSources = isSorted ? sourceOffsets : sortedCopy + + if !isSorted { + for i in 1 ..< count { + precondition( + sortedSources[i] != sortedSources[i - 1], + "Duplicate element in move list") + } + } + + // Contiguous indices in a different order: rotate, then permute. + if sortedSources[count - 1] - sortedSources[0] == count - 1 { + _moveContiguousReordered( + sourceOffsets: sourceOffsets, + minSource: sortedSources[0], + count: count, + toOffset: destination) + return + } + + withUnsafeTemporaryAllocation( + of: Element.self, capacity: count + ) { saved in + for i in 0 ..< count { + saved.initializeElement(at: i, to: _elements[sourceOffsets[i]]) + } + defer { saved.baseAddress!.deinitialize(count: count) } + + _elements.withUnsafeMutableBufferPointer { buffer in + buffer._compactAndPlace( + removing: sortedSources, + inserting: saved, + at: destination, + totalCount: totalCount) + } + } + + guard _table != nil else { + _checkInvariants() + return + } + + _ensureUnique() + + let minSource: Int = sortedSources[0] + let maxSource: Int = sortedSources[count - 1] + let affectedStart: Int = Swift.min(minSource, destination) + let affectedEnd: Int = Swift.max(maxSource, destination + count - 1) + let affectedCount: Int = affectedEnd - affectedStart + 1 + + // Same heuristic as in `_moveRange`: when the affected region is small + // relative to the table, per-bucket updates beat a full-table rebuild. + let targetedUpdateLimit = _capacity / 3 + + if affectedCount <= targetedUpdateLimit { + _table!.update { hashTable in + for i in 0 ..< count { + let oldPos = sourceOffsets[i] + let newPos = destination + i + if oldPos != newPos { + var it = hashTable.bucketIterator(for: _elements[newPos]) + it.advance(until: oldPos) + it.currentValue = newPos + } + } + + if affectedStart < destination { + var oldPos = affectedStart + + sortedSources._sortedCount(below: affectedStart) + var si = oldPos - affectedStart + for newPos in affectedStart ..< destination { + // Mirrors the catch-up loop after the gap; see there. + while si < count && sortedSources[si] <= oldPos { + oldPos += 1 + si += 1 + } + if oldPos != newPos { + var it = hashTable.bucketIterator(for: _elements[newPos]) + it.advance(until: oldPos) + it.currentValue = newPos + } + oldPos += 1 + } + } + + if destination + count <= affectedEnd { + let firstNSIndex = destination + var oldPos = firstNSIndex + + sortedSources._sortedCount(below: firstNSIndex) + var si = oldPos - firstNSIndex + for newPos in (destination + count) ... affectedEnd { + // `<=` (not `==`): the initial `oldPos` counts sources + // strictly below `firstNSIndex`, so any source in + // `[firstNSIndex, oldPos]` still needs folding in here. + while si < count && sortedSources[si] <= oldPos { + oldPos += 1 + si += 1 + } + if oldPos != newPos { + var it = hashTable.bucketIterator(for: _elements[newPos]) + it.advance(until: oldPos) + it.currentValue = newPos + } + oldPos += 1 + } + } + } + } else { + _table!.update { hashTable in + hashTable.clear() + hashTable.fill(uncheckedUniqueElements: _elements) + } + } + + _checkInvariants() + } + } + + @inlinable + internal mutating func _moveContiguousReordered( + sourceOffsets: UnsafeMutableBufferPointer, + minSource: Int, + count: Int, + toOffset destination: Int + ) { + _moveRange(minSource, count: count, toOffset: destination) + + withUnsafeTemporaryAllocation(of: Int.self, capacity: count) { perm in + for i in 0 ..< count { + perm[i] = sourceOffsets[i] - minSource + } + + _elements.withUnsafeMutableBufferPointer { buffer in + buffer._applyPermutation(perm, offset: destination) + } + } + + if _table != nil { + _ensureUnique() + _table!.update { hashTable in + for i in 0 ..< count { + let oldLocalPos = sourceOffsets[i] - minSource + guard oldLocalPos != i else { continue } + var it = hashTable.bucketIterator( + for: _elements[destination + i]) + it.advance(until: destination + oldLocalPos) + it.currentValue = destination + i + } + } + } + + _checkInvariants() + } +} + +extension UnsafeMutableBufferPointer { + /// Moves a contiguous subrange to a new position using three-reverse + /// rotation. + @inlinable + internal func _moveSubrange( + _ source: Range, + toOffset destination: Int + ) { + let src = source.lowerBound + let count = source.count + if destination < src { + _reverse(destination ..< src) + _reverse(src ..< src + count) + _reverse(destination ..< src + count) + } else { + _reverse(src ..< src + count) + _reverse(src + count ..< destination + count) + _reverse(src ..< destination + count) + } + } + + /// Reverses elements in the given index range. + @inlinable + internal func _reverse(_ range: Range) { + var lo = range.lowerBound + var hi = range.upperBound - 1 + while lo < hi { + swapAt(lo, hi) + lo += 1 + hi -= 1 + } + } + + /// Removes elements at the positions in `sortedRemovals` (which must be + /// sorted and within bounds), compacts the remaining elements to leave a + /// gap at `destination`, and fills the gap from `insertions`. + /// + /// `totalCount` is the number of initialized elements in the buffer. + @inlinable + internal func _compactAndPlace( + removing sortedRemovals: UnsafeMutableBufferPointer, + inserting insertions: UnsafeMutableBufferPointer, + at destination: Int, + totalCount: Int + ) { + let removalCount = sortedRemovals.count + + // Forward pass: compact non-removed elements into 0..= destination + removalCount { + if sj >= 0 && sortedRemovals[sj] == readRight { + sj -= 1 + readRight -= 1 + } else { + if writeRight != readRight { + self[writeRight] = self[readRight] + } + writeRight -= 1 + readRight -= 1 + } + } + + // Place inserted elements in the gap. + for i in 0 ..< removalCount { + self[destination + i] = insertions[i] + } + } + + /// Applies a permutation to elements at `offset ..< offset + perm.count`. + /// After this call, the element that was at `offset + perm[i]` will be at + /// `offset + i`. The `perm` buffer is consumed (its contents are + /// undefined on return). + @inlinable + internal func _applyPermutation( + _ perm: UnsafeMutableBufferPointer, + offset: Int + ) { + for start in 0 ..< perm.count { + guard perm[start] != start else { continue } + var j = start + let temp = self[offset + j] + while perm[j] != start { + let from = perm[j] + self[offset + j] = self[offset + from] + perm[j] = j + j = from + } + self[offset + j] = temp + perm[j] = j + } + } +} + +extension UnsafeMutableBufferPointer where Element == Int { + /// Returns the number of elements strictly less than `value` in this + /// sorted buffer (i.e., the lower bound index). + @inlinable + internal func _sortedCount(below value: Int) -> Int { + var lo = 0 + var hi = count + while lo < hi { + let mid = lo + (hi - lo) / 2 + if self[mid] < value { + lo = mid + 1 + } else { + hi = mid + } + } + return lo + } +} diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index c8f67fec..554d7c78 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -1597,10 +1597,304 @@ class OrderedSetTests: CollectionTestCase { let leftSlice = items1[0 ..< i] expectNotEqual(items1[0 ..< c], leftSlice) // same identity expectNotEqual(items2[0 ..< c], leftSlice) // different identity - + let rightSlice = items1[i + 1 ..< c] expectNotEqual(items1[0 ..< c], rightSlice) // same identity expectNotEqual(items2[0 ..< c], rightSlice) // different identity } } + + func test_move_empty() { + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + var set = OrderedSet(layout: layout) + let expected = Array(0 ..< layout.count) + set.move([] as [Int], toOffset: 0) + expectEqualElements(set, expected) + } + } + + func test_move_single_element() { + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + guard count >= 1 else { return } + withEvery("source", in: 0 ..< count) { source in + withEvery("destination", in: 0 ..< count) { destination in + withEvery("isShared", in: [false, true]) { isShared in + var set = OrderedSet(layout: layout) + withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in + set.move([source], toOffset: destination) + var expected = Array(0 ..< count) + expected.remove(at: source) + expected.insert(source, at: destination) + expectEqualElements(set, expected) + withEvery("item", in: 0 ..< count) { item in + expectNotNil(set.firstIndex(of: item)) + } + } + } + } + } + } + } + + func test_move_multiple_elements_to_middle() { + // Spot-check for a moderately-sized non-contiguous input. The pair + // form is exhaustively covered by `test_move_exhaustive_small`. + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + guard count >= 4 else { return } + withEvery("isShared", in: [false, true]) { isShared in + var set = OrderedSet(layout: layout) + withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in + let mid = (count - 2) / 2 + set.move([0, count - 1], toOffset: mid) + var expected = Array(1 ..< count - 1) + expected.insert(contentsOf: [0, count - 1], at: mid) + expectEqualElements(set, expected) + } + } + } + } + + func test_move_all_elements() { + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + guard count >= 1 else { return } + withEvery("isShared", in: [false, true]) { isShared in + var set = OrderedSet(layout: layout) + withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in + let reversed = Array((0 ..< count).reversed()) + set.move(reversed, toOffset: 0) + expectEqualElements(set, reversed) + } + } + } + } + + func test_move_already_in_place() { + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + guard count >= 3 else { return } + var set = OrderedSet(layout: layout) + let expected = Array(0 ..< count) + set.move([1, 2], toOffset: 1) + expectEqualElements(set, expected) + } + } + + func test_move_scattered_sources() { + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + guard count >= 7 else { return } + withEvery("isShared", in: [false, true]) { isShared in + var set = OrderedSet(layout: layout) + withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in + let evens = stride(from: 0, to: count, by: 2).map { $0 } + let odds = stride(from: 1, to: count, by: 2).map { $0 } + set.move(evens, toOffset: 0) + var expected = evens + expected.append(contentsOf: odds) + expectEqualElements(set, expected) + withEvery("item", in: 0 ..< count) { item in + expectNotNil(set.firstIndex(of: item)) + } + } + } + } + } + + func test_move_reorders_within_destination() { + // The moved elements must appear in the order given by the input, + // not their original order. + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + guard count >= 5 else { return } + withEvery("isShared", in: [false, true]) { isShared in + var set = OrderedSet(layout: layout) + withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in + set.move([3, 1], toOffset: 1) + var expected = Array(0 ..< count) + expected.remove(at: 3) + expected.remove(at: 1) + expected.insert(contentsOf: [3, 1], at: 1) + expectEqualElements(set, expected) + } + } + } + } + + func test_move_exhaustive_small() { + withOrderedSetLayouts(scales: [0]) { layout in + let count = layout.count + guard count >= 3 else { return } + withEvery("a", in: 0 ..< count) { a in + withEvery("b", in: 0 ..< count) { b in + guard b != a else { return } + withEvery("destination", in: 0 ... count - 2) { destination in + var set = OrderedSet(layout: layout) + set.move([a, b], toOffset: destination) + var expected = Array(0 ..< count) + let ia = expected.firstIndex(of: a)! + expected.remove(at: ia) + let ib = expected.firstIndex(of: b)! + expected.remove(at: ib) + expected.insert(contentsOf: [a, b], at: destination) + expectEqualElements(set, expected) + } + } + } + } + } + + func test_move_range_noop() { + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + guard count >= 4 else { return } + var set = OrderedSet(layout: layout) + let expected = Array(0 ..< count) + let mid = count / 2 + set.move(mid ..< mid + 2, toOffset: mid) + expectEqualElements(set, expected) + } + } + + func test_move_range_exhaustive_small() { + withOrderedSetLayouts(scales: [0]) { layout in + let count = layout.count + guard count >= 2 else { return } + withEvery("src", in: 0 ..< count) { src in + withEvery("k", in: 1 ... count - src) { k in + withEvery("dst", in: 0 ... count - k) { dst in + var set = OrderedSet(layout: layout) + set.move(src ..< src + k, toOffset: dst) + var expected = Array(0 ..< count) + let removed = Array(expected[src ..< src + k]) + expected.removeSubrange(src ..< src + k) + expected.insert(contentsOf: removed, at: dst) + expectEqualElements(set, expected) + } + } + } + } + } + + func test_move_contiguous_elements_uses_range_path() { + // Moving contiguous elements via the sequence overload must agree with + // the dedicated range overload. + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + guard count >= 8 else { return } + let src = count / 2 + let k = 3 + let dst = 1 + var setA = OrderedSet(layout: layout) + var setB = OrderedSet(layout: layout) + setA.move(Array(src ..< src + k), toOffset: dst) + setB.move(src ..< src + k, toOffset: dst) + expectEqualElements(setA, setB) + } + } + + func test_move_contiguous_reordered() { + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + guard count >= 8 else { return } + withEvery("isShared", in: [false, true]) { isShared in + var set = OrderedSet(layout: layout) + withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in + let src = count / 2 + let k = 3 + let dst = 1 + let reversed = Array((src ..< src + k).reversed()) + set.move(reversed, toOffset: dst) + var expected = Array(0 ..< count) + expected.removeSubrange(src ..< src + k) + expected.insert(contentsOf: reversed, at: dst) + expectEqualElements(set, expected) + withEvery("item", in: 0 ..< count) { item in + expectNotNil(set.firstIndex(of: item)) + } + } + } + } + } + + func test_move_contiguous_reordered_exhaustive() { + withOrderedSetLayouts(scales: [0]) { layout in + let count = layout.count + guard count >= 5 else { return } + withEvery("src", in: 0 ..< count - 2) { src in + let elems = [src, src + 1, src + 2] + let permutations = [ + [elems[0], elems[2], elems[1]], + [elems[1], elems[0], elems[2]], + [elems[1], elems[2], elems[0]], + [elems[2], elems[0], elems[1]], + [elems[2], elems[1], elems[0]], + ] + withEvery("permIndex", in: permutations.indices) { permIndex in + let perm = permutations[permIndex] + withEvery("dst", in: 0 ... count - 3) { dst in + var set = OrderedSet(layout: layout) + set.move(perm, toOffset: dst) + var expected = Array(0 ..< count) + for e in perm.reversed() { + expected.remove(at: expected.firstIndex(of: e)!) + } + expected.insert(contentsOf: perm, at: dst) + expectEqualElements(set, expected) + } + } + } + } + } + + func test_move_scattered_destination_is_source_hash_table_size() { + // count = 16, scale 5 -> capacity 24, targetedUpdateLimit = 8. + // sortedSources = [3, 5, 10], destination = 5: affectedCount = 8, + // so the targeted-update path fires. `destination` is itself a source. + var set = OrderedSet(0 ..< 16) + set.move([3, 5, 10], toOffset: 5) + expectEqualElements(set, [0, 1, 2, 4, 6, 3, 5, 10, 7, 8, 9, 11, 12, 13, 14, 15]) + for v in 0 ..< 16 { + expectEqual(set.firstIndex(of: v), set.firstIndex(where: { $0 == v })) + } + let occupied = set.__unstable.hashTableContents.lazy + .filter { $0 != nil }.count + expectEqual(occupied, set.count) + } + + // Sweeps over all non-empty source subsets of size up to `maxK`, every + // permutation, and every destination. Verifies the hash table has no + // phantom or missing buckets after each move; element order and lookup + // checks alone don't catch that class of defect. + func test_move_exhaustive_hash_table_integrity() { + func check(_ set: OrderedSet, _ context: @autoclosure () -> String) { + let occupied = set.__unstable.hashTableContents.lazy + .filter { $0 != nil }.count + expectEqual(occupied, set.count, "\(context())") + for v in set { + expectEqual( + set.firstIndex(of: v), set.firstIndex(where: { $0 == v }), + "\(context()): firstIndex(of: \(v))") + } + } + + let n = 16 + #if COLLECTIONS_LONG_TESTS + let maxK = 5 + #else + let maxK = 3 + #endif + withEverySubset("subset", of: Array(0 ..< n)) { subset in + guard !subset.isEmpty, subset.count <= maxK else { return } + withEveryPermutation("perm", of: subset) { perm in + for dst in 0 ... (n - perm.count) { + var set = OrderedSet(0 ..< n) + set.move(perm, toOffset: dst) + check(set, "perm=\(perm) dst=\(dst)") + } + } + } + } } From a83773321e82ac44e9fcc2b3e7bca6251fd934ce Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Thu, 4 Jun 2026 22:26:51 -0700 Subject: [PATCH 2/4] [OrderedCollections] Rework move APIs and extend to OrderedDictionary Reworks the relocation API and extends it to `OrderedDictionary`: * Renames the index-range move to `moveSubrange(_:to:)` (with a `RangeExpression` overload) and the by-value move to `move(contentsOf:to:)`, matching the conventions of `removeSubrange`/`insert(_:at:)`. Adds `move(fromIndices:to:)`, which takes the source indices directly. * Factors the element rearrangement into generic `UnsafeMutableBufferPointer` operations (rotation / rotation+permutation / scatter) so `OrderedDictionary` relocates its keys and values in lockstep through the same code, adding only the parallel value move; the hash-table maintenance stays entirely in `OrderedSet`. * The hot path runs in O(*d* + *k*) and falls back to O(`count`) for large moves; bucket maintenance chooses targeted updates or a full rebuild by the same threshold. * `move(contentsOf:to:)` ignores elements/keys that aren't present; duplicate members are detected and trap. Adds tests (exhaustive hash-table integrity, value alignment under lifetime tracking) and move benchmarks for both types. --- .../OrderedDictionaryBenchmarks.swift | 236 +++++- .../Benchmarks/OrderedSetBenchmarks.swift | 28 +- .../Extensions/OrderedDictionary.md | 3 + .../Extensions/OrderedSet.md | 5 +- .../OrderedDictionary+Move.swift | 144 ++++ .../OrderedSet/OrderedSet+Move.swift | 701 +++++++++++------- .../OrderedDictionary Tests.swift | 157 ++++ .../OrderedSet/OrderedSetTests.swift | 153 +++- 8 files changed, 1120 insertions(+), 307 deletions(-) create mode 100644 Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift diff --git a/Benchmarks/Sources/Benchmarks/OrderedDictionaryBenchmarks.swift b/Benchmarks/Sources/Benchmarks/OrderedDictionaryBenchmarks.swift index 340ee001..bf2817b5 100644 --- a/Benchmarks/Sources/Benchmarks/OrderedDictionaryBenchmarks.swift +++ b/Benchmarks/Sources/Benchmarks/OrderedDictionaryBenchmarks.swift @@ -597,6 +597,240 @@ extension Benchmark { } } } - + + self.add( + title: "OrderedDictionary move(sequence) 1 trailing, to front", + input: Int.self + ) { size in + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: [size - 1], to: 0) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(sequence) 1 trailing, to middle", + input: Int.self + ) { size in + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: [size - 1], to: size / 2) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(sequence) 10% trailing, to front", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let toMove = Array((size - k) ..< size) + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: toMove, to: 0) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(sequence) 10% trailing, to middle", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let toMove = Array((size - k) ..< size) + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: toMove, to: size / 2) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(sequence) 50% evens, to front", + input: Int.self + ) { size in + let toMove = Array(stride(from: 0, to: size, by: 2)) + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: toMove, to: 0) + } + precondition(d.count == size) + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(sequence) 10% scattered, to middle", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let toMove = Array(stride(from: 0, to: size, by: Swift.max(size / k, 1)).prefix(k)) + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: toMove, to: size / 2) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(sequence) 1 mid, back by 5", + input: Int.self + ) { size in + guard size > 10 else { return nil } + let src = size / 2 + let dst = src - 5 + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: [src], to: dst) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(sequence) 10 contiguous, back by 5", + input: Int.self + ) { size in + guard size > 20 else { return nil } + let start = size / 2 + let toMove = Array(start ..< start + 10) + let dst = start - 5 + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: toMove, to: dst) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(sequence) 10% contiguous, to front", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let start = size / 2 + let toMove = Array(start ..< Swift.min(start + k, size)) + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: toMove, to: 0) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(sequence) 10% contiguous, back by 5", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let start = size / 2 + let end = Swift.min(start + k, size) + let toMove = Array(start ..< end) + let dst = Swift.max(start - 5, 0) + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: toMove, to: dst) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(range) 10% mid, to front", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let start = size / 2 + let src = start ..< Swift.min(start + k, size) + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.moveSubrange(src, to: 0) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(range) 10 mid, back by 5", + input: Int.self + ) { size in + guard size > 20 else { return nil } + let start = size / 2 + let src = start ..< start + 10 + let dst = start - 5 + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.moveSubrange(src, to: dst) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(sequence) 10% contiguous reversed, to front", + input: Int.self + ) { size in + let k = Swift.max(size / 10, 1) + let start = size / 2 + let end = Swift.min(start + k, size) + let toMove = Array((start ..< end).reversed()) + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: toMove, to: 0) + } + blackHole(d) + } + } + + self.add( + title: "OrderedDictionary move(sequence) 10 scattered in narrow window, local dest", + input: Int.self + ) { size in + guard size > 60 else { return nil } + let start = size / 2 + let toMove = Array(stride(from: start, to: start + 20, by: 2)) + let dst = start + 20 + return { timer in + var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, + values: size ..< 2 * size) + timer.measure { + d.move(contentsOf: toMove, to: dst) + } + blackHole(d) + } + } + } } diff --git a/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift b/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift index 19cd5a5f..7f2f2324 100644 --- a/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift +++ b/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift @@ -617,7 +617,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move([size - 1], toOffset: 0) + set.move(contentsOf: [size - 1], to: 0) } blackHole(set) } @@ -630,7 +630,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move([size - 1], toOffset: size / 2) + set.move(contentsOf: [size - 1], to: size / 2) } blackHole(set) } @@ -645,7 +645,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(toMove, toOffset: 0) + set.move(contentsOf: toMove, to: 0) } blackHole(set) } @@ -660,7 +660,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(toMove, toOffset: size / 2) + set.move(contentsOf: toMove, to: size / 2) } blackHole(set) } @@ -674,7 +674,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(toMove, toOffset: 0) + set.move(contentsOf: toMove, to: 0) } precondition(set.count == size) blackHole(set) @@ -690,7 +690,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(toMove, toOffset: size / 2) + set.move(contentsOf: toMove, to: size / 2) } blackHole(set) } @@ -706,7 +706,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move([src], toOffset: dst) + set.move(contentsOf: [src], to: dst) } blackHole(set) } @@ -723,7 +723,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(toMove, toOffset: dst) + set.move(contentsOf: toMove, to: dst) } blackHole(set) } @@ -739,7 +739,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(toMove, toOffset: 0) + set.move(contentsOf: toMove, to: 0) } blackHole(set) } @@ -757,7 +757,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(toMove, toOffset: dst) + set.move(contentsOf: toMove, to: dst) } blackHole(set) } @@ -773,7 +773,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(src, toOffset: 0) + set.moveSubrange(src, to: 0) } blackHole(set) } @@ -790,7 +790,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(src, toOffset: dst) + set.moveSubrange(src, to: dst) } blackHole(set) } @@ -807,7 +807,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(toMove, toOffset: 0) + set.move(contentsOf: toMove, to: 0) } blackHole(set) } @@ -824,7 +824,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(toMove, toOffset: dst) + set.move(contentsOf: toMove, to: dst) } blackHole(set) } diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md index 7e0845ee..33793f7b 100644 --- a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md @@ -77,6 +77,9 @@ - ``shuffle()`` - ``shuffle(using:)`` - ``partition(by:)`` +- ``moveSubrange(_:to:)`` +- ``move(contentsOf:to:)`` +- ``move(fromIndices:to:)`` ### Transforming a Dictionary diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md index a36adfef..c8a7bc35 100644 --- a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md @@ -129,8 +129,9 @@ - ``shuffle()`` - ``shuffle(using:)`` - ``partition(by:)`` -- ``move(_:toOffset:)-(Range,_)`` -- ``move(_:toOffset:)-(_,_)`` +- ``moveSubrange(_:to:)`` +- ``move(contentsOf:to:)`` +- ``move(fromIndices:to:)`` ### Creating and Applying Differences diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift new file mode 100644 index 00000000..d77703de --- /dev/null +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift @@ -0,0 +1,144 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 2026 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +// Reordering implementation. +// +// The keys are an `OrderedSet`. Its move relocates the keys (rearranging the +// element storage and patching the hash table) and calls back with the +// resolved plan; the dictionary uses that callback to apply the same +// rearrangement to the parallel `_values` buffer. + +extension OrderedDictionary { + /// Moves the key-value pairs in the given range to the given index, + /// preserving their relative order. + /// + /// var d: OrderedDictionary = [0: "a", 1: "b", 2: "c", 3: "d"] + /// d.moveSubrange(2 ..< 4, to: 0) + /// // d is now [2: "c", 3: "d", 0: "a", 1: "b"] + /// + /// - Parameters: + /// - range: The range of indices addressing the pairs to move. + /// - destination: The index at which the moved pairs should start in the + /// resulting dictionary. Must be in the range + /// `0 ... count - range.count`. + /// + /// - Complexity: O(*d* + *k*) where *d* is the distance between the source + /// and destination, and *k* is the number of pairs moved. Falls back + /// to O(`count`) for large moves. + #if compiler(>=6.3) + @inline(always) + #else + @inline(__always) + #endif + @inlinable + public mutating func moveSubrange( + _ range: some RangeExpression, + to destination: Index + ) { + _moveSubrange(range.relative(to: elements), to: destination) + } + + @inlinable + internal mutating func _moveSubrange( + _ range: Range, + to destination: Index + ) { + _keys._moveSubrange(range, to: destination) + // Apply the same rotation to the values, under the guards the keys use. + let c = range.count + if c > 0, range.lowerBound != destination { + _values.withUnsafeMutableBufferPointer { values in + values._moveSubrange( + range.lowerBound ..< range.lowerBound + c, toOffset: destination) + } + } + _checkInvariants() + } + + /// Moves the pairs with the given keys to the given index, keeping them in + /// the order the keys appear in `keys`. + /// + /// Keys in `keys` that are not present in the dictionary are ignored; only + /// the pairs whose keys are present are relocated. `keys` must not contain + /// duplicates. + /// + /// var d: OrderedDictionary = [0: "a", 1: "b", 2: "c", 3: "d"] + /// d.move(contentsOf: [3, 0], to: 1) + /// // d is now [1: "b", 3: "d", 0: "a", 2: "c"] + /// + /// - Parameters: + /// - keys: The keys of the pairs to move. Keys that are not present in + /// the dictionary are ignored. + /// - destination: The index at which the moved pairs should start in the + /// resulting dictionary. Must be in the range `0 ... count - k`, where + /// `k` is the number of `keys` that are present in the dictionary. + /// + /// - Complexity: O(`count`) in the worst case. When the pairs form a + /// contiguous range or are moved a short distance, the operation is + /// proportional to the distance moved. + @inlinable + public mutating func move( + contentsOf keys: some Sequence, + to destination: Index + ) { + _values.withUnsafeMutableBufferPointer { values in + _keys._move(contentsOf: keys, to: destination) { + sourceOffsets, sortedSources, isContiguousRange in + values._move( + sourceOffsets: sourceOffsets, + sortedSources: sortedSources, + isContiguousRange: isContiguousRange, + to: destination) + } + } + _checkInvariants() + } + + /// Moves the pairs at the given indices to the given index, keeping them in + /// the order the indices appear in `indices`. + /// + /// `indices` must contain distinct, valid indices of the dictionary. + /// + /// var d: OrderedDictionary = [0: "a", 1: "b", 2: "c", 3: "d", 4: "e"] + /// d.move(fromIndices: [4, 1], to: 0) + /// // d is now [4: "e", 1: "b", 0: "a", 2: "c", 3: "d"] + /// + /// - Parameters: + /// - indices: The indices of the pairs to move. + /// - destination: The index at which the moved pairs should start in the + /// resulting dictionary. Must be in the range `0 ... count - k`, where + /// `k` is the number of pairs being moved. + /// + /// - Complexity: O(`count`) in the worst case. When the pairs form a + /// contiguous range or are moved a short distance, the operation is + /// proportional to the distance moved. + @inlinable + public mutating func move( + fromIndices indices: [Index], + to destination: Index + ) { + _values.withUnsafeMutableBufferPointer { values in + indices.withUnsafeBufferPointer { indices in + _keys._move(fromIndices: indices, to: destination) { + sourceOffsets, sortedSources, isContiguousRange in + values._move( + sourceOffsets: sourceOffsets, + sortedSources: sortedSources, + isContiguousRange: isContiguousRange, + to: destination) + } + } + } + _checkInvariants() + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift index 9f93d153..1ff10e22 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift @@ -17,82 +17,321 @@ import InternalCollectionsUtilities // Reordering implementation. // -// Both `move` overloads relocate elements to a new offset, preserving the -// order they appear in the input. The work splits into two concerns: -// -// 1. Rearrange `_elements` so the moved values are contiguous at the -// destination, with the surrounding elements compacted around them. -// 2. Update `_table` so each element's hash bucket points at its new -// offset. -// -// The implementation dispatches to one of three buffer strategies depending -// on the input shape: -// -// * Contiguous range source -> `_moveRange`: a three-reverse rotation of -// `_elements`. O(*d* + *k*) element moves, where *d* is the distance -// between source and destination and *k* is the source count. -// -// * Contiguous range source in a different order -> `_moveContiguousReordered`: -// rotation, followed by a cycle-following in-place permutation to -// reorder the moved block. -// -// * Scattered sources -> `_moveScattered`: a two-pointer compact-and-place -// pass that removes the source positions and writes the moved values -// into the resulting gap. O(*n*) element moves. -// -// For the hash table, each strategy further chooses between targeted -// per-element bucket updates and a coarse fallback (full-table scan in -// `_moveRange`, full rebuild in `_moveScattered`). The fallback is faster -// once the affected region grows beyond roughly a third of the table; see -// the `targetedUpdateLimit` comments at each branch. +// A move rearranges `_elements` so the moved elements become consecutive at +// the destination, then repoints the affected hash-table buckets. The element +// rearrangement is factored into generic `UnsafeMutableBufferPointer` +// operations; `OrderedDictionary` reuses them through the `applyingTo` closure +// to relocate its values in lockstep with the keys. extension OrderedSet { - /// Moves the elements in the given range to the given offset, preserving + /// Moves the elements in the given range to the given index, preserving /// their relative order. /// /// var set: OrderedSet = [0, 1, 2, 3, 4, 5, 6] - /// set.move(4 ..< 6, toOffset: 1) + /// set.moveSubrange(4 ..< 6, to: 1) /// // set is now [0, 4, 5, 1, 2, 3, 6] /// /// - Parameters: - /// - range: The index range of elements to move. - /// - destination: The offset where the moved elements should start in + /// - range: The range of indices addressing the elements to move. + /// - destination: The index at which the moved elements should start in /// the resulting set. Must be in the range `0 ... count - range.count`. /// /// - Complexity: O(*d* + *k*) where *d* is the distance between the source /// and destination, and *k* is the number of elements moved. Falls back /// to O(`count`) for large moves. + #if compiler(>=6.3) + @inline(always) + #else + @inline(__always) + #endif @inlinable - public mutating func move( - _ range: Range, - toOffset destination: Int + public mutating func moveSubrange( + _ range: some RangeExpression, + to destination: Index + ) { + _moveSubrange(range.relative(to: self), to: destination) + } + + @inlinable + internal mutating func _moveSubrange( + _ range: Range, + to destination: Index ) { let c = range.count guard c > 0 else { return } _failEarlyRangeCheck(range, bounds: startIndex ..< endIndex) precondition( destination >= 0 && destination <= count - c, - "Destination offset \(destination) out of range 0 ... \(count - c)") + "Destination index \(destination) out of range 0 ... \(count - c)") guard range.lowerBound != destination else { return } - _moveRange(range.lowerBound, count: c, toOffset: destination) + _elements.withUnsafeMutableBufferPointer { buffer in + buffer._moveSubrange( + range.lowerBound ..< range.lowerBound + c, toOffset: destination) + } + _updateHashAfterContiguousMove( + src: range.lowerBound, count: c, to: destination) + _checkInvariants() + } + + /// Moves the given elements to the given index, keeping them in the + /// order they appear in `elements`. + /// + /// Elements of `elements` that are not members of the set are ignored; + /// only the members are relocated. `elements` must not contain duplicate + /// members. + /// + /// var set: OrderedSet = [0, 1, 2, 3, 4, 5, 6] + /// set.move(contentsOf: [4, 1], to: 2) + /// // set is now [0, 2, 4, 1, 3, 5, 6] + /// + /// - Parameters: + /// - elements: The elements to move. Values that are not members of the + /// set are ignored. + /// - destination: The index at which the moved elements should start in + /// the resulting set. Must be in the range `0 ... count - k`, where + /// `k` is the number of `elements` that are members of the set. + /// + /// - Complexity: O(`count`) in the worst case. When the elements form a + /// contiguous range or are moved a short distance, the operation is + /// proportional to the distance moved. + @inlinable + public mutating func move( + contentsOf elements: some Sequence, + to destination: Index + ) { + _move(contentsOf: elements, to: destination) + } + + /// Moves the elements at the given indices to the given index, keeping them + /// in the order the indices appear in `indices`. + /// + /// `indices` must contain distinct, valid indices of the set. + /// + /// var set: OrderedSet = [0, 1, 2, 3, 4] + /// set.move(fromIndices: [4, 1], to: 0) + /// // set is now [4, 1, 0, 2, 3] + /// + /// - Parameters: + /// - indices: The indices of the elements to move. + /// - destination: The index at which the moved elements should start in + /// the resulting set. Must be in the range `0 ... count - k`, where + /// `k` is the number of elements being moved. + /// + /// - Complexity: O(`count`) in the worst case. When the elements form a + /// contiguous range or are moved a short distance, the operation is + /// proportional to the distance moved. + @inlinable + public mutating func move( + fromIndices indices: [Index], + to destination: Index + ) { + indices.withUnsafeBufferPointer { indices in + _move(fromIndices: indices, to: destination) + } + } +} + +extension OrderedSet { + @inlinable + internal mutating func _move( + fromIndices sourceOffsets: UnsafeBufferPointer, + to destination: Index, + applyingTo body: ( + UnsafeBufferPointer, UnsafeBufferPointer, Bool + ) -> Void = { _, _, _ in } + ) { + var isContiguousRange = true + var isSorted = true + for i in 0 ..< sourceOffsets.count { + let index = sourceOffsets[i] + precondition( + index >= 0 && index < count, + "Index \(index) at \(i) out of bounds 0 ..< \(count)") + if i > 0 { + let prev = sourceOffsets[i - 1] + if index <= prev { + isSorted = false + isContiguousRange = false + } else if index != prev + 1 { + isContiguousRange = false + } + } + } + _move( + sourceOffsets: sourceOffsets, + isContiguousRange: isContiguousRange, + isSorted: isSorted, + to: destination, + applyingTo: body) + } + + @inlinable + internal mutating func _move( + contentsOf elements: some Sequence, + to destination: Index, + applyingTo body: ( + UnsafeBufferPointer, UnsafeBufferPointer, Bool + ) -> Void = { _, _, _ in } + ) { + // Fast path: resolve member indices into a stack buffer, no heap copy. + // Elements that aren't members of the set are skipped. + let handled: Void? = elements.withContiguousStorageIfAvailable { source in + guard source.count > 0 else { return } + withUnsafeTemporaryAllocation( + of: Int.self, capacity: source.count + ) { sourceOffsets in + var isContiguousRange = true + var isSorted = true + var c = 0 + for i in 0 ..< source.count { + guard let index = _find(source[i]).index else { continue } + if c > 0 { + let prev = sourceOffsets[c - 1] + if index <= prev { + isSorted = false + isContiguousRange = false + } else if index != prev + 1 { + isContiguousRange = false + } + } + sourceOffsets[c] = index + c += 1 + } + _move( + sourceOffsets: UnsafeBufferPointer(rebasing: sourceOffsets[..= 0 { + if index <= prev { + isSorted = false + isContiguousRange = false + } else if index != prev + 1 { + isContiguousRange = false + } + } + prev = index + sourceOffsets.append(index) + } + sourceOffsets.withUnsafeBufferPointer { sourceOffsets in + _move( + sourceOffsets: sourceOffsets, + isContiguousRange: isContiguousRange, + isSorted: isSorted, + to: destination, + applyingTo: body) + } + } + + @inlinable + internal mutating func _move( + sourceOffsets: UnsafeBufferPointer, + isContiguousRange: Bool, + isSorted: Bool, + to destination: Index, + applyingTo body: ( + UnsafeBufferPointer, UnsafeBufferPointer, Bool + ) -> Void + ) { + let c = sourceOffsets.count + guard c > 0 else { return } + precondition( + destination >= 0 && destination <= count - c, + "Destination index \(destination) out of range 0 ... \(count - c)") + + var isNoOp = true + for i in 0 ..< c { + if sourceOffsets[i] != destination + i { + isNoOp = false + break + } + } + guard !isNoOp else { return } + + if isSorted { + // Already ascending: the sorted view is the input view, no copy needed. + _applyMove( + sourceOffsets: sourceOffsets, + sortedSources: sourceOffsets, + isContiguousRange: isContiguousRange, + to: destination, + applyingTo: body) + } else { + withUnsafeTemporaryAllocation(of: Int.self, capacity: c) { sortedBuffer in + sortedBuffer.baseAddress!.initialize( + from: sourceOffsets.baseAddress!, count: c) + var sorted = sortedBuffer + sorted.sort() + for i in 1 ..< c { + precondition( + sortedBuffer[i] != sortedBuffer[i - 1], + "Duplicate element in move list") + } + _applyMove( + sourceOffsets: sourceOffsets, + sortedSources: UnsafeBufferPointer(sortedBuffer), + isContiguousRange: isContiguousRange, + to: destination, + applyingTo: body) + } + } _checkInvariants() } @inlinable - internal mutating func _moveRange( - _ src: Int, - count: Int, - toOffset destination: Int + internal mutating func _applyMove( + sourceOffsets: UnsafeBufferPointer, + sortedSources: UnsafeBufferPointer, + isContiguousRange: Bool, + to destination: Index, + applyingTo body: ( + UnsafeBufferPointer, UnsafeBufferPointer, Bool + ) -> Void ) { _elements.withUnsafeMutableBufferPointer { buffer in - buffer._moveSubrange(src ..< src + count, toOffset: destination) + buffer._move( + sourceOffsets: sourceOffsets, + sortedSources: sortedSources, + isContiguousRange: isContiguousRange, + to: destination) } + _updateHashAfterMove( + sourceOffsets: sourceOffsets, + sortedSources: sortedSources, + isContiguousRange: isContiguousRange, + to: destination) + body(sourceOffsets, sortedSources, isContiguousRange) + } +} +extension OrderedSet { + /// Repoints buckets after a contiguous block of `count` elements starting at + /// `src` was rotated to start at `destination`. `_elements` is already + /// rearranged. + @inlinable + internal mutating func _updateHashAfterContiguousMove( + src: Int, + count: Int, + to destination: Int + ) { guard _table != nil else { return } - _ensureUnique() - let distance: Int = destination < src ? src - destination : destination - src + let distance: Int = + destination < src ? src - destination : destination - src _table!.update { hashTable in // Targeted bucket updates touch O(count + distance) buckets, while a @@ -126,8 +365,7 @@ extension OrderedSet { } } } else { - var it = hashTable.bucketIterator( - startingAt: _Bucket(offset: 0)) + var it = hashTable.bucketIterator(startingAt: _Bucket(offset: 0)) repeat { if let value = it.currentValue { if value >= src && value < src + count { @@ -146,254 +384,145 @@ extension OrderedSet { } } } -} -extension OrderedSet { - /// Moves the specified elements to the given offset, keeping them in the - /// order they appear in `elements`. - /// - /// Every value in `elements` must be a member of the set, and `elements` - /// must not contain duplicates. - /// - /// var set: OrderedSet = [0, 1, 2, 3, 4, 5, 6] - /// set.move([4, 1], toOffset: 2) - /// // set is now [0, 2, 4, 1, 3, 5, 6] - /// - /// - Parameters: - /// - elements: The elements to move. - /// - destination: The offset where the moved elements should start in - /// the resulting set. Must be in the range `0 ... count - k`, where - /// `k` is the number of elements being moved. - /// - /// - Complexity: O(`count`) in the worst case. When the elements form a - /// contiguous range or are moved a short distance, the operation is - /// proportional to the distance moved. + /// Repoints buckets after the elements at `sourceOffsets` were relocated to + /// start at `destination`. `_elements` is already rearranged. @inlinable - public mutating func move( - _ elements: some Sequence, - toOffset destination: Int + internal mutating func _updateHashAfterMove( + sourceOffsets: UnsafeBufferPointer, + sortedSources: UnsafeBufferPointer, + isContiguousRange: Bool, + to destination: Int ) { - let toMove = ContiguousArray(elements) - let c = toMove.count - guard c > 0 else { return } - precondition( - destination >= 0 && destination <= count - c, - "Destination offset \(destination) out of range 0 ... \(count - c)") + let count = sourceOffsets.count + let minSource = sortedSources[0] - withUnsafeTemporaryAllocation(of: Int.self, capacity: c) { sourceOffsets in - var isContiguousRange = true - var isSorted = true - for i in 0 ..< c { - guard let index = _find(toMove[i]).index else { - preconditionFailure( - "Attempted to move an element that is not a member of the set") - } - if i > 0 { - let prev = sourceOffsets[i - 1] - if index <= prev { - isSorted = false - isContiguousRange = false - } else if index != prev + 1 { - isContiguousRange = false + if isContiguousRange { + _updateHashAfterContiguousMove( + src: minSource, count: count, to: destination) + return + } + + guard _table != nil else { return } + + let maxSource = sortedSources[count - 1] + let affectedStart: Int = Swift.min(minSource, destination) + let affectedEnd: Int = Swift.max(maxSource, destination + count - 1) + let affectedCount: Int = affectedEnd - affectedStart + 1 + + // Same heuristic as in `_updateHashAfterContiguousMove`: when the affected + // region is small relative to the table, per-bucket updates beat a + // full-table rebuild. + let targetedUpdateLimit = _capacity / 3 + + if affectedCount <= targetedUpdateLimit { + _ensureUnique() + _table!.update { hashTable in + for i in 0 ..< count { + let oldPos = sourceOffsets[i] + let newPos = destination + i + if oldPos != newPos { + var it = hashTable.bucketIterator(for: _elements[newPos]) + it.advance(until: oldPos) + it.currentValue = newPos } } - sourceOffsets[i] = index - } - var isNoOp = true - for i in 0 ..< c { - if sourceOffsets[i] != destination + i { - isNoOp = false - break - } - } - guard !isNoOp else { return } - - if isContiguousRange { - _moveRange(sourceOffsets[0], count: c, toOffset: destination) - _checkInvariants() - return - } - - _moveScattered( - sourceOffsets: sourceOffsets, - isSorted: isSorted, - count: c, - toOffset: destination) - } - } - - @inlinable - internal mutating func _moveScattered( - sourceOffsets: UnsafeMutableBufferPointer, - isSorted: Bool, - count: Int, - toOffset destination: Int - ) { - let totalCount = self.count - - withUnsafeTemporaryAllocation(of: Int.self, capacity: count) { sortedCopy in - if !isSorted { - for i in 0 ..< count { sortedCopy[i] = sourceOffsets[i] } - var mutableSortedCopy = sortedCopy - mutableSortedCopy.sort() - } - let sortedSources = isSorted ? sourceOffsets : sortedCopy - - if !isSorted { - for i in 1 ..< count { - precondition( - sortedSources[i] != sortedSources[i - 1], - "Duplicate element in move list") - } - } - - // Contiguous indices in a different order: rotate, then permute. - if sortedSources[count - 1] - sortedSources[0] == count - 1 { - _moveContiguousReordered( - sourceOffsets: sourceOffsets, - minSource: sortedSources[0], - count: count, - toOffset: destination) - return - } - - withUnsafeTemporaryAllocation( - of: Element.self, capacity: count - ) { saved in - for i in 0 ..< count { - saved.initializeElement(at: i, to: _elements[sourceOffsets[i]]) - } - defer { saved.baseAddress!.deinitialize(count: count) } - - _elements.withUnsafeMutableBufferPointer { buffer in - buffer._compactAndPlace( - removing: sortedSources, - inserting: saved, - at: destination, - totalCount: totalCount) - } - } - - guard _table != nil else { - _checkInvariants() - return - } - - _ensureUnique() - - let minSource: Int = sortedSources[0] - let maxSource: Int = sortedSources[count - 1] - let affectedStart: Int = Swift.min(minSource, destination) - let affectedEnd: Int = Swift.max(maxSource, destination + count - 1) - let affectedCount: Int = affectedEnd - affectedStart + 1 - - // Same heuristic as in `_moveRange`: when the affected region is small - // relative to the table, per-bucket updates beat a full-table rebuild. - let targetedUpdateLimit = _capacity / 3 - - if affectedCount <= targetedUpdateLimit { - _table!.update { hashTable in - for i in 0 ..< count { - let oldPos = sourceOffsets[i] - let newPos = destination + i + if affectedStart < destination { + var oldPos = affectedStart + + sortedSources._sortedCount(below: affectedStart) + var si = oldPos - affectedStart + for newPos in affectedStart ..< destination { + // Mirrors the catch-up loop after the gap; see there. + while si < count && sortedSources[si] <= oldPos { + oldPos += 1 + si += 1 + } if oldPos != newPos { var it = hashTable.bucketIterator(for: _elements[newPos]) it.advance(until: oldPos) it.currentValue = newPos } - } - - if affectedStart < destination { - var oldPos = affectedStart - + sortedSources._sortedCount(below: affectedStart) - var si = oldPos - affectedStart - for newPos in affectedStart ..< destination { - // Mirrors the catch-up loop after the gap; see there. - while si < count && sortedSources[si] <= oldPos { - oldPos += 1 - si += 1 - } - if oldPos != newPos { - var it = hashTable.bucketIterator(for: _elements[newPos]) - it.advance(until: oldPos) - it.currentValue = newPos - } - oldPos += 1 - } - } - - if destination + count <= affectedEnd { - let firstNSIndex = destination - var oldPos = firstNSIndex - + sortedSources._sortedCount(below: firstNSIndex) - var si = oldPos - firstNSIndex - for newPos in (destination + count) ... affectedEnd { - // `<=` (not `==`): the initial `oldPos` counts sources - // strictly below `firstNSIndex`, so any source in - // `[firstNSIndex, oldPos]` still needs folding in here. - while si < count && sortedSources[si] <= oldPos { - oldPos += 1 - si += 1 - } - if oldPos != newPos { - var it = hashTable.bucketIterator(for: _elements[newPos]) - it.advance(until: oldPos) - it.currentValue = newPos - } - oldPos += 1 - } + oldPos += 1 } } - } else { + + if destination + count <= affectedEnd { + let firstNSIndex = destination + var oldPos = firstNSIndex + + sortedSources._sortedCount(below: firstNSIndex) + var si = oldPos - firstNSIndex + for newPos in (destination + count) ... affectedEnd { + // `<=` (not `==`): the initial `oldPos` counts sources + // strictly below `firstNSIndex`, so any source in + // `[firstNSIndex, oldPos]` still needs folding in here. + while si < count && sortedSources[si] <= oldPos { + oldPos += 1 + si += 1 + } + if oldPos != newPos { + var it = hashTable.bucketIterator(for: _elements[newPos]) + it.advance(until: oldPos) + it.currentValue = newPos + } + oldPos += 1 + } + } + } + } else { + // Full rebuild: build fresh storage when shared, rather than copying the + // old table only to clear it. + if _isUnique() { _table!.update { hashTable in hashTable.clear() hashTable.fill(uncheckedUniqueElements: _elements) } - } - - _checkInvariants() - } - } - - @inlinable - internal mutating func _moveContiguousReordered( - sourceOffsets: UnsafeMutableBufferPointer, - minSource: Int, - count: Int, - toOffset destination: Int - ) { - _moveRange(minSource, count: count, toOffset: destination) - - withUnsafeTemporaryAllocation(of: Int.self, capacity: count) { perm in - for i in 0 ..< count { - perm[i] = sourceOffsets[i] - minSource - } - - _elements.withUnsafeMutableBufferPointer { buffer in - buffer._applyPermutation(perm, offset: destination) + } else { + _regenerateHashTable(scale: _scale, reservedScale: _reservedScale) } } - - if _table != nil { - _ensureUnique() - _table!.update { hashTable in - for i in 0 ..< count { - let oldLocalPos = sourceOffsets[i] - minSource - guard oldLocalPos != i else { continue } - var it = hashTable.bucketIterator( - for: _elements[destination + i]) - it.advance(until: destination + oldLocalPos) - it.currentValue = destination + i - } - } - } - - _checkInvariants() } } extension UnsafeMutableBufferPointer { + /// Relocates the elements at `sourceOffsets` (in that order) into consecutive + /// slots starting at `destination`, dispatching to the cheapest applicable + /// strategy. `sortedSources` lists the same offsets ascending; + /// `isContiguousRange` is true when they form a gap-free ascending run. + @inlinable + internal func _move( + sourceOffsets: UnsafeBufferPointer, + sortedSources: UnsafeBufferPointer, + isContiguousRange: Bool, + to destination: Int + ) { + let c = sourceOffsets.count + let minSource = sortedSources[0] + + if isContiguousRange { + _moveSubrange(minSource ..< minSource + c, toOffset: destination) + return + } + + if sortedSources[c - 1] - minSource == c - 1 { + // Contiguous indices in a different order: rotate, then permute. + _moveSubrange(minSource ..< minSource + c, toOffset: destination) + withUnsafeTemporaryAllocation(of: Int.self, capacity: c) { perm in + for i in 0 ..< c { + perm[i] = sourceOffsets[i] - minSource + } + _applyPermutation(perm, offset: destination) + } + return + } + + _moveScattered( + movingFrom: sourceOffsets, + sortedSources: sortedSources, + to: destination, + totalCount: count) + } + /// Moves a contiguous subrange to a new position using three-reverse /// rotation. @inlinable @@ -426,6 +555,34 @@ extension UnsafeMutableBufferPointer { } } + /// Relocates the elements at `movingFrom` (in that order) into consecutive + /// slots starting at `destination`, compacting the rest around them. + /// `sortedSources` lists the same positions ascending; `totalCount` is the + /// number of initialized elements in the buffer. + @inlinable + internal func _moveScattered( + movingFrom sourceOffsets: UnsafeBufferPointer, + sortedSources: UnsafeBufferPointer, + to destination: Int, + totalCount: Int + ) { + let count = sourceOffsets.count + withUnsafeTemporaryAllocation( + of: Element.self, capacity: count + ) { saved in + for i in 0 ..< count { + saved.initializeElement(at: i, to: self[sourceOffsets[i]]) + } + defer { saved.baseAddress!.deinitialize(count: count) } + + _compactAndPlace( + removing: sortedSources, + inserting: saved, + at: destination, + totalCount: totalCount) + } + } + /// Removes elements at the positions in `sortedRemovals` (which must be /// sorted and within bounds), compacts the remaining elements to leave a /// gap at `destination`, and fills the gap from `insertions`. @@ -433,7 +590,7 @@ extension UnsafeMutableBufferPointer { /// `totalCount` is the number of initialized elements in the buffer. @inlinable internal func _compactAndPlace( - removing sortedRemovals: UnsafeMutableBufferPointer, + removing sortedRemovals: UnsafeBufferPointer, inserting insertions: UnsafeMutableBufferPointer, at destination: Int, totalCount: Int @@ -506,7 +663,7 @@ extension UnsafeMutableBufferPointer { } } -extension UnsafeMutableBufferPointer where Element == Int { +extension UnsafeBufferPointer where Element == Int { /// Returns the number of elements strictly less than `value` in this /// sorted buffer (i.e., the lower bound index). @inlinable diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index ecf57f03..312e89c7 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -1113,6 +1113,163 @@ class OrderedDictionaryTests: CollectionTestCase { } } + func test_moveSubrange() { + withEvery("count", in: 0 ..< 12) { count in + withEvery("lower", in: 0 ..< count) { lower in + withEvery("k", in: 1 ... count - lower) { k in + withEvery("dst", in: 0 ... count - k) { dst in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) + let moved = Array(reference[lower ..< lower + k]) + reference.removeSubrange(lower ..< lower + k) + reference.insert(contentsOf: moved, at: dst) + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in + d.moveSubrange(lower ..< lower + k, to: dst) + expectEqualElements(d, reference) + for (key, value) in reference { + expectEqual(d[key], value) + } + } + } + } + } + } + } + } + } + + func test_moveSubrange_rangeExpression() { + // The RangeExpression overload must agree with the concrete range. + withEvery("count", in: 4 ..< 10) { count in + withEvery("dst", in: 0 ... 2) { dst in + var viaExpression = OrderedDictionary( + uniqueKeys: 0 ..< count, values: 100 ..< 100 + count) + var viaRange = viaExpression + viaExpression.moveSubrange(2..., to: dst) + viaRange.moveSubrange(2 ..< count, to: dst) + expectEqualElements(viaExpression, viaRange) + } + } + } + + func test_move_contentsOf() { + withEvery("count", in: 1 ..< 10) { count in + let positions = Array(stride(from: 0, to: count, by: 2)) + withEvery("dst", in: 0 ... count - positions.count) { dst in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) + let keysToMove = positions.map { reference[$0].key } + let moved = positions.map { reference[$0] } + reference.removeAll { keysToMove.contains($0.key) } + reference.insert(contentsOf: moved, at: dst) + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in + d.move(contentsOf: keysToMove, to: dst) + expectEqualElements(d, reference) + for (key, value) in reference { + expectEqual(d[key], value) + } + } + } + } + } + } + } + + func test_move_contentsOf_keepsInputOrder() { + // The moved pairs appear in the order their keys are given, not their + // original order. + withLifetimeTracking { tracker in + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< 6) + let keysToMove = [reference[4].key, reference[1].key] + let moved = [reference[4], reference[1]] + reference.removeAll { keysToMove.contains($0.key) } + reference.insert(contentsOf: moved, at: 1) + d.move(contentsOf: keysToMove, to: 1) + expectEqualElements(d, reference) + } + } + + func test_move_contentsOf_ignoresMissing() { + // Keys not present in the dictionary are skipped. + withLifetimeTracking { tracker in + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< 6) + let missing = tracker.instance(for: 99) + let k4 = reference[4].key + let k1 = reference[1].key + let moved = [reference[4], reference[1]] + reference.removeAll { $0.key == k4 || $0.key == k1 } + reference.insert(contentsOf: moved, at: 0) + d.move(contentsOf: [k4, missing, k1], to: 0) + expectEqualElements(d, reference) + for (key, value) in reference { + expectEqual(d[key], value) + } + } + } + + // Sweeps over source subsets, permutations, and destinations, verifying the + // keys' hash table stays consistent and every key still maps to its value + // after the move relocates keys and values in lockstep. + func test_move_exhaustive_hash_table_integrity() { + func check(_ d: OrderedDictionary, _ context: @autoclosure () -> String) { + let occupied = d.keys.__unstable.hashTableContents.lazy + .filter { $0 != nil }.count + expectEqual(occupied, d.count, "\(context())") + for (key, value) in d { + expectEqual(d.keys.firstIndex(of: key), d.index(forKey: key), "\(context())") + expectEqual(value, 100 + key, "\(context()): value for \(key)") + } + } + + let n = 16 + #if COLLECTIONS_LONG_TESTS + let maxK = 5 + #else + let maxK = 3 + #endif + withEverySubset("subset", of: Array(0 ..< n)) { subset in + guard !subset.isEmpty, subset.count <= maxK else { return } + withEveryPermutation("perm", of: subset) { perm in + for dst in 0 ... (n - perm.count) { + var d = OrderedDictionary(uniqueKeys: 0 ..< n, values: 100 ..< 100 + n) + d.move(contentsOf: perm, to: dst) + check(d, "perm=\(perm) dst=\(dst)") + } + } + } + } + + func test_move_fromIndices() { + withEvery("count", in: 1 ..< 8) { count in + withEvery("a", in: 0 ..< count) { a in + withEvery("b", in: 0 ..< count) { b in + guard a != b else { return } + withEvery("dst", in: 0 ... count - 2) { dst in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) + let moved = [reference[a], reference[b]] + let sorted = [a, b].sorted() + reference.remove(at: sorted[1]) + reference.remove(at: sorted[0]) + reference.insert(contentsOf: moved, at: dst) + withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in + d.move(fromIndices: [a, b], to: dst) + expectEqualElements(d, reference) + for (key, value) in reference { + expectEqual(d[key], value) + } + } + } + } + } + } + } + } + } + func test_removeAll() { withEvery("count", in: 0 ..< 30) { count in withEvery("isShared", in: [false, true]) { isShared in diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index 554d7c78..728586f1 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -1608,7 +1608,7 @@ class OrderedSetTests: CollectionTestCase { withOrderedSetLayouts(scales: [0, 5, 6]) { layout in var set = OrderedSet(layout: layout) let expected = Array(0 ..< layout.count) - set.move([] as [Int], toOffset: 0) + set.move(contentsOf: [] as [Int], to: 0) expectEqualElements(set, expected) } } @@ -1622,7 +1622,7 @@ class OrderedSetTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in var set = OrderedSet(layout: layout) withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in - set.move([source], toOffset: destination) + set.move(contentsOf: [source], to: destination) var expected = Array(0 ..< count) expected.remove(at: source) expected.insert(source, at: destination) @@ -1647,7 +1647,7 @@ class OrderedSetTests: CollectionTestCase { var set = OrderedSet(layout: layout) withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in let mid = (count - 2) / 2 - set.move([0, count - 1], toOffset: mid) + set.move(contentsOf: [0, count - 1], to: mid) var expected = Array(1 ..< count - 1) expected.insert(contentsOf: [0, count - 1], at: mid) expectEqualElements(set, expected) @@ -1664,7 +1664,7 @@ class OrderedSetTests: CollectionTestCase { var set = OrderedSet(layout: layout) withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in let reversed = Array((0 ..< count).reversed()) - set.move(reversed, toOffset: 0) + set.move(contentsOf: reversed, to: 0) expectEqualElements(set, reversed) } } @@ -1677,7 +1677,7 @@ class OrderedSetTests: CollectionTestCase { guard count >= 3 else { return } var set = OrderedSet(layout: layout) let expected = Array(0 ..< count) - set.move([1, 2], toOffset: 1) + set.move(contentsOf: [1, 2], to: 1) expectEqualElements(set, expected) } } @@ -1691,7 +1691,7 @@ class OrderedSetTests: CollectionTestCase { withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in let evens = stride(from: 0, to: count, by: 2).map { $0 } let odds = stride(from: 1, to: count, by: 2).map { $0 } - set.move(evens, toOffset: 0) + set.move(contentsOf: evens, to: 0) var expected = evens expected.append(contentsOf: odds) expectEqualElements(set, expected) @@ -1712,7 +1712,7 @@ class OrderedSetTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in var set = OrderedSet(layout: layout) withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in - set.move([3, 1], toOffset: 1) + set.move(contentsOf: [3, 1], to: 1) var expected = Array(0 ..< count) expected.remove(at: 3) expected.remove(at: 1) @@ -1732,7 +1732,7 @@ class OrderedSetTests: CollectionTestCase { guard b != a else { return } withEvery("destination", in: 0 ... count - 2) { destination in var set = OrderedSet(layout: layout) - set.move([a, b], toOffset: destination) + set.move(contentsOf: [a, b], to: destination) var expected = Array(0 ..< count) let ia = expected.firstIndex(of: a)! expected.remove(at: ia) @@ -1753,20 +1753,137 @@ class OrderedSetTests: CollectionTestCase { var set = OrderedSet(layout: layout) let expected = Array(0 ..< count) let mid = count / 2 - set.move(mid ..< mid + 2, toOffset: mid) + set.moveSubrange(mid ..< mid + 2, to: mid) expectEqualElements(set, expected) } } - func test_move_range_exhaustive_small() { - withOrderedSetLayouts(scales: [0]) { layout in + func test_moveSubrange_rangeExpression() { + // The `RangeExpression` overload must resolve its bounds against the set + // and then agree with the concrete `Range` overload. + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in let count = layout.count + guard count >= 4 else { return } + let k = count - 2 + withEvery("dst", in: 0 ... count - k) { dst in + var viaExpression = OrderedSet(layout: layout) + var viaRange = OrderedSet(layout: layout) + viaExpression.moveSubrange(2..., to: dst) + viaRange.moveSubrange(2 ..< count, to: dst) + expectEqualElements(viaExpression, viaRange) + } + + var closed = OrderedSet(layout: layout) + var halfOpen = OrderedSet(layout: layout) + closed.moveSubrange(1 ... 2, to: 0) + halfOpen.moveSubrange(1 ..< 3, to: 0) + expectEqualElements(closed, halfOpen) + } + } + + // `moveSubrange(_:to:)` addresses elements by index, while + // `move(contentsOf:to:)` addresses them by value. The two must not be + // confusable when `Element == Int`. + func test_move_index_vs_value_semantics() { + var byIndex: OrderedSet = [10, 11, 12, 13, 14] + byIndex.moveSubrange(2 ..< 4, to: 0) + // Moves the elements at offsets 2 and 3 (values 12, 13). + expectEqualElements(byIndex, [12, 13, 10, 11, 14]) + + var byValue: OrderedSet = [10, 11, 12, 13, 14] + byValue.move(contentsOf: [12, 13], to: 0) + // Moves the elements with values 12 and 13. + expectEqualElements(byValue, [12, 13, 10, 11, 14]) + } + + // Non-members in the input are ignored, exercising both the contiguous-input + // fast path and the non-contiguous-sequence fallback. + func test_move_contentsOf_ignoresMissing() { + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + guard count >= 5 else { return } + // Two members interleaved with two non-members. + let members = [count - 1, 1] + let mixed = [count - 1, count + 10, 1, count + 20] + var expected = Array(0 ..< count) + expected.removeAll { members.contains($0) } + expected.insert(contentsOf: members, at: 0) + withEvery("contiguousInput", in: [true, false]) { contiguousInput in + withEvery("isShared", in: [false, true]) { isShared in + var set = OrderedSet(layout: layout) + withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in + if contiguousInput { + set.move(contentsOf: mixed, to: 0) + } else { + set.move(contentsOf: AnySequence(mixed), to: 0) + } + expectEqualElements(set, expected) + withEvery("item", in: 0 ..< count) { item in + expectNotNil(set.firstIndex(of: item)) + } + } + } + } + } + } + + func test_move_contentsOf_allMissing_isNoOp() { + var set: OrderedSet = [0, 1, 2, 3, 4] + set.move(contentsOf: [10, 20], to: 2) + expectEqualElements(set, [0, 1, 2, 3, 4]) + } + + // Index-based move: elements are not equal to their positions here, so this + // genuinely exercises the by-index semantics (distinct from by-value). + func test_move_fromIndices() { + withEvery("count", in: 1 ..< 8) { count in + withEvery("a", in: 0 ..< count) { a in + withEvery("b", in: 0 ..< count) { b in + guard a != b else { return } + withEvery("dst", in: 0 ... count - 2) { dst in + let contents = (0 ..< count).map { $0 * 10 } + var set = OrderedSet(contents) + set.move(fromIndices: [a, b], to: dst) + var expected = contents + let moved = [expected[a], expected[b]] + let sorted = [a, b].sorted() + expected.remove(at: sorted[1]) + expected.remove(at: sorted[0]) + expected.insert(contentsOf: moved, at: dst) + expectEqualElements(set, expected) + for v in contents { + expectNotNil(set.firstIndex(of: v)) + } + } + } + } + } + } + + func test_move_fromIndices_matches_contentsOf() { + // Moving by index must agree with moving the elements at those indices. + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + guard count >= 4 else { return } + let indices = [count - 1, 0, count / 2] + let dst = 1 + guard dst <= count - indices.count else { return } + var byIndex = OrderedSet(layout: layout) + var byValue = byIndex + byIndex.move(fromIndices: indices, to: dst) + byValue.move(contentsOf: indices.map { byValue[$0] }, to: dst) + expectEqualElements(byIndex, byValue) + } + } + + func test_move_range_exhaustive_small() { + withOrderedSetLayouts(scales: [0]) { layout in let count = layout.count guard count >= 2 else { return } withEvery("src", in: 0 ..< count) { src in withEvery("k", in: 1 ... count - src) { k in withEvery("dst", in: 0 ... count - k) { dst in var set = OrderedSet(layout: layout) - set.move(src ..< src + k, toOffset: dst) + set.moveSubrange(src ..< src + k, to: dst) var expected = Array(0 ..< count) let removed = Array(expected[src ..< src + k]) expected.removeSubrange(src ..< src + k) @@ -1789,8 +1906,8 @@ class OrderedSetTests: CollectionTestCase { let dst = 1 var setA = OrderedSet(layout: layout) var setB = OrderedSet(layout: layout) - setA.move(Array(src ..< src + k), toOffset: dst) - setB.move(src ..< src + k, toOffset: dst) + setA.move(contentsOf: Array(src ..< src + k), to: dst) + setB.moveSubrange(src ..< src + k, to: dst) expectEqualElements(setA, setB) } } @@ -1806,7 +1923,7 @@ class OrderedSetTests: CollectionTestCase { let k = 3 let dst = 1 let reversed = Array((src ..< src + k).reversed()) - set.move(reversed, toOffset: dst) + set.move(contentsOf: reversed, to: dst) var expected = Array(0 ..< count) expected.removeSubrange(src ..< src + k) expected.insert(contentsOf: reversed, at: dst) @@ -1836,7 +1953,7 @@ class OrderedSetTests: CollectionTestCase { let perm = permutations[permIndex] withEvery("dst", in: 0 ... count - 3) { dst in var set = OrderedSet(layout: layout) - set.move(perm, toOffset: dst) + set.move(contentsOf: perm, to: dst) var expected = Array(0 ..< count) for e in perm.reversed() { expected.remove(at: expected.firstIndex(of: e)!) @@ -1854,7 +1971,7 @@ class OrderedSetTests: CollectionTestCase { // sortedSources = [3, 5, 10], destination = 5: affectedCount = 8, // so the targeted-update path fires. `destination` is itself a source. var set = OrderedSet(0 ..< 16) - set.move([3, 5, 10], toOffset: 5) + set.move(contentsOf: [3, 5, 10], to: 5) expectEqualElements(set, [0, 1, 2, 4, 6, 3, 5, 10, 7, 8, 9, 11, 12, 13, 14, 15]) for v in 0 ..< 16 { expectEqual(set.firstIndex(of: v), set.firstIndex(where: { $0 == v })) @@ -1891,7 +2008,7 @@ class OrderedSetTests: CollectionTestCase { withEveryPermutation("perm", of: subset) { perm in for dst in 0 ... (n - perm.count) { var set = OrderedSet(0 ..< n) - set.move(perm, toOffset: dst) + set.move(contentsOf: perm, to: dst) check(set, "perm=\(perm) dst=\(dst)") } } From 5a6af29d556c22a01faea4d0028600bd340a5b8a Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Fri, 5 Jun 2026 14:41:48 -0700 Subject: [PATCH 3/4] [OrderedCollections] Refine move APIs and simplify no-op check --- .../OrderedDictionaryBenchmarks.swift | 24 +++--- .../Benchmarks/OrderedSetBenchmarks.swift | 24 +++--- .../Extensions/OrderedDictionary.md | 4 +- .../Extensions/OrderedSet.md | 4 +- .../OrderedDictionary+Move.swift | 26 +++--- .../OrderedSet/OrderedSet+Move.swift | 86 ++++++++++++++----- .../OrderedDictionary Tests.swift | 18 ++-- .../OrderedSet/OrderedSetTests.swift | 66 +++++++------- 8 files changed, 149 insertions(+), 103 deletions(-) diff --git a/Benchmarks/Sources/Benchmarks/OrderedDictionaryBenchmarks.swift b/Benchmarks/Sources/Benchmarks/OrderedDictionaryBenchmarks.swift index bf2817b5..d0a83e12 100644 --- a/Benchmarks/Sources/Benchmarks/OrderedDictionaryBenchmarks.swift +++ b/Benchmarks/Sources/Benchmarks/OrderedDictionaryBenchmarks.swift @@ -606,7 +606,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: [size - 1], to: 0) + d.move(keys: [size - 1], to: 0) } blackHole(d) } @@ -620,7 +620,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: [size - 1], to: size / 2) + d.move(keys: [size - 1], to: size / 2) } blackHole(d) } @@ -636,7 +636,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: toMove, to: 0) + d.move(keys: toMove, to: 0) } blackHole(d) } @@ -652,7 +652,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: toMove, to: size / 2) + d.move(keys: toMove, to: size / 2) } blackHole(d) } @@ -667,7 +667,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: toMove, to: 0) + d.move(keys: toMove, to: 0) } precondition(d.count == size) blackHole(d) @@ -684,7 +684,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: toMove, to: size / 2) + d.move(keys: toMove, to: size / 2) } blackHole(d) } @@ -701,7 +701,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: [src], to: dst) + d.move(keys: [src], to: dst) } blackHole(d) } @@ -719,7 +719,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: toMove, to: dst) + d.move(keys: toMove, to: dst) } blackHole(d) } @@ -736,7 +736,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: toMove, to: 0) + d.move(keys: toMove, to: 0) } blackHole(d) } @@ -755,7 +755,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: toMove, to: dst) + d.move(keys: toMove, to: dst) } blackHole(d) } @@ -808,7 +808,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: toMove, to: 0) + d.move(keys: toMove, to: 0) } blackHole(d) } @@ -826,7 +826,7 @@ extension Benchmark { var d = OrderedDictionary(uncheckedUniqueKeys: 0 ..< size, values: size ..< 2 * size) timer.measure { - d.move(contentsOf: toMove, to: dst) + d.move(keys: toMove, to: dst) } blackHole(d) } diff --git a/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift b/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift index 7f2f2324..25e0ffe9 100644 --- a/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift +++ b/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift @@ -617,7 +617,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: [size - 1], to: 0) + set.move(members: [size - 1], to: 0) } blackHole(set) } @@ -630,7 +630,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: [size - 1], to: size / 2) + set.move(members: [size - 1], to: size / 2) } blackHole(set) } @@ -645,7 +645,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: toMove, to: 0) + set.move(members: toMove, to: 0) } blackHole(set) } @@ -660,7 +660,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: toMove, to: size / 2) + set.move(members: toMove, to: size / 2) } blackHole(set) } @@ -674,7 +674,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: toMove, to: 0) + set.move(members: toMove, to: 0) } precondition(set.count == size) blackHole(set) @@ -690,7 +690,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: toMove, to: size / 2) + set.move(members: toMove, to: size / 2) } blackHole(set) } @@ -706,7 +706,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: [src], to: dst) + set.move(members: [src], to: dst) } blackHole(set) } @@ -723,7 +723,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: toMove, to: dst) + set.move(members: toMove, to: dst) } blackHole(set) } @@ -739,7 +739,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: toMove, to: 0) + set.move(members: toMove, to: 0) } blackHole(set) } @@ -757,7 +757,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: toMove, to: dst) + set.move(members: toMove, to: dst) } blackHole(set) } @@ -807,7 +807,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: toMove, to: 0) + set.move(members: toMove, to: 0) } blackHole(set) } @@ -824,7 +824,7 @@ extension Benchmark { return { timer in var set = OrderedSet(0 ..< size) timer.measure { - set.move(contentsOf: toMove, to: dst) + set.move(members: toMove, to: dst) } blackHole(set) } diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md index 33793f7b..2e538aaf 100644 --- a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedDictionary.md @@ -78,8 +78,8 @@ - ``shuffle(using:)`` - ``partition(by:)`` - ``moveSubrange(_:to:)`` -- ``move(contentsOf:to:)`` -- ``move(fromIndices:to:)`` +- ``move(keys:to:)`` +- ``move(indices:to:)`` ### Transforming a Dictionary diff --git a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md index c8a7bc35..5381d121 100644 --- a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md @@ -130,8 +130,8 @@ - ``shuffle(using:)`` - ``partition(by:)`` - ``moveSubrange(_:to:)`` -- ``move(contentsOf:to:)`` -- ``move(fromIndices:to:)`` +- ``move(members:to:)`` +- ``move(indices:to:)`` ### Creating and Applying Differences diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift index d77703de..223845ad 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift @@ -73,7 +73,7 @@ extension OrderedDictionary { /// duplicates. /// /// var d: OrderedDictionary = [0: "a", 1: "b", 2: "c", 3: "d"] - /// d.move(contentsOf: [3, 0], to: 1) + /// d.move(keys: [3, 0], to: 1) /// // d is now [1: "b", 3: "d", 0: "a", 2: "c"] /// /// - Parameters: @@ -88,11 +88,11 @@ extension OrderedDictionary { /// proportional to the distance moved. @inlinable public mutating func move( - contentsOf keys: some Sequence, + keys: some Sequence, to destination: Index ) { _values.withUnsafeMutableBufferPointer { values in - _keys._move(contentsOf: keys, to: destination) { + _keys._move(members: keys, to: destination) { sourceOffsets, sortedSources, isContiguousRange in values._move( sourceOffsets: sourceOffsets, @@ -110,7 +110,7 @@ extension OrderedDictionary { /// `indices` must contain distinct, valid indices of the dictionary. /// /// var d: OrderedDictionary = [0: "a", 1: "b", 2: "c", 3: "d", 4: "e"] - /// d.move(fromIndices: [4, 1], to: 0) + /// d.move(indices: [4, 1], to: 0) /// // d is now [4: "e", 1: "b", 0: "a", 2: "c", 3: "d"] /// /// - Parameters: @@ -124,19 +124,17 @@ extension OrderedDictionary { /// proportional to the distance moved. @inlinable public mutating func move( - fromIndices indices: [Index], + indices: some Sequence, to destination: Index ) { _values.withUnsafeMutableBufferPointer { values in - indices.withUnsafeBufferPointer { indices in - _keys._move(fromIndices: indices, to: destination) { - sourceOffsets, sortedSources, isContiguousRange in - values._move( - sourceOffsets: sourceOffsets, - sortedSources: sortedSources, - isContiguousRange: isContiguousRange, - to: destination) - } + _keys._move(indices: indices, to: destination) { + sourceOffsets, sortedSources, isContiguousRange in + values._move( + sourceOffsets: sourceOffsets, + sortedSources: sortedSources, + isContiguousRange: isContiguousRange, + to: destination) } } _checkInvariants() diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift index 1ff10e22..1d59f8e8 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift @@ -74,32 +74,31 @@ extension OrderedSet { } /// Moves the given elements to the given index, keeping them in the - /// order they appear in `elements`. + /// order they appear in `members`. /// - /// Elements of `elements` that are not members of the set are ignored; - /// only the members are relocated. `elements` must not contain duplicate - /// members. + /// Elements that are not members of the set are ignored; only the members + /// are relocated. `members` must not contain duplicate elements. /// /// var set: OrderedSet = [0, 1, 2, 3, 4, 5, 6] - /// set.move(contentsOf: [4, 1], to: 2) + /// set.move(members: [4, 1], to: 2) /// // set is now [0, 2, 4, 1, 3, 5, 6] /// /// - Parameters: - /// - elements: The elements to move. Values that are not members of the + /// - members: The elements to move. Values that are not members of the /// set are ignored. /// - destination: The index at which the moved elements should start in /// the resulting set. Must be in the range `0 ... count - k`, where - /// `k` is the number of `elements` that are members of the set. + /// `k` is the number of `members` that are present in the set. /// /// - Complexity: O(`count`) in the worst case. When the elements form a /// contiguous range or are moved a short distance, the operation is /// proportional to the distance moved. @inlinable public mutating func move( - contentsOf elements: some Sequence, + members elements: some Sequence, to destination: Index ) { - _move(contentsOf: elements, to: destination) + _move(members: elements, to: destination) } /// Moves the elements at the given indices to the given index, keeping them @@ -108,7 +107,7 @@ extension OrderedSet { /// `indices` must contain distinct, valid indices of the set. /// /// var set: OrderedSet = [0, 1, 2, 3, 4] - /// set.move(fromIndices: [4, 1], to: 0) + /// set.move(indices: [4, 1], to: 0) /// // set is now [4, 1, 0, 2, 3] /// /// - Parameters: @@ -122,16 +121,60 @@ extension OrderedSet { /// proportional to the distance moved. @inlinable public mutating func move( - fromIndices indices: [Index], + indices: some Sequence, to destination: Index ) { - indices.withUnsafeBufferPointer { indices in - _move(fromIndices: indices, to: destination) - } + _move(indices: indices, to: destination) } } extension OrderedSet { + @inlinable + internal mutating func _move( + indices: some Sequence, + to destination: Index, + applyingTo body: ( + UnsafeBufferPointer, UnsafeBufferPointer, Bool + ) -> Void = { _, _, _ in } + ) { + // Fast path: operate directly on the sequence's storage when available. + let handled: Void? = indices.withContiguousStorageIfAvailable { buffer in + _move(fromIndices: buffer, to: destination, applyingTo: body) + } + if handled != nil { return } + + // Fallback: collect the indices into an array, checking bounds and + // detecting order as we go. + var isContiguousRange = true + var isSorted = true + var prev = -1 + var sourceOffsets: [Int] = [] + sourceOffsets.reserveCapacity(indices.underestimatedCount) + for index in indices { + precondition( + index >= 0 && index < count, + "Index \(index) at \(sourceOffsets.count) out of bounds 0 ..< \(count)") + if prev >= 0 { + if index <= prev { + isSorted = false + isContiguousRange = false + } else if index != prev + 1 { + isContiguousRange = false + } + } + prev = index + sourceOffsets.append(index) + } + sourceOffsets.withUnsafeBufferPointer { sourceOffsets in + _move( + sourceOffsets: sourceOffsets, + isContiguousRange: isContiguousRange, + isSorted: isSorted, + to: destination, + applyingTo: body) + } + } + @inlinable internal mutating func _move( fromIndices sourceOffsets: UnsafeBufferPointer, @@ -167,7 +210,7 @@ extension OrderedSet { @inlinable internal mutating func _move( - contentsOf elements: some Sequence, + members elements: some Sequence, to destination: Index, applyingTo body: ( UnsafeBufferPointer, UnsafeBufferPointer, Bool @@ -252,14 +295,11 @@ extension OrderedSet { destination >= 0 && destination <= count - c, "Destination index \(destination) out of range 0 ... \(count - c)") - var isNoOp = true - for i in 0 ..< c { - if sourceOffsets[i] != destination + i { - isNoOp = false - break - } - } - guard !isNoOp else { return } + // A no-op is exactly an in-order contiguous run already sitting at + // `destination`. `isContiguousRange` (computed while scanning the input) + // already guarantees `sourceOffsets[i] == sourceOffsets[0] + i`, so it + // only remains to check that the run starts at `destination`. + if isContiguousRange && sourceOffsets[0] == destination { return } if isSorted { // Already ascending: the sorted view is the input view, no copy needed. diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index 312e89c7..75e0696a 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -1153,7 +1153,7 @@ class OrderedDictionaryTests: CollectionTestCase { } } - func test_move_contentsOf() { + func test_move_keys() { withEvery("count", in: 1 ..< 10) { count in let positions = Array(stride(from: 0, to: count, by: 2)) withEvery("dst", in: 0 ... count - positions.count) { dst in @@ -1165,7 +1165,7 @@ class OrderedDictionaryTests: CollectionTestCase { reference.removeAll { keysToMove.contains($0.key) } reference.insert(contentsOf: moved, at: dst) withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in - d.move(contentsOf: keysToMove, to: dst) + d.move(keys: keysToMove, to: dst) expectEqualElements(d, reference) for (key, value) in reference { expectEqual(d[key], value) @@ -1177,7 +1177,7 @@ class OrderedDictionaryTests: CollectionTestCase { } } - func test_move_contentsOf_keepsInputOrder() { + func test_move_keys_keepsInputOrder() { // The moved pairs appear in the order their keys are given, not their // original order. withLifetimeTracking { tracker in @@ -1186,12 +1186,12 @@ class OrderedDictionaryTests: CollectionTestCase { let moved = [reference[4], reference[1]] reference.removeAll { keysToMove.contains($0.key) } reference.insert(contentsOf: moved, at: 1) - d.move(contentsOf: keysToMove, to: 1) + d.move(keys: keysToMove, to: 1) expectEqualElements(d, reference) } } - func test_move_contentsOf_ignoresMissing() { + func test_move_keys_ignoresMissing() { // Keys not present in the dictionary are skipped. withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< 6) @@ -1201,7 +1201,7 @@ class OrderedDictionaryTests: CollectionTestCase { let moved = [reference[4], reference[1]] reference.removeAll { $0.key == k4 || $0.key == k1 } reference.insert(contentsOf: moved, at: 0) - d.move(contentsOf: [k4, missing, k1], to: 0) + d.move(keys: [k4, missing, k1], to: 0) expectEqualElements(d, reference) for (key, value) in reference { expectEqual(d[key], value) @@ -1234,14 +1234,14 @@ class OrderedDictionaryTests: CollectionTestCase { withEveryPermutation("perm", of: subset) { perm in for dst in 0 ... (n - perm.count) { var d = OrderedDictionary(uniqueKeys: 0 ..< n, values: 100 ..< 100 + n) - d.move(contentsOf: perm, to: dst) + d.move(keys: perm, to: dst) check(d, "perm=\(perm) dst=\(dst)") } } } } - func test_move_fromIndices() { + func test_move_indices() { withEvery("count", in: 1 ..< 8) { count in withEvery("a", in: 0 ..< count) { a in withEvery("b", in: 0 ..< count) { b in @@ -1256,7 +1256,7 @@ class OrderedDictionaryTests: CollectionTestCase { reference.remove(at: sorted[0]) reference.insert(contentsOf: moved, at: dst) withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in - d.move(fromIndices: [a, b], to: dst) + d.move(indices: [a, b], to: dst) expectEqualElements(d, reference) for (key, value) in reference { expectEqual(d[key], value) diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index 728586f1..b65ad7b7 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -1608,7 +1608,7 @@ class OrderedSetTests: CollectionTestCase { withOrderedSetLayouts(scales: [0, 5, 6]) { layout in var set = OrderedSet(layout: layout) let expected = Array(0 ..< layout.count) - set.move(contentsOf: [] as [Int], to: 0) + set.move(members: [] as [Int], to: 0) expectEqualElements(set, expected) } } @@ -1622,7 +1622,7 @@ class OrderedSetTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in var set = OrderedSet(layout: layout) withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in - set.move(contentsOf: [source], to: destination) + set.move(members: [source], to: destination) var expected = Array(0 ..< count) expected.remove(at: source) expected.insert(source, at: destination) @@ -1647,7 +1647,7 @@ class OrderedSetTests: CollectionTestCase { var set = OrderedSet(layout: layout) withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in let mid = (count - 2) / 2 - set.move(contentsOf: [0, count - 1], to: mid) + set.move(members: [0, count - 1], to: mid) var expected = Array(1 ..< count - 1) expected.insert(contentsOf: [0, count - 1], at: mid) expectEqualElements(set, expected) @@ -1664,7 +1664,7 @@ class OrderedSetTests: CollectionTestCase { var set = OrderedSet(layout: layout) withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in let reversed = Array((0 ..< count).reversed()) - set.move(contentsOf: reversed, to: 0) + set.move(members: reversed, to: 0) expectEqualElements(set, reversed) } } @@ -1677,7 +1677,7 @@ class OrderedSetTests: CollectionTestCase { guard count >= 3 else { return } var set = OrderedSet(layout: layout) let expected = Array(0 ..< count) - set.move(contentsOf: [1, 2], to: 1) + set.move(members: [1, 2], to: 1) expectEqualElements(set, expected) } } @@ -1691,7 +1691,7 @@ class OrderedSetTests: CollectionTestCase { withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in let evens = stride(from: 0, to: count, by: 2).map { $0 } let odds = stride(from: 1, to: count, by: 2).map { $0 } - set.move(contentsOf: evens, to: 0) + set.move(members: evens, to: 0) var expected = evens expected.append(contentsOf: odds) expectEqualElements(set, expected) @@ -1712,7 +1712,7 @@ class OrderedSetTests: CollectionTestCase { withEvery("isShared", in: [false, true]) { isShared in var set = OrderedSet(layout: layout) withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in - set.move(contentsOf: [3, 1], to: 1) + set.move(members: [3, 1], to: 1) var expected = Array(0 ..< count) expected.remove(at: 3) expected.remove(at: 1) @@ -1732,7 +1732,7 @@ class OrderedSetTests: CollectionTestCase { guard b != a else { return } withEvery("destination", in: 0 ... count - 2) { destination in var set = OrderedSet(layout: layout) - set.move(contentsOf: [a, b], to: destination) + set.move(members: [a, b], to: destination) var expected = Array(0 ..< count) let ia = expected.firstIndex(of: a)! expected.remove(at: ia) @@ -1782,7 +1782,7 @@ class OrderedSetTests: CollectionTestCase { } // `moveSubrange(_:to:)` addresses elements by index, while - // `move(contentsOf:to:)` addresses them by value. The two must not be + // `move(members:to:)` addresses them by value. The two must not be // confusable when `Element == Int`. func test_move_index_vs_value_semantics() { var byIndex: OrderedSet = [10, 11, 12, 13, 14] @@ -1791,14 +1791,14 @@ class OrderedSetTests: CollectionTestCase { expectEqualElements(byIndex, [12, 13, 10, 11, 14]) var byValue: OrderedSet = [10, 11, 12, 13, 14] - byValue.move(contentsOf: [12, 13], to: 0) + byValue.move(members: [12, 13], to: 0) // Moves the elements with values 12 and 13. expectEqualElements(byValue, [12, 13, 10, 11, 14]) } // Non-members in the input are ignored, exercising both the contiguous-input // fast path and the non-contiguous-sequence fallback. - func test_move_contentsOf_ignoresMissing() { + func test_move_members_ignoresMissing() { withOrderedSetLayouts(scales: [0, 5, 6]) { layout in let count = layout.count guard count >= 5 else { return } @@ -1813,9 +1813,9 @@ class OrderedSetTests: CollectionTestCase { var set = OrderedSet(layout: layout) withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in if contiguousInput { - set.move(contentsOf: mixed, to: 0) + set.move(members: mixed, to: 0) } else { - set.move(contentsOf: AnySequence(mixed), to: 0) + set.move(members: AnySequence(mixed), to: 0) } expectEqualElements(set, expected) withEvery("item", in: 0 ..< count) { item in @@ -1827,32 +1827,40 @@ class OrderedSetTests: CollectionTestCase { } } - func test_move_contentsOf_allMissing_isNoOp() { + func test_move_members_allMissing_isNoOp() { var set: OrderedSet = [0, 1, 2, 3, 4] - set.move(contentsOf: [10, 20], to: 2) + set.move(members: [10, 20], to: 2) expectEqualElements(set, [0, 1, 2, 3, 4]) } // Index-based move: elements are not equal to their positions here, so this // genuinely exercises the by-index semantics (distinct from by-value). - func test_move_fromIndices() { + func test_move_indices() { withEvery("count", in: 1 ..< 8) { count in withEvery("a", in: 0 ..< count) { a in withEvery("b", in: 0 ..< count) { b in guard a != b else { return } withEvery("dst", in: 0 ... count - 2) { dst in let contents = (0 ..< count).map { $0 * 10 } - var set = OrderedSet(contents) - set.move(fromIndices: [a, b], to: dst) var expected = contents let moved = [expected[a], expected[b]] let sorted = [a, b].sorted() expected.remove(at: sorted[1]) expected.remove(at: sorted[0]) expected.insert(contentsOf: moved, at: dst) - expectEqualElements(set, expected) - for v in contents { - expectNotNil(set.firstIndex(of: v)) + // Array exercises the contiguous-storage fast path; AnySequence + // exercises the collect-into-array fallback. + withEvery("contiguous", in: [true, false]) { contiguous in + var set = OrderedSet(contents) + if contiguous { + set.move(indices: [a, b], to: dst) + } else { + set.move(indices: AnySequence([a, b]), to: dst) + } + expectEqualElements(set, expected) + for v in contents { + expectNotNil(set.firstIndex(of: v)) + } } } } @@ -1860,7 +1868,7 @@ class OrderedSetTests: CollectionTestCase { } } - func test_move_fromIndices_matches_contentsOf() { + func test_move_indices_matches_members() { // Moving by index must agree with moving the elements at those indices. withOrderedSetLayouts(scales: [0, 5, 6]) { layout in let count = layout.count @@ -1870,8 +1878,8 @@ class OrderedSetTests: CollectionTestCase { guard dst <= count - indices.count else { return } var byIndex = OrderedSet(layout: layout) var byValue = byIndex - byIndex.move(fromIndices: indices, to: dst) - byValue.move(contentsOf: indices.map { byValue[$0] }, to: dst) + byIndex.move(indices: indices, to: dst) + byValue.move(members: indices.map { byValue[$0] }, to: dst) expectEqualElements(byIndex, byValue) } } @@ -1906,7 +1914,7 @@ class OrderedSetTests: CollectionTestCase { let dst = 1 var setA = OrderedSet(layout: layout) var setB = OrderedSet(layout: layout) - setA.move(contentsOf: Array(src ..< src + k), to: dst) + setA.move(members: Array(src ..< src + k), to: dst) setB.moveSubrange(src ..< src + k, to: dst) expectEqualElements(setA, setB) } @@ -1923,7 +1931,7 @@ class OrderedSetTests: CollectionTestCase { let k = 3 let dst = 1 let reversed = Array((src ..< src + k).reversed()) - set.move(contentsOf: reversed, to: dst) + set.move(members: reversed, to: dst) var expected = Array(0 ..< count) expected.removeSubrange(src ..< src + k) expected.insert(contentsOf: reversed, at: dst) @@ -1953,7 +1961,7 @@ class OrderedSetTests: CollectionTestCase { let perm = permutations[permIndex] withEvery("dst", in: 0 ... count - 3) { dst in var set = OrderedSet(layout: layout) - set.move(contentsOf: perm, to: dst) + set.move(members: perm, to: dst) var expected = Array(0 ..< count) for e in perm.reversed() { expected.remove(at: expected.firstIndex(of: e)!) @@ -1971,7 +1979,7 @@ class OrderedSetTests: CollectionTestCase { // sortedSources = [3, 5, 10], destination = 5: affectedCount = 8, // so the targeted-update path fires. `destination` is itself a source. var set = OrderedSet(0 ..< 16) - set.move(contentsOf: [3, 5, 10], to: 5) + set.move(members: [3, 5, 10], to: 5) expectEqualElements(set, [0, 1, 2, 4, 6, 3, 5, 10, 7, 8, 9, 11, 12, 13, 14, 15]) for v in 0 ..< 16 { expectEqual(set.firstIndex(of: v), set.firstIndex(where: { $0 == v })) @@ -2008,7 +2016,7 @@ class OrderedSetTests: CollectionTestCase { withEveryPermutation("perm", of: subset) { perm in for dst in 0 ... (n - perm.count) { var set = OrderedSet(0 ..< n) - set.move(contentsOf: perm, to: dst) + set.move(members: perm, to: dst) check(set, "perm=\(perm) dst=\(dst)") } } From 72f074a23aa9d3335068b82a0d2a9de1bdf3682f Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Fri, 5 Jun 2026 16:37:46 -0700 Subject: [PATCH 4/4] [OrderedCollections] Use pre-removal destination index for move APIs --- .../OrderedDictionary+Move.swift | 64 ++++--- .../OrderedSet/OrderedSet+Move.swift | 163 +++++++++++++----- .../OrderedDictionary Tests.swift | 23 +-- .../OrderedSet/OrderedSetTests.swift | 115 ++++++++---- 4 files changed, 251 insertions(+), 114 deletions(-) diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift index 223845ad..a61f0dea 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift @@ -19,8 +19,13 @@ // rearrangement to the parallel `_values` buffer. extension OrderedDictionary { - /// Moves the key-value pairs in the given range to the given index, - /// preserving their relative order. + /// Moves the key-value pairs in the given range so they land just before the + /// pair at the given index, preserving their relative order. + /// + /// `destination` is interpreted in the dictionary's original index space + /// (before the moved pairs are removed): the moved pairs are inserted just + /// before the pair currently at `destination`. Pass `endIndex` to move them + /// to the end. This matches the standard library's `moveSubranges(_:to:)`. /// /// var d: OrderedDictionary = [0: "a", 1: "b", 2: "c", 3: "d"] /// d.moveSubrange(2 ..< 4, to: 0) @@ -28,9 +33,8 @@ extension OrderedDictionary { /// /// - Parameters: /// - range: The range of indices addressing the pairs to move. - /// - destination: The index at which the moved pairs should start in the - /// resulting dictionary. Must be in the range - /// `0 ... count - range.count`. + /// - destination: The index before which to insert the moved pairs, in the + /// original index space. Must be in the range `0 ... count`. /// /// - Complexity: O(*d* + *k*) where *d* is the distance between the source /// and destination, and *k* is the number of pairs moved. Falls back @@ -45,9 +49,18 @@ extension OrderedDictionary { _ range: some RangeExpression, to destination: Index ) { - _moveSubrange(range.relative(to: elements), to: destination) + let range = range.relative(to: elements) + precondition( + destination >= 0 && destination <= count, + "Destination index \(destination) out of range 0 ... \(count)") + // Convert the pre-removal insertion point to the moved block's final start + // index by discounting the moved pairs that sit before it. + let target = destination + - Swift.max(0, Swift.min(range.count, destination - range.lowerBound)) + _moveSubrange(range, to: target) } + /// - Parameter destination: The moved block's final start index (post-removal). @inlinable internal mutating func _moveSubrange( _ range: Range, @@ -65,8 +78,13 @@ extension OrderedDictionary { _checkInvariants() } - /// Moves the pairs with the given keys to the given index, keeping them in - /// the order the keys appear in `keys`. + /// Moves the pairs with the given keys so they land just before the pair at + /// the given index, keeping them in the order the keys appear in `keys`. + /// + /// `destination` is interpreted in the dictionary's original index space + /// (before the moved pairs are removed): the moved pairs are inserted just + /// before the pair currently at `destination`. Pass `endIndex` to move them + /// to the end. /// /// Keys in `keys` that are not present in the dictionary are ignored; only /// the pairs whose keys are present are relocated. `keys` must not contain @@ -74,14 +92,13 @@ extension OrderedDictionary { /// /// var d: OrderedDictionary = [0: "a", 1: "b", 2: "c", 3: "d"] /// d.move(keys: [3, 0], to: 1) - /// // d is now [1: "b", 3: "d", 0: "a", 2: "c"] + /// // d is now [3: "d", 0: "a", 1: "b", 2: "c"] /// /// - Parameters: /// - keys: The keys of the pairs to move. Keys that are not present in /// the dictionary are ignored. - /// - destination: The index at which the moved pairs should start in the - /// resulting dictionary. Must be in the range `0 ... count - k`, where - /// `k` is the number of `keys` that are present in the dictionary. + /// - destination: The index before which to insert the moved pairs, in the + /// original index space. Must be in the range `0 ... count`. /// /// - Complexity: O(`count`) in the worst case. When the pairs form a /// contiguous range or are moved a short distance, the operation is @@ -93,19 +110,25 @@ extension OrderedDictionary { ) { _values.withUnsafeMutableBufferPointer { values in _keys._move(members: keys, to: destination) { - sourceOffsets, sortedSources, isContiguousRange in + sourceOffsets, sortedSources, isContiguousRange, target in values._move( sourceOffsets: sourceOffsets, sortedSources: sortedSources, isContiguousRange: isContiguousRange, - to: destination) + to: target) } } _checkInvariants() } - /// Moves the pairs at the given indices to the given index, keeping them in - /// the order the indices appear in `indices`. + /// Moves the pairs at the given indices so they land just before the pair at + /// the given index, keeping them in the order the indices appear in + /// `indices`. + /// + /// `destination` is interpreted in the dictionary's original index space + /// (before the moved pairs are removed): the moved pairs are inserted just + /// before the pair currently at `destination`. Pass `endIndex` to move them + /// to the end. /// /// `indices` must contain distinct, valid indices of the dictionary. /// @@ -115,9 +138,8 @@ extension OrderedDictionary { /// /// - Parameters: /// - indices: The indices of the pairs to move. - /// - destination: The index at which the moved pairs should start in the - /// resulting dictionary. Must be in the range `0 ... count - k`, where - /// `k` is the number of pairs being moved. + /// - destination: The index before which to insert the moved pairs, in the + /// original index space. Must be in the range `0 ... count`. /// /// - Complexity: O(`count`) in the worst case. When the pairs form a /// contiguous range or are moved a short distance, the operation is @@ -129,12 +151,12 @@ extension OrderedDictionary { ) { _values.withUnsafeMutableBufferPointer { values in _keys._move(indices: indices, to: destination) { - sourceOffsets, sortedSources, isContiguousRange in + sourceOffsets, sortedSources, isContiguousRange, target in values._move( sourceOffsets: sourceOffsets, sortedSources: sortedSources, isContiguousRange: isContiguousRange, - to: destination) + to: target) } } _checkInvariants() diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift index 1d59f8e8..78678c0a 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift @@ -24,8 +24,14 @@ import InternalCollectionsUtilities // to relocate its values in lockstep with the keys. extension OrderedSet { - /// Moves the elements in the given range to the given index, preserving - /// their relative order. + /// Moves the elements in the given range so they land just before the + /// element at the given index, preserving their relative order. + /// + /// `destination` is interpreted in the set's original index space (before the + /// moved elements are removed), matching the standard library's + /// `moveSubranges(_:to:)` and `MutableCollection.move(fromOffsets:toOffset:)`: + /// the moved elements are inserted just before the element currently at + /// `destination`. Pass `endIndex` to move them to the end. /// /// var set: OrderedSet = [0, 1, 2, 3, 4, 5, 6] /// set.moveSubrange(4 ..< 6, to: 1) @@ -33,8 +39,8 @@ extension OrderedSet { /// /// - Parameters: /// - range: The range of indices addressing the elements to move. - /// - destination: The index at which the moved elements should start in - /// the resulting set. Must be in the range `0 ... count - range.count`. + /// - destination: The index before which to insert the moved elements, in + /// the original index space. Must be in the range `0 ... count`. /// /// - Complexity: O(*d* + *k*) where *d* is the distance between the source /// and destination, and *k* is the number of elements moved. Falls back @@ -49,9 +55,18 @@ extension OrderedSet { _ range: some RangeExpression, to destination: Index ) { - _moveSubrange(range.relative(to: self), to: destination) + let range = range.relative(to: self) + precondition( + destination >= 0 && destination <= count, + "Destination index \(destination) out of range 0 ... \(count)") + // Convert the pre-removal insertion point to the moved block's final start + // index by discounting the moved elements that sit before it. + let target = destination + - Swift.max(0, Swift.min(range.count, destination - range.lowerBound)) + _moveSubrange(range, to: target) } + /// - Parameter destination: The moved block's final start index (post-removal). @inlinable internal mutating func _moveSubrange( _ range: Range, @@ -73,22 +88,27 @@ extension OrderedSet { _checkInvariants() } - /// Moves the given elements to the given index, keeping them in the - /// order they appear in `members`. + /// Moves the given elements so they land just before the element at the given + /// index, keeping them in the order they appear in `members`. + /// + /// `destination` is interpreted in the set's original index space (before the + /// moved elements are removed): the moved elements are inserted just before + /// the element currently at `destination`. Pass `endIndex` to move them to + /// the end. This matches the standard library's + /// `MutableCollection.move(fromOffsets:toOffset:)`. /// /// Elements that are not members of the set are ignored; only the members /// are relocated. `members` must not contain duplicate elements. /// /// var set: OrderedSet = [0, 1, 2, 3, 4, 5, 6] /// set.move(members: [4, 1], to: 2) - /// // set is now [0, 2, 4, 1, 3, 5, 6] + /// // set is now [0, 4, 1, 2, 3, 5, 6] /// /// - Parameters: /// - members: The elements to move. Values that are not members of the /// set are ignored. - /// - destination: The index at which the moved elements should start in - /// the resulting set. Must be in the range `0 ... count - k`, where - /// `k` is the number of `members` that are present in the set. + /// - destination: The index before which to insert the moved elements, in + /// the original index space. Must be in the range `0 ... count`. /// /// - Complexity: O(`count`) in the worst case. When the elements form a /// contiguous range or are moved a short distance, the operation is @@ -101,8 +121,14 @@ extension OrderedSet { _move(members: elements, to: destination) } - /// Moves the elements at the given indices to the given index, keeping them - /// in the order the indices appear in `indices`. + /// Moves the elements at the given indices so they land just before the + /// element at the given index, keeping them in the order the indices appear + /// in `indices`. + /// + /// `destination` is interpreted in the set's original index space (before the + /// moved elements are removed): the moved elements are inserted just before + /// the element currently at `destination`. Pass `endIndex` to move them to + /// the end. /// /// `indices` must contain distinct, valid indices of the set. /// @@ -112,9 +138,8 @@ extension OrderedSet { /// /// - Parameters: /// - indices: The indices of the elements to move. - /// - destination: The index at which the moved elements should start in - /// the resulting set. Must be in the range `0 ... count - k`, where - /// `k` is the number of elements being moved. + /// - destination: The index before which to insert the moved elements, in + /// the original index space. Must be in the range `0 ... count`. /// /// - Complexity: O(`count`) in the worst case. When the elements form a /// contiguous range or are moved a short distance, the operation is @@ -129,24 +154,33 @@ extension OrderedSet { } extension OrderedSet { + /// Moves the elements at the given indices so they land just before the + /// element at `destination`. + /// + /// - Parameter destination: A pre-removal insertion point in `0 ... count`; + /// the moved elements land just before the element at this offset. @inlinable internal mutating func _move( indices: some Sequence, to destination: Index, applyingTo body: ( - UnsafeBufferPointer, UnsafeBufferPointer, Bool - ) -> Void = { _, _, _ in } + UnsafeBufferPointer, UnsafeBufferPointer, Bool, Int + ) -> Void = { _, _, _, _ in } ) { + precondition( + destination >= 0 && destination <= count, + "Destination index \(destination) out of range 0 ... \(count)") // Fast path: operate directly on the sequence's storage when available. let handled: Void? = indices.withContiguousStorageIfAvailable { buffer in _move(fromIndices: buffer, to: destination, applyingTo: body) } if handled != nil { return } - // Fallback: collect the indices into an array, checking bounds and - // detecting order as we go. + // Fallback: collect the indices into an array, checking bounds, detecting + // order, and counting how many sit before `destination` as we go. var isContiguousRange = true var isSorted = true + var below = 0 var prev = -1 var sourceOffsets: [Int] = [] sourceOffsets.reserveCapacity(indices.underestimatedCount) @@ -162,29 +196,42 @@ extension OrderedSet { isContiguousRange = false } } + if index < destination { below += 1 } prev = index sourceOffsets.append(index) } + // `destination` is a pre-removal insertion point; subtracting the moved + // elements before it gives the block's final start index. + let target = destination - below sourceOffsets.withUnsafeBufferPointer { sourceOffsets in _move( sourceOffsets: sourceOffsets, isContiguousRange: isContiguousRange, isSorted: isSorted, - to: destination, + to: target, applyingTo: body) } } + /// Moves the elements at the given offsets so they land just before the + /// element at `destination`. + /// + /// - Parameter destination: A pre-removal insertion point in `0 ... count`; + /// the moved elements land just before the element at this offset. @inlinable internal mutating func _move( fromIndices sourceOffsets: UnsafeBufferPointer, to destination: Index, applyingTo body: ( - UnsafeBufferPointer, UnsafeBufferPointer, Bool - ) -> Void = { _, _, _ in } + UnsafeBufferPointer, UnsafeBufferPointer, Bool, Int + ) -> Void = { _, _, _, _ in } ) { + precondition( + destination >= 0 && destination <= count, + "Destination index \(destination) out of range 0 ... \(count)") var isContiguousRange = true var isSorted = true + var below = 0 for i in 0 ..< sourceOffsets.count { let index = sourceOffsets[i] precondition( @@ -199,23 +246,33 @@ extension OrderedSet { isContiguousRange = false } } + if index < destination { below += 1 } } + let target = destination - below _move( sourceOffsets: sourceOffsets, isContiguousRange: isContiguousRange, isSorted: isSorted, - to: destination, + to: target, applyingTo: body) } + /// Moves the given elements so they land just before the element at + /// `destination`, skipping any that aren't members. + /// + /// - Parameter destination: A pre-removal insertion point in `0 ... count`; + /// the moved elements land just before the element at this offset. @inlinable internal mutating func _move( members elements: some Sequence, to destination: Index, applyingTo body: ( - UnsafeBufferPointer, UnsafeBufferPointer, Bool - ) -> Void = { _, _, _ in } + UnsafeBufferPointer, UnsafeBufferPointer, Bool, Int + ) -> Void = { _, _, _, _ in } ) { + precondition( + destination >= 0 && destination <= count, + "Destination index \(destination) out of range 0 ... \(count)") // Fast path: resolve member indices into a stack buffer, no heap copy. // Elements that aren't members of the set are skipped. let handled: Void? = elements.withContiguousStorageIfAvailable { source in @@ -225,6 +282,7 @@ extension OrderedSet { ) { sourceOffsets in var isContiguousRange = true var isSorted = true + var below = 0 var c = 0 for i in 0 ..< source.count { guard let index = _find(source[i]).index else { continue } @@ -237,6 +295,7 @@ extension OrderedSet { isContiguousRange = false } } + if index < destination { below += 1 } sourceOffsets[c] = index c += 1 } @@ -244,7 +303,7 @@ extension OrderedSet { sourceOffsets: UnsafeBufferPointer(rebasing: sourceOffsets[.., isContiguousRange: Bool, isSorted: Bool, - to destination: Index, + to target: Index, applyingTo body: ( - UnsafeBufferPointer, UnsafeBufferPointer, Bool + UnsafeBufferPointer, UnsafeBufferPointer, Bool, Int ) -> Void ) { let c = sourceOffsets.count guard c > 0 else { return } - precondition( - destination >= 0 && destination <= count - c, - "Destination index \(destination) out of range 0 ... \(count - c)") // A no-op is exactly an in-order contiguous run already sitting at - // `destination`. `isContiguousRange` (computed while scanning the input) + // `target`. `isContiguousRange` (computed while scanning the input) // already guarantees `sourceOffsets[i] == sourceOffsets[0] + i`, so it - // only remains to check that the run starts at `destination`. - if isContiguousRange && sourceOffsets[0] == destination { return } + // only remains to check that the run starts at `target`. + if isContiguousRange && sourceOffsets[0] == target { return } if isSorted { // Already ascending: the sorted view is the input view, no copy needed. @@ -307,7 +373,7 @@ extension OrderedSet { sourceOffsets: sourceOffsets, sortedSources: sourceOffsets, isContiguousRange: isContiguousRange, - to: destination, + to: target, applyingTo: body) } else { withUnsafeTemporaryAllocation(of: Int.self, capacity: c) { sortedBuffer in @@ -324,13 +390,17 @@ extension OrderedSet { sourceOffsets: sourceOffsets, sortedSources: UnsafeBufferPointer(sortedBuffer), isContiguousRange: isContiguousRange, - to: destination, + to: target, applyingTo: body) } } _checkInvariants() } + /// Rearranges `_elements` and repoints the hash table for an already-resolved + /// move, then invokes `body` so callers can mirror the rearrangement. + /// + /// - Parameter destination: The moved block's final start index (post-removal). @inlinable internal mutating func _applyMove( sourceOffsets: UnsafeBufferPointer, @@ -338,7 +408,7 @@ extension OrderedSet { isContiguousRange: Bool, to destination: Index, applyingTo body: ( - UnsafeBufferPointer, UnsafeBufferPointer, Bool + UnsafeBufferPointer, UnsafeBufferPointer, Bool, Int ) -> Void ) { _elements.withUnsafeMutableBufferPointer { buffer in @@ -353,14 +423,14 @@ extension OrderedSet { sortedSources: sortedSources, isContiguousRange: isContiguousRange, to: destination) - body(sourceOffsets, sortedSources, isContiguousRange) + body(sourceOffsets, sortedSources, isContiguousRange, destination) } } extension OrderedSet { /// Repoints buckets after a contiguous block of `count` elements starting at /// `src` was rotated to start at `destination`. `_elements` is already - /// rearranged. + /// rearranged. `destination` is the block's final start index (post-removal). @inlinable internal mutating func _updateHashAfterContiguousMove( src: Int, @@ -426,7 +496,8 @@ extension OrderedSet { } /// Repoints buckets after the elements at `sourceOffsets` were relocated to - /// start at `destination`. `_elements` is already rearranged. + /// start at `destination`. `_elements` is already rearranged. `destination` + /// is the block's final start index (post-removal). @inlinable internal mutating func _updateHashAfterMove( sourceOffsets: UnsafeBufferPointer, @@ -529,6 +600,7 @@ extension UnsafeMutableBufferPointer { /// slots starting at `destination`, dispatching to the cheapest applicable /// strategy. `sortedSources` lists the same offsets ascending; /// `isContiguousRange` is true when they form a gap-free ascending run. + /// `destination` is the block's final start index (post-removal). @inlinable internal func _move( sourceOffsets: UnsafeBufferPointer, @@ -565,6 +637,8 @@ extension UnsafeMutableBufferPointer { /// Moves a contiguous subrange to a new position using three-reverse /// rotation. + /// + /// - Parameter destination: The subrange's final start index (post-removal). @inlinable internal func _moveSubrange( _ source: Range, @@ -598,7 +672,8 @@ extension UnsafeMutableBufferPointer { /// Relocates the elements at `movingFrom` (in that order) into consecutive /// slots starting at `destination`, compacting the rest around them. /// `sortedSources` lists the same positions ascending; `totalCount` is the - /// number of initialized elements in the buffer. + /// number of initialized elements in the buffer. `destination` is the block's + /// final start index (post-removal). @inlinable internal func _moveScattered( movingFrom sourceOffsets: UnsafeBufferPointer, @@ -628,6 +703,8 @@ extension UnsafeMutableBufferPointer { /// gap at `destination`, and fills the gap from `insertions`. /// /// `totalCount` is the number of initialized elements in the buffer. + /// + /// - Parameter destination: The gap's final start index (post-removal). @inlinable internal func _compactAndPlace( removing sortedRemovals: UnsafeBufferPointer, diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index 75e0696a..4e10fa83 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -1117,13 +1117,12 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("count", in: 0 ..< 12) { count in withEvery("lower", in: 0 ..< count) { lower in withEvery("k", in: 1 ... count - lower) { k in - withEvery("dst", in: 0 ... count - k) { dst in + withEvery("dst", in: 0 ... count) { dst in withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - let moved = Array(reference[lower ..< lower + k]) - reference.removeSubrange(lower ..< lower + k) - reference.insert(contentsOf: moved, at: dst) + reference = referenceMove( + reference, positions: Array(lower ..< lower + k), to: dst) withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.moveSubrange(lower ..< lower + k, to: dst) expectEqualElements(d, reference) @@ -1156,14 +1155,12 @@ class OrderedDictionaryTests: CollectionTestCase { func test_move_keys() { withEvery("count", in: 1 ..< 10) { count in let positions = Array(stride(from: 0, to: count, by: 2)) - withEvery("dst", in: 0 ... count - positions.count) { dst in + withEvery("dst", in: 0 ... count) { dst in withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) let keysToMove = positions.map { reference[$0].key } - let moved = positions.map { reference[$0] } - reference.removeAll { keysToMove.contains($0.key) } - reference.insert(contentsOf: moved, at: dst) + reference = referenceMove(reference, positions: positions, to: dst) withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.move(keys: keysToMove, to: dst) expectEqualElements(d, reference) @@ -1232,7 +1229,7 @@ class OrderedDictionaryTests: CollectionTestCase { withEverySubset("subset", of: Array(0 ..< n)) { subset in guard !subset.isEmpty, subset.count <= maxK else { return } withEveryPermutation("perm", of: subset) { perm in - for dst in 0 ... (n - perm.count) { + for dst in 0 ... n { var d = OrderedDictionary(uniqueKeys: 0 ..< n, values: 100 ..< 100 + n) d.move(keys: perm, to: dst) check(d, "perm=\(perm) dst=\(dst)") @@ -1246,15 +1243,11 @@ class OrderedDictionaryTests: CollectionTestCase { withEvery("a", in: 0 ..< count) { a in withEvery("b", in: 0 ..< count) { b in guard a != b else { return } - withEvery("dst", in: 0 ... count - 2) { dst in + withEvery("dst", in: 0 ... count) { dst in withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) - let moved = [reference[a], reference[b]] - let sorted = [a, b].sorted() - reference.remove(at: sorted[1]) - reference.remove(at: sorted[0]) - reference.insert(contentsOf: moved, at: dst) + reference = referenceMove(reference, positions: [a, b], to: dst) withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d in d.move(indices: [a, b], to: dst) expectEqualElements(d, reference) diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift index b65ad7b7..c6811714 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSetTests.swift @@ -22,6 +22,24 @@ import InternalCollectionsUtilities extension OrderedSet: SetAPIExtras {} +/// Reference implementation of the move APIs' pre-removal destination +/// semantics: relocate the elements at `positions` (in the given order) so they +/// land just before the element originally at `destination` (`count` == end). +/// Non-moved elements keep their relative order, those originally before +/// `destination` staying before the moved block and the rest after it. +func referenceMove( + _ contents: [Element], positions: [Int], to destination: Int +) -> [Element] { + let moved = Set(positions) + var before: [Element] = [] + var after: [Element] = [] + for i in contents.indices where !moved.contains(i) { + if i < destination { before.append(contents[i]) } + else { after.append(contents[i]) } + } + return before + positions.map { contents[$0] } + after +} + class OrderedSetTests: CollectionTestCase { func test_init_uncheckedUniqueElements_concrete() { withEvery("count", in: 0 ..< 20) { count in @@ -1618,14 +1636,13 @@ class OrderedSetTests: CollectionTestCase { let count = layout.count guard count >= 1 else { return } withEvery("source", in: 0 ..< count) { source in - withEvery("destination", in: 0 ..< count) { destination in + withEvery("destination", in: 0 ... count) { destination in withEvery("isShared", in: [false, true]) { isShared in var set = OrderedSet(layout: layout) withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in set.move(members: [source], to: destination) - var expected = Array(0 ..< count) - expected.remove(at: source) - expected.insert(source, at: destination) + let expected = referenceMove( + Array(0 ..< count), positions: [source], to: destination) expectEqualElements(set, expected) withEvery("item", in: 0 ..< count) { item in expectNotNil(set.firstIndex(of: item)) @@ -1648,8 +1665,8 @@ class OrderedSetTests: CollectionTestCase { withHiddenCopies(if: isShared, of: &set, checker: { $0._checkInvariants() }) { set in let mid = (count - 2) / 2 set.move(members: [0, count - 1], to: mid) - var expected = Array(1 ..< count - 1) - expected.insert(contentsOf: [0, count - 1], at: mid) + let expected = referenceMove( + Array(0 ..< count), positions: [0, count - 1], to: mid) expectEqualElements(set, expected) } } @@ -1730,15 +1747,11 @@ class OrderedSetTests: CollectionTestCase { withEvery("a", in: 0 ..< count) { a in withEvery("b", in: 0 ..< count) { b in guard b != a else { return } - withEvery("destination", in: 0 ... count - 2) { destination in + withEvery("destination", in: 0 ... count) { destination in var set = OrderedSet(layout: layout) set.move(members: [a, b], to: destination) - var expected = Array(0 ..< count) - let ia = expected.firstIndex(of: a)! - expected.remove(at: ia) - let ib = expected.firstIndex(of: b)! - expected.remove(at: ib) - expected.insert(contentsOf: [a, b], at: destination) + let expected = referenceMove( + Array(0 ..< count), positions: [a, b], to: destination) expectEqualElements(set, expected) } } @@ -1840,14 +1853,9 @@ class OrderedSetTests: CollectionTestCase { withEvery("a", in: 0 ..< count) { a in withEvery("b", in: 0 ..< count) { b in guard a != b else { return } - withEvery("dst", in: 0 ... count - 2) { dst in + withEvery("dst", in: 0 ... count) { dst in let contents = (0 ..< count).map { $0 * 10 } - var expected = contents - let moved = [expected[a], expected[b]] - let sorted = [a, b].sorted() - expected.remove(at: sorted[1]) - expected.remove(at: sorted[0]) - expected.insert(contentsOf: moved, at: dst) + let expected = referenceMove(contents, positions: [a, b], to: dst) // Array exercises the contiguous-storage fast path; AnySequence // exercises the collect-into-array fallback. withEvery("contiguous", in: [true, false]) { contiguous in @@ -1889,13 +1897,11 @@ class OrderedSetTests: CollectionTestCase { guard count >= 2 else { return } withEvery("src", in: 0 ..< count) { src in withEvery("k", in: 1 ... count - src) { k in - withEvery("dst", in: 0 ... count - k) { dst in + withEvery("dst", in: 0 ... count) { dst in var set = OrderedSet(layout: layout) set.moveSubrange(src ..< src + k, to: dst) - var expected = Array(0 ..< count) - let removed = Array(expected[src ..< src + k]) - expected.removeSubrange(src ..< src + k) - expected.insert(contentsOf: removed, at: dst) + let expected = referenceMove( + Array(0 ..< count), positions: Array(src ..< src + k), to: dst) expectEqualElements(set, expected) } } @@ -1959,14 +1965,10 @@ class OrderedSetTests: CollectionTestCase { ] withEvery("permIndex", in: permutations.indices) { permIndex in let perm = permutations[permIndex] - withEvery("dst", in: 0 ... count - 3) { dst in + withEvery("dst", in: 0 ... count) { dst in var set = OrderedSet(layout: layout) set.move(members: perm, to: dst) - var expected = Array(0 ..< count) - for e in perm.reversed() { - expected.remove(at: expected.firstIndex(of: e)!) - } - expected.insert(contentsOf: perm, at: dst) + let expected = referenceMove(Array(0 ..< count), positions: perm, to: dst) expectEqualElements(set, expected) } } @@ -1974,13 +1976,56 @@ class OrderedSetTests: CollectionTestCase { } } + // The destination is allowed to coincide with a moved element (a "move into + // the middle of the selection"). The moved block then lands just after the + // nearest element that isn't moved, matching the standard library's + // `moveSubranges(_:to:)`. This mirrors the stdlib's own `to: 14` test case + // (`Array(1...20)`, moving `[10..<15, 18..<20]`). + func test_move_destination_inside_selection_matchesStdlib() { + var set = OrderedSet(1 ... 20) + // Elements at offsets 10...14 and 18...19 are values 11...15 and 19...20. + set.move(members: [11, 12, 13, 14, 15, 19, 20], to: 14) + expectEqualElements( + set, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 19, 20, 16, 17, 18]) + + // A contiguous run whose destination falls inside the run is a no-op. + var run: OrderedSet = [0, 1, 2, 3, 4] + run.move(indices: [1, 2, 3], to: 2) + expectEqualElements(run, [0, 1, 2, 3, 4]) + run.moveSubrange(1 ..< 4, to: 3) + expectEqualElements(run, [0, 1, 2, 3, 4]) + } + + // An empty selection is a no-op regardless of destination, for every overload. + func test_move_empty_selection_isNoOp() { + withOrderedSetLayouts(scales: [0, 5, 6]) { layout in + let count = layout.count + let expected = Array(0 ..< count) + withEvery("dst", in: 0 ... count) { dst in + var byMembers = OrderedSet(layout: layout) + byMembers.move(members: [] as [Int], to: dst) + expectEqualElements(byMembers, expected) + + var byIndices = OrderedSet(layout: layout) + byIndices.move(indices: [] as [Int], to: dst) + expectEqualElements(byIndices, expected) + + var byRange = OrderedSet(layout: layout) + byRange.moveSubrange(dst ..< dst, to: dst) + expectEqualElements(byRange, expected) + } + } + } + func test_move_scattered_destination_is_source_hash_table_size() { // count = 16, scale 5 -> capacity 24, targetedUpdateLimit = 8. - // sortedSources = [3, 5, 10], destination = 5: affectedCount = 8, - // so the targeted-update path fires. `destination` is itself a source. + // Sources [3, 5, 10] to pre-removal offset 5 (itself a source) resolve to a + // final start of 4 (one source, 3, sits before the insertion point); + // affectedCount = 8, so the targeted-update path fires. var set = OrderedSet(0 ..< 16) set.move(members: [3, 5, 10], to: 5) - expectEqualElements(set, [0, 1, 2, 4, 6, 3, 5, 10, 7, 8, 9, 11, 12, 13, 14, 15]) + expectEqualElements(set, [0, 1, 2, 4, 3, 5, 10, 6, 7, 8, 9, 11, 12, 13, 14, 15]) for v in 0 ..< 16 { expectEqual(set.firstIndex(of: v), set.firstIndex(where: { $0 == v })) } @@ -2014,7 +2059,7 @@ class OrderedSetTests: CollectionTestCase { withEverySubset("subset", of: Array(0 ..< n)) { subset in guard !subset.isEmpty, subset.count <= maxK else { return } withEveryPermutation("perm", of: subset) { perm in - for dst in 0 ... (n - perm.count) { + for dst in 0 ... n { var set = OrderedSet(0 ..< n) set.move(members: perm, to: dst) check(set, "perm=\(perm) dst=\(dst)")