mirror of
https://github.com/apple/swift-collections
synced 2026-11-24 04:27:53 +00:00
I have a linked list prototype that can support comparable indices (and an O(1) `count`); accordingly, reinstate the requirement for index comparability. This eliminates a potential performance footgun for custom containers that define their own Index, as an incomparable index would make `func distance` 2x slower.
48 lines
1.5 KiB
Swift
48 lines
1.5 KiB
Swift
//===----------------------------------------------------------------------===//
|
|
//
|
|
// This source file is part of the Swift Collections open source project
|
|
//
|
|
// Copyright (c) 2024 - 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 compiler(>=6.4) && UnstableContainersPreview
|
|
|
|
@available(SwiftStdlib 6.4, *)
|
|
extension PermutableContainer
|
|
where
|
|
Self: BidirectionalContainer,
|
|
Element: ~Copyable
|
|
{
|
|
@inlinable
|
|
@discardableResult
|
|
public mutating func moveSubrange(
|
|
_ subrange: Range<Index>,
|
|
to insertionPoint: Index
|
|
) -> Range<Index> {
|
|
if subrange.contains(insertionPoint) {
|
|
return subrange
|
|
}
|
|
let c = self.distance(from: subrange.lowerBound, to: subrange.upperBound)
|
|
if insertionPoint < subrange.lowerBound {
|
|
self.reverseSubrange(insertionPoint ..< subrange.upperBound)
|
|
let cut = self.index(insertionPoint, offsetBy: c)
|
|
self.reverseSubrange(insertionPoint ..< cut)
|
|
self.reverseSubrange(cut ..< subrange.upperBound)
|
|
return insertionPoint ..< cut
|
|
}
|
|
self.reverseSubrange(subrange.lowerBound ..< insertionPoint)
|
|
let cut = self.index(insertionPoint, offsetBy: -c)
|
|
self.reverseSubrange(subrange.lowerBound ..< cut)
|
|
self.reverseSubrange(cut ..< insertionPoint)
|
|
return cut ..< insertionPoint
|
|
}
|
|
}
|
|
|
|
#endif
|