diff --git a/Benchmarks/Sources/Benchmarks/OrderedDictionaryBenchmarks.swift b/Benchmarks/Sources/Benchmarks/OrderedDictionaryBenchmarks.swift index 340ee001..d0a83e12 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(keys: [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(keys: [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(keys: 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(keys: 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(keys: 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(keys: 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(keys: [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(keys: 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(keys: 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(keys: 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(keys: 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(keys: toMove, to: dst) + } + blackHole(d) + } + } + } } diff --git a/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift b/Benchmarks/Sources/Benchmarks/OrderedSetBenchmarks.swift index 9e51e2a9..25e0ffe9 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(members: [size - 1], to: 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(members: [size - 1], to: 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(members: toMove, to: 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(members: toMove, to: 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(members: toMove, to: 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(members: toMove, to: 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(members: [src], to: 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(members: toMove, to: 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(members: toMove, to: 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(members: toMove, to: 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.moveSubrange(src, to: 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.moveSubrange(src, to: 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(members: toMove, to: 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(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 7e0845ee..2e538aaf 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(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 a7d38994..5381d121 100644 --- a/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md +++ b/Sources/OrderedCollections/OrderedCollections.docc/Extensions/OrderedSet.md @@ -129,6 +129,9 @@ - ``shuffle()`` - ``shuffle(using:)`` - ``partition(by:)`` +- ``moveSubrange(_: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 new file mode 100644 index 00000000..a61f0dea --- /dev/null +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift @@ -0,0 +1,164 @@ +//===----------------------------------------------------------------------===// +// +// 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 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) + /// // 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 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 + /// 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 + ) { + 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, + 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 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 + /// duplicates. + /// + /// var d: OrderedDictionary = [0: "a", 1: "b", 2: "c", 3: "d"] + /// d.move(keys: [3, 0], to: 1) + /// // 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 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 + /// proportional to the distance moved. + @inlinable + public mutating func move( + keys: some Sequence, + to destination: Index + ) { + _values.withUnsafeMutableBufferPointer { values in + _keys._move(members: keys, to: destination) { + sourceOffsets, sortedSources, isContiguousRange, target in + values._move( + sourceOffsets: sourceOffsets, + sortedSources: sortedSources, + isContiguousRange: isContiguousRange, + to: target) + } + } + _checkInvariants() + } + + /// 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. + /// + /// var d: OrderedDictionary = [0: "a", 1: "b", 2: "c", 3: "d", 4: "e"] + /// d.move(indices: [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 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 + /// proportional to the distance moved. + @inlinable + public mutating func move( + indices: some Sequence, + to destination: Index + ) { + _values.withUnsafeMutableBufferPointer { values in + _keys._move(indices: indices, to: destination) { + sourceOffsets, sortedSources, isContiguousRange, target in + values._move( + sourceOffsets: sourceOffsets, + sortedSources: sortedSources, + isContiguousRange: isContiguousRange, + to: target) + } + } + _checkInvariants() + } +} diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift new file mode 100644 index 00000000..78678c0a --- /dev/null +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift @@ -0,0 +1,800 @@ +//===----------------------------------------------------------------------===// +// +// 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. +// +// 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 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) + /// // set is now [0, 4, 5, 1, 2, 3, 6] + /// + /// - Parameters: + /// - range: The range of indices addressing the elements to move. + /// - 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 + /// 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 + ) { + 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, + to destination: Index + ) { + let c = range.count + guard c > 0 else { return } + _failEarlyRangeCheck(range, bounds: startIndex ..< endIndex) + precondition( + destination >= 0 && destination <= count - c, + "Destination index \(destination) out of range 0 ... \(count - c)") + guard range.lowerBound != destination else { return } + _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 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, 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 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 + /// proportional to the distance moved. + @inlinable + public mutating func move( + members elements: some Sequence, + to destination: Index + ) { + _move(members: elements, to: destination) + } + + /// 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. + /// + /// var set: OrderedSet = [0, 1, 2, 3, 4] + /// set.move(indices: [4, 1], to: 0) + /// // set is now [4, 1, 0, 2, 3] + /// + /// - Parameters: + /// - indices: The indices of the elements to move. + /// - 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 + /// proportional to the distance moved. + @inlinable + public mutating func move( + indices: some Sequence, + to destination: Index + ) { + _move(indices: indices, to: destination) + } +} + +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, 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, 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) + 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 + } + } + 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: 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, 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( + 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 + } + } + if index < destination { below += 1 } + } + let target = destination - below + _move( + sourceOffsets: sourceOffsets, + isContiguousRange: isContiguousRange, + isSorted: isSorted, + 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, 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 + guard source.count > 0 else { return } + withUnsafeTemporaryAllocation( + of: Int.self, capacity: source.count + ) { 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 } + if c > 0 { + let prev = sourceOffsets[c - 1] + if index <= prev { + isSorted = false + isContiguousRange = false + } else if index != prev + 1 { + isContiguousRange = false + } + } + if index < destination { below += 1 } + 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 + } + } + if index < destination { below += 1 } + prev = index + sourceOffsets.append(index) + } + let target = destination - below + sourceOffsets.withUnsafeBufferPointer { sourceOffsets in + _move( + sourceOffsets: sourceOffsets, + isContiguousRange: isContiguousRange, + isSorted: isSorted, + to: target, + applyingTo: body) + } + } + + /// Relocates the elements at `sourceOffsets` (in that order) so the moved + /// block starts at `target`. + /// + /// - Parameter target: The moved block's final start index (post-removal), in + /// `0 ... count - sourceOffsets.count`. Callers convert the public, + /// pre-removal destination to this while scanning the input, so no extra + /// pass is needed here. + @inlinable + internal mutating func _move( + sourceOffsets: UnsafeBufferPointer, + isContiguousRange: Bool, + isSorted: Bool, + to target: Index, + applyingTo body: ( + UnsafeBufferPointer, UnsafeBufferPointer, Bool, Int + ) -> Void + ) { + let c = sourceOffsets.count + guard c > 0 else { return } + + // A no-op is exactly an in-order contiguous run already sitting at + // `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 `target`. + if isContiguousRange && sourceOffsets[0] == target { return } + + if isSorted { + // Already ascending: the sorted view is the input view, no copy needed. + _applyMove( + sourceOffsets: sourceOffsets, + sortedSources: sourceOffsets, + isContiguousRange: isContiguousRange, + to: target, + 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: 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, + sortedSources: UnsafeBufferPointer, + isContiguousRange: Bool, + to destination: Index, + applyingTo body: ( + UnsafeBufferPointer, UnsafeBufferPointer, Bool, Int + ) -> Void + ) { + _elements.withUnsafeMutableBufferPointer { buffer in + buffer._move( + sourceOffsets: sourceOffsets, + sortedSources: sortedSources, + isContiguousRange: isContiguousRange, + to: destination) + } + _updateHashAfterMove( + sourceOffsets: sourceOffsets, + sortedSources: sortedSources, + isContiguousRange: isContiguousRange, + to: destination) + 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. `destination` is the block's final start index (post-removal). + @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 + + _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 + } + } + } + + /// Repoints buckets after the elements at `sourceOffsets` were relocated to + /// start at `destination`. `_elements` is already rearranged. `destination` + /// is the block's final start index (post-removal). + @inlinable + internal mutating func _updateHashAfterMove( + sourceOffsets: UnsafeBufferPointer, + sortedSources: UnsafeBufferPointer, + isContiguousRange: Bool, + to destination: Int + ) { + let count = sourceOffsets.count + let minSource = sortedSources[0] + + 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 + } + } + + 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 { + // 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) + } + } else { + _regenerateHashTable(scale: _scale, reservedScale: _reservedScale) + } + } + } +} + +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. + /// `destination` is the block's final start index (post-removal). + @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. + /// + /// - Parameter destination: The subrange's final start index (post-removal). + @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 + } + } + + /// 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. `destination` is the block's + /// final start index (post-removal). + @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`. + /// + /// `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, + 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 UnsafeBufferPointer 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/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index 62fc5abe..ec9647a8 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -1168,6 +1168,156 @@ 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) { dst in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) + 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) + 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_keys() { + withEvery("count", in: 1 ..< 10) { count in + let positions = Array(stride(from: 0, to: count, by: 2)) + 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 } + 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) + for (key, value) in reference { + expectEqual(d[key], value) + } + } + } + } + } + } + } + + func test_move_keys_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(keys: keysToMove, to: 1) + expectEqualElements(d, reference) + } + } + + func test_move_keys_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(keys: [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 { + var d = OrderedDictionary(uniqueKeys: 0 ..< n, values: 100 ..< 100 + n) + d.move(keys: perm, to: dst) + check(d, "perm=\(perm) dst=\(dst)") + } + } + } + } + + 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) { dst in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var (d, reference) = tracker.orderedDictionary(keys: 0 ..< count) + 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) + 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 c8f67fec..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 @@ -1597,10 +1615,456 @@ 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(members: [] as [Int], to: 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(members: [source], to: 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)) + } + } + } + } + } + } + } + + 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(members: [0, count - 1], to: mid) + let expected = referenceMove( + Array(0 ..< count), positions: [0, count - 1], to: 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(members: reversed, to: 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(members: [1, 2], to: 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(members: evens, to: 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(members: [3, 1], to: 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) { destination in + var set = OrderedSet(layout: layout) + set.move(members: [a, b], to: destination) + let expected = referenceMove( + Array(0 ..< count), positions: [a, b], to: 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.moveSubrange(mid ..< mid + 2, to: mid) + expectEqualElements(set, expected) + } + } + + 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(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] + 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(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_members_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(members: mixed, to: 0) + } else { + set.move(members: AnySequence(mixed), to: 0) + } + expectEqualElements(set, expected) + withEvery("item", in: 0 ..< count) { item in + expectNotNil(set.firstIndex(of: item)) + } + } + } + } + } + } + + func test_move_members_allMissing_isNoOp() { + var set: OrderedSet = [0, 1, 2, 3, 4] + 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_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) { dst in + let contents = (0 ..< count).map { $0 * 10 } + 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 + 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)) + } + } + } + } + } + } + } + + 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 + 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(indices: indices, to: dst) + byValue.move(members: 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) { dst in + var set = OrderedSet(layout: layout) + set.moveSubrange(src ..< src + k, to: dst) + let expected = referenceMove( + Array(0 ..< count), positions: Array(src ..< src + k), to: 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(members: Array(src ..< src + k), to: dst) + setB.moveSubrange(src ..< src + k, to: 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(members: reversed, to: 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) { dst in + var set = OrderedSet(layout: layout) + set.move(members: perm, to: dst) + let expected = referenceMove(Array(0 ..< count), positions: perm, to: dst) + expectEqualElements(set, expected) + } + } + } + } + } + + // 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. + // 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, 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 })) + } + 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 { + var set = OrderedSet(0 ..< n) + set.move(members: perm, to: dst) + check(set, "perm=\(perm) dst=\(dst)") + } + } + } + } }