mirror of
https://github.com/apple/swift-collections
synced 2026-11-22 04:20:40 +00:00
Work around another MergeModules crash (#62)
* [utils] Add utility for shuffling sources to help reproduce MergeModules issues * [Deque] Collapse Sequence/Collection conformances into a single file The MergeModules phase in the compiler is broken: it isn’t always able to correctly handle circular dependencies across source files, like the ones that keep organically popping up with Sequence/Collection conformances that are defined in separate files. Such dependencies sometimes triggers a compiler crash, depending on some (unknown) environmental parameters. Trying to manually find and eliminate these circular dependencies has not proved productive. Instead, roll all Collection conformances into a single, huge source file. * [Deque] Update CMakeLists
This commit is contained in:
1 parent
4a4aecf0ce
commit
fa45de1018
6 files changed
+529
-506
No files matched your search
@@ -17,6 +17,7 @@ add_library(DequeModule
|
||||
Deque._UnsafeHandle.swift
|
||||
Deque.swift
|
||||
Deque+Codable.swift
|
||||
Deque+Collection.swift
|
||||
Deque+CustomDebugStringConvertible.swift
|
||||
Deque+CustomReflectable.swift
|
||||
Deque+CustomStringConvertible.swift
|
||||
@@ -24,10 +25,6 @@ add_library(DequeModule
|
||||
Deque+ExpressibleByArrayLiteral.swift
|
||||
Deque+Extras.swift
|
||||
Deque+Hashable.swift
|
||||
Deque+MutableCollection.swift
|
||||
Deque+RandomAccessCollection.swift
|
||||
Deque+RangeReplaceableCollection.swift
|
||||
Deque+Sequence.swift
|
||||
Deque+Testing.swift
|
||||
UnsafeMutableBufferPointer+Utilities.swift)
|
||||
set_target_properties(DequeModule PROPERTIES
|
||||
|
||||
+480
-16
@@ -9,6 +9,470 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Deque: Sequence {
|
||||
// Implementation note: we could also use the default `IndexingIterator` here.
|
||||
// This custom implementation performs direct storage access to eliminate any
|
||||
// and all index validation overhead. It also optimizes away repeated
|
||||
// conversions from indices to storage slots.
|
||||
|
||||
/// An iterator over the members of a deque.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var _storage: Deque._Storage
|
||||
|
||||
@usableFromInline
|
||||
internal var _nextSlot: _Slot
|
||||
|
||||
@usableFromInline
|
||||
internal var _endSlot: _Slot
|
||||
|
||||
@inlinable
|
||||
internal init(_storage: Deque._Storage, start: _Slot, end: _Slot) {
|
||||
self._storage = _storage
|
||||
self._nextSlot = start
|
||||
self._endSlot = end
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init(_base: Deque) {
|
||||
self = _base._storage.read { handle in
|
||||
let start = handle.startSlot
|
||||
let end = Swift.min(start.advanced(by: handle.count), handle.limSlot)
|
||||
return Self(_storage: _base._storage, start: start, end: end)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init(_base: Deque, from index: Int) {
|
||||
self = _base._storage.read { handle in
|
||||
assert(index >= 0 && index <= handle.count)
|
||||
let start = handle.slot(forOffset: index)
|
||||
if index == handle.count {
|
||||
return Self(_storage: _base._storage, start: start, end: start)
|
||||
}
|
||||
var end = handle.endSlot
|
||||
if start >= end { end = handle.limSlot }
|
||||
return Self(_storage: _base._storage, start: start, end: end)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@inline(never)
|
||||
internal mutating func _swapSegment() -> Bool {
|
||||
assert(_nextSlot == _endSlot)
|
||||
return _storage.read { handle in
|
||||
let end = handle.endSlot
|
||||
if end == .zero || end == _nextSlot {
|
||||
return false
|
||||
}
|
||||
_endSlot = end
|
||||
_nextSlot = .zero
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or `nil` if no next element
|
||||
/// exists.
|
||||
///
|
||||
/// Once `nil` has been returned, all subsequent calls return `nil`.
|
||||
@inlinable
|
||||
public mutating func next() -> Element? {
|
||||
if _nextSlot == _endSlot {
|
||||
guard _swapSegment() else { return nil }
|
||||
}
|
||||
assert(_nextSlot < _endSlot)
|
||||
let slot = _nextSlot
|
||||
_nextSlot = _nextSlot.advanced(by: 1)
|
||||
return _storage.read { handle in
|
||||
return handle.ptr(at: slot).pointee
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an iterator over the elements of the deque.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(_base: self)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
|
||||
ContiguousArray(unsafeUninitializedCapacity: _storage.count) { target, count in
|
||||
_storage.read { source in
|
||||
let segments = source.segments()
|
||||
let c = segments.first.count
|
||||
target[..<c]._rebased()._initialize(from: segments.first)
|
||||
count += segments.first.count
|
||||
if let second = segments.second {
|
||||
target[c ..< c + second.count]._rebased()._initialize(from: second)
|
||||
count += second.count
|
||||
}
|
||||
assert(count == source.count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public __consuming func _copyContents(
|
||||
initializing target: UnsafeMutableBufferPointer<Element>
|
||||
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
|
||||
_storage.read { source in
|
||||
let segments = source.segments()
|
||||
let c1 = Swift.min(segments.first.count, target.count)
|
||||
target[..<c1]._rebased()._initialize(from: segments.first.prefix(c1)._rebased())
|
||||
guard target.count > c1, let second = segments.second else {
|
||||
return (Iterator(_base: self, from: c1), c1)
|
||||
}
|
||||
let c2 = Swift.min(second.count, target.count - c1)
|
||||
target[c1 ..< c1 + c2]._rebased()._initialize(from: second.prefix(c2)._rebased())
|
||||
return (Iterator(_base: self, from: c1 + c2), c1 + c2)
|
||||
}
|
||||
}
|
||||
|
||||
/// Call `body(b)`, where `b` is an unsafe buffer pointer to the deque's
|
||||
/// contiguous storage, if available. If the deque's contents aren't stored
|
||||
/// contiguously, `body` is not called and `nil` is returned. The supplied
|
||||
/// buffer pointer is only valid for the duration of the call.
|
||||
///
|
||||
/// Often, the optimizer can eliminate bounds- and uniqueness-checks within an
|
||||
/// algorithm, but when that fails, invoking the same algorithm on the unsafe
|
||||
/// buffer supplied to `body` lets you trade safety for speed.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: The function to invoke.
|
||||
///
|
||||
/// - Returns: The value returned by `body`, or `nil` if `body` wasn't called.
|
||||
///
|
||||
/// - Complexity: O(1) when this instance has a unique reference to its
|
||||
/// underlying storage; O(`count`) otherwise.
|
||||
@inlinable
|
||||
public func withContiguousStorageIfAvailable<R>(
|
||||
_ body: (UnsafeBufferPointer<Element>) throws -> R
|
||||
) rethrows -> R? {
|
||||
return try _storage.read { handle in
|
||||
let endSlot = handle.startSlot.advanced(by: handle.count)
|
||||
guard endSlot.position <= handle.capacity else { return nil }
|
||||
return try body(handle.buffer(for: handle.startSlot ..< endSlot))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Deque: RandomAccessCollection {
|
||||
public typealias Index = Int
|
||||
public typealias SubSequence = Slice<Self>
|
||||
public typealias Indices = Range<Int>
|
||||
|
||||
/// The number of elements in the deque.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var count: Int { _storage.count }
|
||||
|
||||
/// The position of the first element in a nonempty deque.
|
||||
///
|
||||
/// For an instance of `Deque`, `startIndex` is always zero. If the deque is
|
||||
/// empty, `startIndex` is equal to `endIndex`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var startIndex: Int { 0 }
|
||||
|
||||
/// The deque’s “past the end” position—that is, the position one greater than
|
||||
/// the last valid subscript argument.
|
||||
///
|
||||
/// For an instance of `Deque`, `endIndex` is always equal to its `count`. If
|
||||
/// the deque is empty, `endIndex` is equal to `startIndex`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var endIndex: Int { count }
|
||||
|
||||
/// The indices that are valid for subscripting this deque, in ascending order.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var indices: Range<Int> { 0 ..< count }
|
||||
|
||||
/// Returns the position immediately after the given index.
|
||||
///
|
||||
/// - Parameter `i`: A valid index of the deque. `i` must be less than
|
||||
/// `endIndex`.
|
||||
///
|
||||
/// - Returns: The next valid index immediately after `i`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func index(after i: Int) -> Int {
|
||||
// Note: Like `Array`, index manipulation methods on deques don't trap on
|
||||
// invalid indices. (Indices are still validated on element access.)
|
||||
return i + 1
|
||||
}
|
||||
|
||||
/// Replaces the given index with its successor.
|
||||
///
|
||||
/// - Parameter `i`: A valid index of the deque. `i` must be less than
|
||||
/// `endIndex`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func formIndex(after i: inout Int) {
|
||||
// Note: Like `Array`, index manipulation methods on deques
|
||||
// don't trap on invalid indices.
|
||||
// (Indices are still validated on element access.)
|
||||
i += 1
|
||||
}
|
||||
|
||||
/// Returns the position immediately before the given index.
|
||||
///
|
||||
/// - Parameter `i`: A valid index of the deque. `i` must be greater than
|
||||
/// `startIndex`.
|
||||
///
|
||||
/// - Returns: The preceding valid index immediately before `i`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func index(before i: Int) -> Int {
|
||||
// Note: Like `Array`, index manipulation methods on deques don't trap on
|
||||
// invalid indices. (Indices are still validated on element access.)
|
||||
return i - 1
|
||||
}
|
||||
|
||||
/// Replaces the given index with its predecessor.
|
||||
///
|
||||
/// - Parameter `i`: A valid index of the deque. `i` must be greater than `startIndex`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func formIndex(before i: inout Int) {
|
||||
// Note: Like `Array`, index manipulation methods on deques don't trap on
|
||||
// invalid indices. (Indices are still validated on element access.)
|
||||
i -= 1
|
||||
}
|
||||
|
||||
/// Returns an index that is the specified distance from the given index.
|
||||
///
|
||||
/// The value passed as `distance` must not offset `i` beyond the bounds of
|
||||
/// the collection.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - i: A valid index of the deque.
|
||||
/// - `distance`: The distance by which to offset `i`.
|
||||
///
|
||||
/// - Returns: An index offset by `distance` from the index `i`. If `distance`
|
||||
/// is positive, this is the same value as the result of `distance` calls
|
||||
/// to `index(after:)`. If `distance` is negative, this is the same value
|
||||
/// as the result of `abs(distance)` calls to `index(before:)`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func index(_ i: Int, offsetBy distance: Int) -> Int {
|
||||
// Note: Like `Array`, index manipulation methods on deques don't trap on
|
||||
// invalid indices. (Indices are still validated on element access.)
|
||||
return i + distance
|
||||
}
|
||||
|
||||
/// Returns an index that is the specified distance from the given index,
|
||||
/// unless that distance is beyond a given limiting index.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - i: A valid index of the array.
|
||||
/// - distance: The distance to offset `i`.
|
||||
/// - limit: A valid index of the deque to use as a limit.
|
||||
/// If `distance > 0`, then `limit` has no effect it is less than `i`.
|
||||
/// Likewise, if `distance < 0`, then `limit` has no effect if it is
|
||||
/// greater than `i`.
|
||||
///
|
||||
/// - Returns: An index offset by `distance` from the index `i`, unless that
|
||||
/// index would be beyond `limit` in the direction of movement. In that
|
||||
/// case, the method returns `nil`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Int,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Int
|
||||
) -> Int? {
|
||||
// Note: Like `Array`, index manipulation methods on deques
|
||||
// don't trap on invalid indices.
|
||||
// (Indices are still validated on element access.)
|
||||
let l = limit - i
|
||||
if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l {
|
||||
return nil
|
||||
}
|
||||
return i + distance
|
||||
}
|
||||
|
||||
|
||||
/// Returns the distance between two indices.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - start: A valid index of the collection.
|
||||
/// - end: Another valid index of the collection.
|
||||
///
|
||||
/// - Returns: The distance between `start` and `end`. If `end` is equal to
|
||||
/// `start`, the result is zero. Otherwise the result is positive if `end`
|
||||
/// is greater than `start`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func distance(from start: Int, to end: Int) -> Int {
|
||||
// Note: Like `Array`, index manipulation method on deques
|
||||
// don't trap on invalid indices.
|
||||
// (Indices are still validated on element access.)
|
||||
return end - start
|
||||
}
|
||||
|
||||
/// Accesses the element at the specified position.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - index: The position of the element to access. `index` must be greater
|
||||
/// than or equal to `startIndex` and less than `endIndex`.
|
||||
///
|
||||
/// - Complexity: Reading an element from a deque is O(1). Writing is O(1)
|
||||
/// unless the deque’s storage is shared with another deque, in which case
|
||||
/// writing is O(`count`).
|
||||
@inlinable
|
||||
public subscript(index: Int) -> Element {
|
||||
get {
|
||||
precondition(index >= 0 && index < count, "Index out of bounds")
|
||||
return _storage.read { $0.ptr(at: $0.slot(forOffset: index)).pointee }
|
||||
}
|
||||
set {
|
||||
precondition(index >= 0 && index < count, "Index out of bounds")
|
||||
_storage.ensureUnique()
|
||||
_storage.update { handle in
|
||||
let slot = handle.slot(forOffset: index)
|
||||
handle.ptr(at: slot).pointee = newValue
|
||||
}
|
||||
}
|
||||
_modify {
|
||||
precondition(index >= 0 && index < count, "Index out of bounds")
|
||||
_storage.ensureUnique()
|
||||
// We technically aren't supposed to escape storage pointers out of a
|
||||
// managed buffer, so we escape a `(slot, value)` pair instead, leaving
|
||||
// the corresponding slot temporarily uninitialized.
|
||||
var (slot, value) = _storage.update { handle -> (_Slot, Element) in
|
||||
let slot = handle.slot(forOffset: index)
|
||||
return (slot, handle.ptr(at: slot).move())
|
||||
}
|
||||
defer {
|
||||
_storage.update { handle in
|
||||
handle.ptr(at: slot).initialize(to: value)
|
||||
}
|
||||
}
|
||||
yield &value
|
||||
}
|
||||
}
|
||||
|
||||
/// Accesses a contiguous subrange of the deque's elements.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bounds: A range of the deque's indices. The bounds of the range must
|
||||
/// be valid indices of the deque (including the `endIndex`).
|
||||
///
|
||||
/// The accessed slice uses the same indices for the same elements as the
|
||||
/// original collection.
|
||||
@inlinable
|
||||
public subscript(bounds: Range<Int>) -> Slice<Self> {
|
||||
get {
|
||||
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
|
||||
"Invalid bounds")
|
||||
return Slice(base: self, bounds: bounds)
|
||||
}
|
||||
set(source) {
|
||||
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
|
||||
"Invalid bounds")
|
||||
self.replaceSubrange(bounds, with: source)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension Deque: MutableCollection {
|
||||
/// Exchanges the values at the specified indices of the collection.
|
||||
///
|
||||
/// Both parameters must be valid indices of the collection and not equal to
|
||||
/// `endIndex`. Passing the same index as both `i` and `j` has no effect.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - i: The index of the first value to swap.
|
||||
/// - j: The index of the second value to swap.
|
||||
///
|
||||
/// - Complexity: O(1) when this instance has a unique reference to its
|
||||
/// underlying storage; O(`count`) otherwise.
|
||||
@inlinable
|
||||
public mutating func swapAt(_ i: Int, _ j: Int) {
|
||||
precondition(i >= 0 && i < count, "Index out of bounds")
|
||||
precondition(j >= 0 && j < count, "Index out of bounds")
|
||||
_storage.ensureUnique()
|
||||
_storage.update { handle in
|
||||
let slot1 = handle.slot(forOffset: i)
|
||||
let slot2 = handle.slot(forOffset: j)
|
||||
handle.mutableBuffer.swapAt(slot1.position, slot2.position)
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME: Implement `partition(by:)` by making storage contiguous,
|
||||
// and partitioning that.
|
||||
|
||||
/// Call `body(b)`, where `b` is an unsafe buffer pointer to the deque's
|
||||
/// mutable contiguous storage. If the deque's contents aren't stored
|
||||
/// contiguously, `body` is not called and `nil` is returned. The supplied
|
||||
/// buffer pointer is only valid for the duration of the call.
|
||||
///
|
||||
/// Often, the optimizer can eliminate bounds- and uniqueness-checks within an
|
||||
/// algorithm, but when that fails, invoking the same algorithm on the unsafe
|
||||
/// buffer supplied to `body` lets you trade safety for speed.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: The function to invoke.
|
||||
///
|
||||
/// - Returns: The value returned by `body`, or `nil` if `body` wasn't called.
|
||||
///
|
||||
/// - Complexity: O(1) when this instance has a unique reference to its
|
||||
/// underlying storage; O(`count`) otherwise. (Not counting the call to
|
||||
/// `body`.)
|
||||
@inlinable
|
||||
public mutating func withContiguousMutableStorageIfAvailable<R>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
|
||||
) rethrows -> R? {
|
||||
_storage.ensureUnique()
|
||||
return try _storage.update { handle in
|
||||
let endSlot = handle.startSlot.advanced(by: handle.count)
|
||||
guard endSlot.position <= handle.capacity else {
|
||||
// FIXME: Rotate storage such that it becomes contiguous.
|
||||
return nil
|
||||
}
|
||||
let original = handle.mutableBuffer(for: handle.startSlot ..< endSlot)
|
||||
var extract = original
|
||||
defer {
|
||||
precondition(extract.baseAddress == original.baseAddress && extract.count == original.count,
|
||||
"Closure must not replace the provided buffer")
|
||||
}
|
||||
return try body(&extract)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
|
||||
) rethrows -> R? {
|
||||
return try withContiguousMutableStorageIfAvailable(body)
|
||||
}
|
||||
}
|
||||
|
||||
extension Deque: RangeReplaceableCollection {
|
||||
/// Creates a new, empty deque.
|
||||
///
|
||||
@@ -27,6 +491,22 @@ extension Deque: RangeReplaceableCollection {
|
||||
_storage = _Storage()
|
||||
}
|
||||
|
||||
/// Reserves enough space to store the specified number of elements.
|
||||
///
|
||||
/// If you are adding a known number of elements to a deque, use this method
|
||||
/// to avoid multiple reallocations. It ensures that the deque has unique
|
||||
/// storage, with space allocated for at least the requested number of
|
||||
/// elements.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - minimumCapacity: The requested number of elements to store.
|
||||
///
|
||||
/// - Complexity: O(`count`)
|
||||
@inlinable
|
||||
public mutating func reserveCapacity(_ minimumCapacity: Int) {
|
||||
_storage.ensureUnique(minimumCapacity: minimumCapacity, linearGrowth: true)
|
||||
}
|
||||
|
||||
/// Replaces a range of elements with the elements in the specified
|
||||
/// collection.
|
||||
///
|
||||
@@ -77,22 +557,6 @@ extension Deque: RangeReplaceableCollection {
|
||||
}
|
||||
}
|
||||
|
||||
/// Reserves enough space to store the specified number of elements.
|
||||
///
|
||||
/// If you are adding a known number of elements to a deque, use this method
|
||||
/// to avoid multiple reallocations. It ensures that the deque has unique
|
||||
/// storage, with space allocated for at least the requested number of
|
||||
/// elements.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - minimumCapacity: The requested number of elements to store.
|
||||
///
|
||||
/// - Complexity: O(`count`)
|
||||
@inlinable
|
||||
public mutating func reserveCapacity(_ minimumCapacity: Int) {
|
||||
_storage.ensureUnique(minimumCapacity: minimumCapacity, linearGrowth: true)
|
||||
}
|
||||
|
||||
/// Creates a new deque containing the specified number of a single, repeated
|
||||
/// value.
|
||||
///
|
||||
@@ -1,83 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 2021 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Deque: MutableCollection {
|
||||
/// Exchanges the values at the specified indices of the collection.
|
||||
///
|
||||
/// Both parameters must be valid indices of the collection and not equal to
|
||||
/// `endIndex`. Passing the same index as both `i` and `j` has no effect.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - i: The index of the first value to swap.
|
||||
/// - j: The index of the second value to swap.
|
||||
///
|
||||
/// - Complexity: O(1) when this instance has a unique reference to its
|
||||
/// underlying storage; O(`count`) otherwise.
|
||||
@inlinable
|
||||
public mutating func swapAt(_ i: Int, _ j: Int) {
|
||||
precondition(i >= 0 && i < count, "Index out of bounds")
|
||||
precondition(j >= 0 && j < count, "Index out of bounds")
|
||||
_storage.ensureUnique()
|
||||
_storage.update { handle in
|
||||
let slot1 = handle.slot(forOffset: i)
|
||||
let slot2 = handle.slot(forOffset: j)
|
||||
handle.mutableBuffer.swapAt(slot1.position, slot2.position)
|
||||
}
|
||||
}
|
||||
|
||||
// FIXME: Implement `partition(by:)` by making storage contiguous,
|
||||
// and partitioning that.
|
||||
|
||||
/// Call `body(b)`, where `b` is an unsafe buffer pointer to the deque's
|
||||
/// mutable contiguous storage. If the deque's contents aren't stored
|
||||
/// contiguously, `body` is not called and `nil` is returned. The supplied
|
||||
/// buffer pointer is only valid for the duration of the call.
|
||||
///
|
||||
/// Often, the optimizer can eliminate bounds- and uniqueness-checks within an
|
||||
/// algorithm, but when that fails, invoking the same algorithm on the unsafe
|
||||
/// buffer supplied to `body` lets you trade safety for speed.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: The function to invoke.
|
||||
///
|
||||
/// - Returns: The value returned by `body`, or `nil` if `body` wasn't called.
|
||||
///
|
||||
/// - Complexity: O(1) when this instance has a unique reference to its
|
||||
/// underlying storage; O(`count`) otherwise. (Not counting the call to
|
||||
/// `body`.)
|
||||
@inlinable
|
||||
public mutating func withContiguousMutableStorageIfAvailable<R>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
|
||||
) rethrows -> R? {
|
||||
_storage.ensureUnique()
|
||||
return try _storage.update { handle in
|
||||
let endSlot = handle.startSlot.advanced(by: handle.count)
|
||||
guard endSlot.position <= handle.capacity else {
|
||||
// FIXME: Rotate storage such that it becomes contiguous.
|
||||
return nil
|
||||
}
|
||||
let original = handle.mutableBuffer(for: handle.startSlot ..< endSlot)
|
||||
var extract = original
|
||||
defer {
|
||||
precondition(extract.baseAddress == original.baseAddress && extract.count == original.count,
|
||||
"Closure must not replace the provided buffer")
|
||||
}
|
||||
return try body(&extract)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
|
||||
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
|
||||
) rethrows -> R? {
|
||||
return try withContiguousMutableStorageIfAvailable(body)
|
||||
}
|
||||
}
|
||||
@@ -1,243 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 2021 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Deque: RandomAccessCollection {
|
||||
public typealias Index = Int
|
||||
public typealias SubSequence = Slice<Self>
|
||||
|
||||
/// The number of elements in the deque.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var count: Int { _storage.count }
|
||||
|
||||
/// The position of the first element in a nonempty deque.
|
||||
///
|
||||
/// For an instance of `Deque`, `startIndex` is always zero. If the deque is
|
||||
/// empty, `startIndex` is equal to `endIndex`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var startIndex: Int { 0 }
|
||||
|
||||
/// The deque’s “past the end” position—that is, the position one greater than
|
||||
/// the last valid subscript argument.
|
||||
///
|
||||
/// For an instance of `Deque`, `endIndex` is always equal to its `count`. If
|
||||
/// the deque is empty, `endIndex` is equal to `startIndex`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public var endIndex: Int { count }
|
||||
|
||||
/// Returns the position immediately after the given index.
|
||||
///
|
||||
/// - Parameter `i`: A valid index of the deque. `i` must be less than
|
||||
/// `endIndex`.
|
||||
///
|
||||
/// - Returns: The next valid index immediately after `i`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func index(after i: Int) -> Int {
|
||||
// Note: Like `Array`, index manipulation methods on deques don't trap on
|
||||
// invalid indices. (Indices are still validated on element access.)
|
||||
return i + 1
|
||||
}
|
||||
|
||||
/// Replaces the given index with its successor.
|
||||
///
|
||||
/// - Parameter `i`: A valid index of the deque. `i` must be less than
|
||||
/// `endIndex`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func formIndex(after i: inout Int) {
|
||||
// Note: Like `Array`, index manipulation methods on deques
|
||||
// don't trap on invalid indices.
|
||||
// (Indices are still validated on element access.)
|
||||
i += 1
|
||||
}
|
||||
|
||||
/// Returns the position immediately before the given index.
|
||||
///
|
||||
/// - Parameter `i`: A valid index of the deque. `i` must be greater than
|
||||
/// `startIndex`.
|
||||
///
|
||||
/// - Returns: The preceding valid index immediately before `i`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func index(before i: Int) -> Int {
|
||||
// Note: Like `Array`, index manipulation methods on deques don't trap on
|
||||
// invalid indices. (Indices are still validated on element access.)
|
||||
return i - 1
|
||||
}
|
||||
|
||||
/// Replaces the given index with its predecessor.
|
||||
///
|
||||
/// - Parameter `i`: A valid index of the deque. `i` must be greater than `startIndex`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func formIndex(before i: inout Int) {
|
||||
// Note: Like `Array`, index manipulation methods on deques don't trap on
|
||||
// invalid indices. (Indices are still validated on element access.)
|
||||
i -= 1
|
||||
}
|
||||
|
||||
/// Returns an index that is the specified distance from the given index.
|
||||
///
|
||||
/// The value passed as `distance` must not offset `i` beyond the bounds of
|
||||
/// the collection.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - i: A valid index of the deque.
|
||||
/// - `distance`: The distance by which to offset `i`.
|
||||
///
|
||||
/// - Returns: An index offset by `distance` from the index `i`. If `distance`
|
||||
/// is positive, this is the same value as the result of `distance` calls
|
||||
/// to `index(after:)`. If `distance` is negative, this is the same value
|
||||
/// as the result of `abs(distance)` calls to `index(before:)`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func index(_ i: Int, offsetBy distance: Int) -> Int {
|
||||
// Note: Like `Array`, index manipulation methods on deques don't trap on
|
||||
// invalid indices. (Indices are still validated on element access.)
|
||||
return i + distance
|
||||
}
|
||||
|
||||
/// Returns an index that is the specified distance from the given index,
|
||||
/// unless that distance is beyond a given limiting index.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - i: A valid index of the array.
|
||||
/// - distance: The distance to offset `i`.
|
||||
/// - limit: A valid index of the deque to use as a limit.
|
||||
/// If `distance > 0`, then `limit` has no effect it is less than `i`.
|
||||
/// Likewise, if `distance < 0`, then `limit` has no effect if it is
|
||||
/// greater than `i`.
|
||||
///
|
||||
/// - Returns: An index offset by `distance` from the index `i`, unless that
|
||||
/// index would be beyond `limit` in the direction of movement. In that
|
||||
/// case, the method returns `nil`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func index(
|
||||
_ i: Int,
|
||||
offsetBy distance: Int,
|
||||
limitedBy limit: Int
|
||||
) -> Int? {
|
||||
// Note: Like `Array`, index manipulation methods on deques
|
||||
// don't trap on invalid indices.
|
||||
// (Indices are still validated on element access.)
|
||||
let l = limit - i
|
||||
if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l {
|
||||
return nil
|
||||
}
|
||||
return i + distance
|
||||
}
|
||||
|
||||
|
||||
/// Returns the distance between two indices.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - start: A valid index of the collection.
|
||||
/// - end: Another valid index of the collection.
|
||||
///
|
||||
/// - Returns: The distance between `start` and `end`. If `end` is equal to
|
||||
/// `start`, the result is zero. Otherwise the result is positive if `end`
|
||||
/// is greater than `start`.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
@inline(__always)
|
||||
public func distance(from start: Int, to end: Int) -> Int {
|
||||
// Note: Like `Array`, index manipulation method on deques
|
||||
// don't trap on invalid indices.
|
||||
// (Indices are still validated on element access.)
|
||||
return end - start
|
||||
}
|
||||
|
||||
/// Accesses the element at the specified position.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - index: The position of the element to access. `index` must be greater
|
||||
/// than or equal to `startIndex` and less than `endIndex`.
|
||||
///
|
||||
/// - Complexity: Reading an element from a deque is O(1). Writing is O(1)
|
||||
/// unless the deque’s storage is shared with another deque, in which case
|
||||
/// writing is O(`count`).
|
||||
@inlinable
|
||||
public subscript(index: Int) -> Element {
|
||||
get {
|
||||
precondition(index >= 0 && index < count, "Index out of bounds")
|
||||
return _storage.read { $0.ptr(at: $0.slot(forOffset: index)).pointee }
|
||||
}
|
||||
set {
|
||||
precondition(index >= 0 && index < count, "Index out of bounds")
|
||||
_storage.ensureUnique()
|
||||
_storage.update { handle in
|
||||
let slot = handle.slot(forOffset: index)
|
||||
handle.ptr(at: slot).pointee = newValue
|
||||
}
|
||||
}
|
||||
_modify {
|
||||
precondition(index >= 0 && index < count, "Index out of bounds")
|
||||
_storage.ensureUnique()
|
||||
// We technically aren't supposed to escape storage pointers out of a
|
||||
// managed buffer, so we escape a `(slot, value)` pair instead, leaving
|
||||
// the corresponding slot temporarily uninitialized.
|
||||
var (slot, value) = _storage.update { handle -> (_Slot, Element) in
|
||||
let slot = handle.slot(forOffset: index)
|
||||
return (slot, handle.ptr(at: slot).move())
|
||||
}
|
||||
defer {
|
||||
_storage.update { handle in
|
||||
handle.ptr(at: slot).initialize(to: value)
|
||||
}
|
||||
}
|
||||
yield &value
|
||||
}
|
||||
}
|
||||
|
||||
/// Accesses a contiguous subrange of the deque's elements.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - bounds: A range of the deque's indices. The bounds of the range must
|
||||
/// be valid indices of the deque (including the `endIndex`).
|
||||
///
|
||||
/// The accessed slice uses the same indices for the same elements as the
|
||||
/// original collection.
|
||||
@inlinable
|
||||
public subscript(bounds: Range<Int>) -> Slice<Self> {
|
||||
get {
|
||||
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
|
||||
"Invalid bounds")
|
||||
return Slice(base: self, bounds: bounds)
|
||||
}
|
||||
set(source) {
|
||||
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
|
||||
"Invalid bounds")
|
||||
self.replaceSubrange(bounds, with: source)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,160 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// This source file is part of the Swift Collections open source project
|
||||
//
|
||||
// Copyright (c) 2021 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
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension Deque: Sequence {
|
||||
// Implementation note: we could also use the default `IndexingIterator` here.
|
||||
// This custom implementation performs direct storage access to eliminate any
|
||||
// and all index validation overhead. It also optimizes away repeated
|
||||
// conversions from indices to storage slots.
|
||||
|
||||
/// An iterator over the members of a deque.
|
||||
public struct Iterator: IteratorProtocol {
|
||||
@usableFromInline
|
||||
internal var _storage: Deque._Storage
|
||||
|
||||
@usableFromInline
|
||||
internal var _nextSlot: _Slot
|
||||
|
||||
@usableFromInline
|
||||
internal var _endSlot: _Slot
|
||||
|
||||
@inlinable
|
||||
internal init(_storage: Deque._Storage, start: _Slot, end: _Slot) {
|
||||
self._storage = _storage
|
||||
self._nextSlot = start
|
||||
self._endSlot = end
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init(_base: Deque) {
|
||||
self = _base._storage.read { handle in
|
||||
let start = handle.startSlot
|
||||
let end = Swift.min(start.advanced(by: handle.count), handle.limSlot)
|
||||
return Self(_storage: _base._storage, start: start, end: end)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal init(_base: Deque, from index: Int) {
|
||||
assert(index <= _base.count)
|
||||
self = _base._storage.read { handle in
|
||||
let start = handle.slot(forOffset: index)
|
||||
if index == _base.count {
|
||||
return Self(_storage: _base._storage, start: start, end: start)
|
||||
}
|
||||
var end = handle.endSlot
|
||||
if start >= end { end = handle.limSlot }
|
||||
return Self(_storage: _base._storage, start: start, end: end)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@inline(never)
|
||||
internal mutating func _swapSegment() -> Bool {
|
||||
assert(_nextSlot == _endSlot)
|
||||
return _storage.read { handle in
|
||||
let end = handle.endSlot
|
||||
if end == .zero || end == _nextSlot {
|
||||
return false
|
||||
}
|
||||
_endSlot = end
|
||||
_nextSlot = .zero
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
/// Advances to the next element and returns it, or `nil` if no next element
|
||||
/// exists.
|
||||
///
|
||||
/// Once `nil` has been returned, all subsequent calls return `nil`.
|
||||
@inlinable
|
||||
public mutating func next() -> Element? {
|
||||
if _nextSlot == _endSlot {
|
||||
guard _swapSegment() else { return nil }
|
||||
}
|
||||
assert(_nextSlot < _endSlot)
|
||||
let slot = _nextSlot
|
||||
_nextSlot = _nextSlot.advanced(by: 1)
|
||||
return _storage.read { handle in
|
||||
return handle.ptr(at: slot).pointee
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an iterator over the elements of the deque.
|
||||
///
|
||||
/// - Complexity: O(1)
|
||||
@inlinable
|
||||
public func makeIterator() -> Iterator {
|
||||
Iterator(_base: self)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
|
||||
ContiguousArray(unsafeUninitializedCapacity: count) { target, count in
|
||||
_storage.read { source in
|
||||
let segments = source.segments()
|
||||
let c = segments.first.count
|
||||
target[..<c]._rebased()._initialize(from: segments.first)
|
||||
count += segments.first.count
|
||||
if let second = segments.second {
|
||||
target[c ..< c + second.count]._rebased()._initialize(from: second)
|
||||
count += second.count
|
||||
}
|
||||
assert(count == self.count)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public __consuming func _copyContents(
|
||||
initializing target: UnsafeMutableBufferPointer<Element>
|
||||
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
|
||||
_storage.read { source in
|
||||
let segments = source.segments()
|
||||
let c1 = Swift.min(segments.first.count, target.count)
|
||||
target[..<c1]._rebased()._initialize(from: segments.first.prefix(c1)._rebased())
|
||||
guard target.count > c1, let second = segments.second else {
|
||||
return (Iterator(_base: self, from: c1), c1)
|
||||
}
|
||||
let c2 = Swift.min(second.count, target.count - c1)
|
||||
target[c1 ..< c1 + c2]._rebased()._initialize(from: second.prefix(c2)._rebased())
|
||||
return (Iterator(_base: self, from: c1 + c2), c1 + c2)
|
||||
}
|
||||
}
|
||||
|
||||
/// Call `body(b)`, where `b` is an unsafe buffer pointer to the deque's
|
||||
/// contiguous storage, if available. If the deque's contents aren't stored
|
||||
/// contiguously, `body` is not called and `nil` is returned. The supplied
|
||||
/// buffer pointer is only valid for the duration of the call.
|
||||
///
|
||||
/// Often, the optimizer can eliminate bounds- and uniqueness-checks within an
|
||||
/// algorithm, but when that fails, invoking the same algorithm on the unsafe
|
||||
/// buffer supplied to `body` lets you trade safety for speed.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - body: The function to invoke.
|
||||
///
|
||||
/// - Returns: The value returned by `body`, or `nil` if `body` wasn't called.
|
||||
///
|
||||
/// - Complexity: O(1) when this instance has a unique reference to its
|
||||
/// underlying storage; O(`count`) otherwise.
|
||||
@inlinable
|
||||
public func withContiguousStorageIfAvailable<R>(
|
||||
_ body: (UnsafeBufferPointer<Element>) throws -> R
|
||||
) rethrows -> R? {
|
||||
return try _storage.read { handle in
|
||||
let endSlot = handle.startSlot.advanced(by: handle.count)
|
||||
guard endSlot.position <= handle.capacity else { return nil }
|
||||
return try body(handle.buffer(for: handle.startSlot ..< endSlot))
|
||||
}
|
||||
}
|
||||
}
|
||||
Executable
+48
@@ -0,0 +1,48 @@
|
||||
#!/bin/sh
|
||||
#
|
||||
# Randomly reorder Swift source files in the specified directory, then
|
||||
# try rebuilding the package, in a loop.
|
||||
#
|
||||
# This script is useful to help reproducing nondeterministic issues
|
||||
# with the Swift compiler's MergeModules phase, as in
|
||||
# https://github.com/apple/swift-collections/issues/7
|
||||
#
|
||||
|
||||
set -eu
|
||||
|
||||
|
||||
function shuffle() {
|
||||
input="$1"
|
||||
|
||||
tmp="$(dirname "$input")/tmp"
|
||||
mkdir "$tmp"
|
||||
local i=0
|
||||
ls "$input"/*.swift | sort -R | while read file; do
|
||||
mv "$file" "$tmp/$i.swift"
|
||||
i=$(($i + 1))
|
||||
done
|
||||
|
||||
mv "$tmp"/*.swift "$input"
|
||||
rmdir "$tmp"
|
||||
}
|
||||
|
||||
if [[ -z "${1+set}" || ! -d "$1" ]]; then
|
||||
echo "Usage: $0 <directory> <build-arguments>..." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
dir="$1"
|
||||
shift
|
||||
|
||||
cd "$(dirname "$0")/.."
|
||||
|
||||
i=0
|
||||
while true; do
|
||||
echo
|
||||
echo "$i"
|
||||
|
||||
rm -rf .build
|
||||
shuffle "$dir"
|
||||
xcrun swift build "$@"
|
||||
i="$(($i + 1))"
|
||||
done
|
||||
Reference in new issue
Block a user