From 508f36f48d23a429a9cb01f571edc8bd1601b43e Mon Sep 17 00:00:00 2001 From: David Nadoba Date: Mon, 25 May 2026 22:49:14 -0700 Subject: [PATCH] [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)") + } + } + } + } }