Initial import.

Introduce OrderedCollections module
This commit is contained in:
Karoy Lorentey committed 2021-04-05 09:41:00 -07:00
commit a2bcac435f
198 files changed
+38487

No files matched your search

+49
View File
@@ -0,0 +1,49 @@
//===----------------------------------------------------------------------===//
//
// 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: Encodable where Element: Encodable {
/// Encodes the elements of this deque into the given encoder in an unkeyed
/// container.
///
/// This function throws an error if any values are invalid for the given
/// encoder's format.
///
/// - Parameter encoder: The encoder to write data to.
@inlinable
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
for element in self {
try container.encode(element)
}
}
}
extension Deque: Decodable where Element: Decodable {
/// Creates a new deque by decoding from the given decoder.
///
/// This initializer throws an error if reading from the decoder fails, or
/// if the data read is corrupted or otherwise invalid.
///
/// - Parameter decoder: The decoder to read data from.
@inlinable
public init(from decoder: Decoder) throws {
self.init()
var container = try decoder.unkeyedContainer()
if let count = container.count {
self.reserveCapacity(count)
}
while !container.isAtEnd {
let element = try container.decode(Element.self)
self.append(element)
}
}
}
@@ -0,0 +1,28 @@
//===----------------------------------------------------------------------===//
//
// 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: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
var result = "Deque<\(Element.self)>(["
var first = true
for item in self {
if first {
first = false
} else {
result += ", "
}
debugPrint(item, terminator: "", to: &result)
}
result += "])"
return result
}
}
@@ -0,0 +1,17 @@
//===----------------------------------------------------------------------===//
//
// 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: CustomReflectable {
/// The custom mirror for this instance.
public var customMirror: Mirror {
Mirror(self, unlabeledChildren: self, displayStyle: .collection)
}
}
@@ -0,0 +1,28 @@
//===----------------------------------------------------------------------===//
//
// 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: CustomStringConvertible {
/// A textual representation of this instance.
public var description: String {
var result = "["
var first = true
for item in self {
if first {
first = false
} else {
result += ", "
}
print(item, terminator: "", to: &result)
}
result += "]"
return result
}
}
+22
View File
@@ -0,0 +1,22 @@
//===----------------------------------------------------------------------===//
//
// 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: Equatable where Element: Equatable {
/// Returns a Boolean value indicating whether two values are equal. Two
/// deques are considered equal if they contain the same elements in the same
/// order.
///
/// - Complexity: O(`min(left.count, right.count)`)
@inlinable
public static func ==(left: Self, right: Self) -> Bool {
return left.elementsEqual(right)
}
}
@@ -0,0 +1,27 @@
//===----------------------------------------------------------------------===//
//
// 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: ExpressibleByArrayLiteral {
/// Creates a new deque from the contents of an array literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use an array literal. Instead, create a new set using an array
/// literal as its value by enclosing a comma-separated list of values in
/// square brackets. You can use an array literal anywhere a set is expected
/// by the type context.
///
/// - Parameter elements: A variadic list of elements of the new set.
@inlinable
@inline(__always)
public init(arrayLiteral elements: Element...) {
self.init(elements)
}
}
+180
View File
@@ -0,0 +1,180 @@
//===----------------------------------------------------------------------===//
//
// 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 {
/// Creates a deque with the specified capacity, then calls the given
/// closure with a buffer covering the array's uninitialized memory.
///
/// Inside the closure, set the `initializedCount` parameter to the number of
/// elements that are initialized by the closure. The memory in the range
/// `buffer[0..<initializedCount]` must be initialized at the end of the
/// closure's execution, and the memory in the range
/// `buffer[initializedCount...]` must be uninitialized. This postcondition
/// must hold even if the `initializer` closure throws an error.
///
/// - Note: While the resulting deque may have a capacity larger than the
/// requested amount, the buffer passed to the closure will cover exactly
/// the requested number of elements.
///
/// - Parameters:
/// - unsafeUninitializedCapacity: The number of elements to allocate
/// space for in the new deque.
/// - initializer: A closure that initializes elements and sets the count
/// of the new deque.
/// - Parameters:
/// - buffer: A buffer covering uninitialized memory with room for the
/// specified number of elements.
/// - initializedCount: The count of initialized elements in the deque,
/// which begins as zero. Set `initializedCount` to the number of
/// elements you initialize.
@inlinable
public init(
unsafeUninitializedCapacity capacity: Int,
initializingWith initializer:
(inout UnsafeMutableBufferPointer<Element>, inout Int) throws -> Void
) rethrows {
self._storage = .init(minimumCapacity: capacity)
try _storage.update { handle in
handle.startSlot = .zero
var count = 0
var buffer = handle.mutableBuffer(for: .zero ..< _Slot(at: capacity))
defer {
precondition(count <= capacity,
"Initialized count set to greater than specified capacity")
let b = handle.mutableBuffer(for: .zero ..< _Slot(at: capacity))
precondition(buffer.baseAddress == b.baseAddress && buffer.count == b.count,
"Initializer relocated Deque storage")
handle.count = count
}
try initializer(&buffer, &count)
}
}
}
extension Deque {
/// Removes and returns the first element of this deque, if it exists.
///
/// - Returns: The first element of the original collection if the collection
/// isn't empty; otherwise, `nil`.
///
/// - Complexity: O(1) when this instance has a unique reference to its
/// underlying storage; O(`count`) otherwise.
@inlinable
public mutating func popFirst() -> Element? {
// FIXME: Add this to the stdlib on BidirectionalCollection
// where Self == Self.SubSequence
guard count > 0 else { return nil }
_storage.ensureUnique()
return _storage.update {
$0.uncheckedRemoveFirst()
}
}
// Note: `popLast` is implemented by the stdlib as a
// `RangeReplaceableCollection` extension, defined in terms of
// `_customRemoveLast`.
/// Adds a new element at the front of the deque.
///
/// Use this method to append a single element to the front of a deque.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.prepend(100)
/// print(numbers)
/// // Prints "[100, 1, 2, 3, 4, 5]"
///
/// Because deques increase their allocated capacity using an exponential
/// strategy, prepending a single element to a deque is an O(1) operation when
/// averaged over many calls to the `prepend(_:)` method. When a deque has
/// additional capacity and is not sharing its storage with another instance,
/// prepending an element is O(1). When a deque needs to reallocate storage
/// before prepending or its storage is shared with another copy, prepending
/// is O(`count`).
///
/// - Parameter newElement: The element to prepend to the deque.
///
/// - Complexity: Amortized O(1).
///
/// - SeeAlso: `append(_:)`
@inlinable
public mutating func prepend(_ newElement: Element) {
_storage.ensureUnique(minimumCapacity: count + 1)
return _storage.update {
$0.uncheckedPrepend(newElement)
}
}
/// Adds the elements of a collection to the front of the deque.
///
/// Use this method to prepend the elements of a collection to the front of
/// this deque. This example prepends the elements of a `Range<Int>` instance
/// to a deque of integers.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.prepend(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5]"
///
/// - Parameter newElements: The elements to prepend to the deque.
///
/// - Complexity: Amortized O(`newElements.count`).
///
/// - SeeAlso: `append(contentsOf:)`
@inlinable
public mutating func prepend<C: Collection>(contentsOf newElements: C) where C.Element == Element {
let done: Void? = newElements.withContiguousStorageIfAvailable { source in
_storage.ensureUnique(minimumCapacity: count + source.count)
_storage.update { $0.uncheckedPrepend(contentsOf: source) }
}
guard done == nil else { return }
let c = newElements.count
guard c > 0 else { return }
_storage.ensureUnique(minimumCapacity: count + c)
_storage.update { target in
let gaps = target.availableSegments().suffix(c)
gaps.initialize(from: newElements)
target.count += c
target.startSlot = target.slot(target.startSlot, offsetBy: -c)
}
}
/// Adds the elements of a sequence to the front of the deque.
///
/// Use this method to prepend the elements of a sequence to the front of this
/// deque. This example prepends the elements of a `Range<Int>` instance to a
/// deque of integers.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.prepend(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5]"
///
/// - Parameter newElements: The elements to prepend to the deque.
///
/// - Complexity: Amortized O(`newElements.count`).
///
/// - SeeAlso: `append(contentsOf:)`
@inlinable
public mutating func prepend<S: Sequence>(contentsOf newElements: S) where S.Element == Element {
let originalCount = self.count
self.append(contentsOf: newElements)
let newCount = self.count
let c = newCount - originalCount
_storage.update { target in
target.startSlot = target.slot(forOffset: originalCount)
target.count = target.capacity
target.closeGap(offsets: c ..< c + (target.capacity - newCount))
assert(target.count == newCount)
}
}
}
+24
View File
@@ -0,0 +1,24 @@
//===----------------------------------------------------------------------===//
//
// 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: Hashable where Element: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Complexity: O(`count`)
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(count) // discriminator
for element in self {
hasher.combine(element)
}
}
}
@@ -0,0 +1,83 @@
//===----------------------------------------------------------------------===//
//
// 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: Index, _ j: Index) {
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)
}
}
@@ -0,0 +1,243 @@
//===----------------------------------------------------------------------===//
//
// 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: Index { 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: Index { 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: Index) -> Index {
// 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 Index) {
// 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: Index) -> Index {
// 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 Index) {
// 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: Index, offsetBy distance: Int) -> Index {
// 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: Index, to end: Index) -> 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: Index) -> 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<Index>) -> 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)
}
}
}
@@ -0,0 +1,437 @@
//===----------------------------------------------------------------------===//
//
// 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: RangeReplaceableCollection {
/// Creates a new, empty deque.
///
/// This is equivalent to initializing with an empty array literal.
/// For example:
///
/// let deque1 = Deque<Int>()
/// print(deque1.isEmpty) // true
///
/// let deque2: Deque<Int> = []
/// print(deque2.isEmpty) // true
///
/// - Complexity: O(1)
@inlinable
public init() {
_storage = _Storage()
}
/// Replaces a range of elements with the elements in the specified
/// collection.
///
/// This method has the effect of removing the specified range of elements
/// from the deque and inserting the new elements at the same location. The
/// number of new elements need not match the number of elements being
/// removed.
///
/// - Parameters:
/// - subrange: The subrange of the deque to replace. The bounds of the
/// subrange must be valid indices of the deque (including the
/// `endIndex`).
/// - newElements: The new elements to add to the deque.
///
/// - Complexity: O(`self.count + newElements.count`). If the operation needs
/// to change the size of the deque, it minimizes the number of existing
/// items that need to be moved by shifting elements either before or after
/// `subrange`.
@inlinable
public mutating func replaceSubrange<C: Collection>(
_ subrange: Range<Index>,
with newElements: __owned C
) where C.Element == Element {
precondition(subrange.lowerBound >= 0 && subrange.upperBound <= count, "Index range out of bounds")
let removalCount = subrange.count
let insertionCount = newElements.count
let deltaCount = insertionCount - removalCount
_storage.ensureUnique(minimumCapacity: count + deltaCount)
let replacementCount = Swift.min(removalCount, insertionCount)
let targetCut = subrange.lowerBound + replacementCount
let sourceCut = newElements.index(newElements.startIndex, offsetBy: replacementCount)
_storage.update { target in
target.uncheckedReplaceInPlace(
inOffsets: subrange.lowerBound ..< targetCut,
with: newElements[..<sourceCut])
if deltaCount < 0 {
let r = targetCut ..< subrange.upperBound
assert(replacementCount + r.count == removalCount)
target.uncheckedRemove(offsets: r)
} else if deltaCount > 0 {
target.uncheckedInsert(
contentsOf: newElements[sourceCut...],
count: deltaCount,
atOffset: targetCut)
}
}
}
/// 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.
///
/// - Parameters:
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the element. `count` must be zero
/// or greater.
///
/// - Complexity: O(`count`)
@inlinable
public init(repeating repeatedValue: Element, count: Int) {
precondition(count >= 0)
self.init(minimumCapacity: count)
_storage.update { handle in
assert(handle.startSlot == .zero)
if count > 0 {
handle.ptr(at: .zero).initialize(repeating: repeatedValue, count: count)
}
handle.count = count
}
}
/// Creates a deque containing the elements of a sequence.
///
/// - Parameters:
/// - elements: The sequence of elements to turn into a deque.
///
/// - Complexity: O(*n*), where *n* is the number of elements in the sequence.
@inlinable
public init<S: Sequence>(_ elements: S) where S.Element == Element {
self.init()
self.append(contentsOf: elements)
}
/// Creates a deque containing the elements of a collection.
///
/// - Parameters:
/// - elements: The collection of elements to turn into a deque.
///
/// - Complexity: O(`elements.count`)
@inlinable
public init<C: Collection>(_ elements: C) where C.Element == Element {
let c = elements.count
guard c > 0 else { _storage = _Storage(); return }
self._storage = _Storage(minimumCapacity: c)
_storage.update { handle in
assert(handle.startSlot == .zero)
let target = handle.mutableBuffer(for: .zero ..< _Slot(at: c))
let done: Void? = elements.withContiguousStorageIfAvailable { source in
target._initialize(from: source)
}
if done == nil {
target._initialize(from: elements)
}
handle.count = c
}
}
/// Adds a new element at the end of the deque.
///
/// Use this method to append a single element to the end of a deque.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.append(100)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 100]"
///
/// Because deques increase their allocated capacity using an exponential
/// strategy, appending a single element to a deque is an O(1) operation when
/// averaged over many calls to the `append(_:)` method. When a deque has
/// additional capacity and is not sharing its storage with another instance,
/// appending an element is O(1). When a deque needs to reallocate storage
/// before prepending or its storage is shared with another copy, appending is
/// O(`count`).
///
/// - Parameters:
/// - newElement: The element to append to the deque.
///
/// - Complexity: Amortized O(1)
///
/// - SeeAlso: `prepend(_:)`
@inlinable
public mutating func append(_ newElement: Element) {
_storage.ensureUnique(minimumCapacity: count + 1)
_storage.update {
$0.uncheckedAppend(newElement)
}
}
/// Adds the elements of a sequence to the end of the deque.
///
/// Use this method to append the elements of a sequence to the front of this
/// deque. This example appends the elements of a `Range<Int>` instance to a
/// deque of integers.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.append(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameter newElements: The elements to append to the deque.
///
/// - Complexity: Amortized O(`newElements.count`).
@inlinable
public mutating func append<S: Sequence>(contentsOf newElements: S) where S.Element == Element {
let done: Void? = newElements.withContiguousStorageIfAvailable { source in
_storage.ensureUnique(minimumCapacity: count + source.count)
_storage.update { $0.uncheckedAppend(contentsOf: source) }
}
if done != nil {
return
}
let underestimatedCount = newElements.underestimatedCount
reserveCapacity(count + underestimatedCount)
var it: S.Iterator = _storage.update { target in
let gaps = target.availableSegments()
let (it, copied) = gaps.initialize(fromSequencePrefix: newElements)
target.count += copied
return it
}
while let next = it.next() {
_storage.ensureUnique(minimumCapacity: count + 1)
_storage.update { target in
target.uncheckedAppend(next)
let gaps = target.availableSegments()
target.count += gaps.initialize(fromPrefixOf: &it)
}
}
}
/// Adds the elements of a collection to the end of the deque.
///
/// Use this method to append the elements of a collection to the front of
/// this deque. This example appends the elements of a `Range<Int>` instance
/// to a deque of integers.
///
/// var numbers: Deque = [1, 2, 3, 4, 5]
/// numbers.append(contentsOf: 10...15)
/// print(numbers)
/// // Prints "[1, 2, 3, 4, 5, 10, 11, 12, 13, 14, 15]"
///
/// - Parameter newElements: The elements to append to the deque.
///
/// - Complexity: Amortized O(`newElements.count`).
@inlinable
public mutating func append<C: Collection>(contentsOf newElements: C) where C.Element == Element {
let done: Void? = newElements.withContiguousStorageIfAvailable { source in
_storage.ensureUnique(minimumCapacity: count + source.count)
_storage.update { $0.uncheckedAppend(contentsOf: source) }
}
guard done == nil else { return }
let c = newElements.count
guard c > 0 else { return }
reserveCapacity(count + c)
_storage.update { target in
let gaps = target.availableSegments().prefix(c)
gaps.initialize(from: newElements)
target.count += c
}
}
/// Inserts a new element at the specified position.
///
/// The new element is inserted before the element currently at the specified
/// index. If you pass the deque’s `endIndex` as the `index` parameter, the
/// new element is appended to the deque.
///
/// - Parameters:
/// - newElement: The new element to insert into the deque.
/// - index: The position at which to insert the new element. `index` must
/// be a valid index of the deque (including `endIndex`).
///
/// - Complexity: O(`count`). The operation shifts existing elements either
/// towards the beginning or the end of the deque to minimize the number of
/// elements that need to be moved. When inserting at the start or the end,
/// this reduces the complexity to amortized O(1).
@inlinable
public mutating func insert(_ newElement: Element, at index: Index) {
precondition(index >= 0 && index <= count,
"Can't insert element at invalid index")
_storage.ensureUnique(minimumCapacity: count + 1)
_storage.update { target in
if index == 0 {
target.uncheckedPrepend(newElement)
return
}
if index == count {
target.uncheckedAppend(newElement)
return
}
let gap = target.openGap(ofSize: 1, atOffset: index)
assert(gap.first.count == 1)
gap.first.baseAddress!.initialize(to: newElement)
}
}
/// Inserts the elements of a collection into the deque at the specified
/// position.
///
/// The new elements are inserted before the element currently at the
/// specified index. If you pass the deque's `endIndex` property as the
/// `index` parameter, the new elements are appended to the deque.
///
/// - Parameters:
/// - newElements: The new elements to insert into the deque.
/// - index: The position at which to insert the new elements. `index` must
/// be a valid index of the deque (including `endIndex`).
///
/// - Complexity: O(`count + newElements.count`). The operation shifts
/// existing elements either towards the beginning or the end of the deque
/// to minimize the number of elements that need to be moved. When
/// inserting at the start or the end, this reduces the complexity to
/// amortized O(1).
@inlinable
public mutating func insert<C: Collection>(
contentsOf newElements: __owned C, at index: Index
) where C.Element == Element {
precondition(index >= 0 && index <= count,
"Can't insert elements at an invalid index")
let newCount = newElements.count
_storage.ensureUnique(minimumCapacity: count + newCount)
_storage.update { target in
target.uncheckedInsert(contentsOf: newElements, count: newCount, atOffset: index)
}
}
/// Removes and returns the element at the specified position.
///
/// To close the resulting gap, all elements following the specified position
/// are (logically) moved up by one index position. (Internally, the deque may
/// actually decide to shift previous elements forward instead to minimize the
/// number of elements that need to be moved.)
///
/// - Parameters:
/// - index: The position of the element to remove. `index` must be a valid
/// index of the array.
///
/// - Returns: The element originally at the specified index.
///
/// - Complexity: O(`count`). Removing elements from the start or end of the
/// deque costs O(1) if the deque's storage isn't shared.
@inlinable
@discardableResult
public mutating func remove(at index: Index) -> Element {
precondition(index >= 0 && index < self.count, "Index out of bounds")
// FIXME: Implement storage shrinking
_storage.ensureUnique()
return _storage.update { target in
// FIXME: Add direct implementation & see if it makes a difference
let result = self[index]
target.uncheckedRemove(offsets: index ..< index + 1)
return result
}
}
/// Removes the elements in the specified subrange from the deque.
/// All elements following the specified range are (logically) moved up to
/// close the resulting gap. (Internally, the deque may actually decide to
/// shift previous elements forward instead to minimize the number of elements
/// that need to be moved.)
///
/// - Parameters:
/// - bounds: The range of the collection to be removed. The bounds of the
/// range must be valid indices of the collection.
///
/// - Complexity: O(`count`). Removing elements from the start or end of the
/// deque costs O(`bounds.count`) if the deque's storage isn't shared.
@inlinable
public mutating func removeSubrange(_ bounds: Range<Index>) {
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= self.count,
"Index range out of bounds")
_storage.ensureUnique()
_storage.update { $0.uncheckedRemove(offsets: bounds) }
}
@inlinable
public mutating func _customRemoveLast() -> Element? {
precondition(!isEmpty, "Cannot remove last element of an empty Deque")
_storage.ensureUnique()
return _storage.update { $0.uncheckedRemoveLast() }
}
@inlinable
public mutating func _customRemoveLast(_ n: Int) -> Bool {
precondition(n >= 0, "Can't remove a negative number of elements")
precondition(n <= count, "Can't remove more elements than there are in the Collection")
_storage.ensureUnique()
_storage.update { $0.uncheckedRemoveLast(n) }
return true
}
/// Removes and returns the first element of the deque.
///
/// The collection must not be empty.
///
/// - Returns: The removed element.
///
/// - Complexity: O(1) if the underlying storage isn't shared; otherwise
/// O(`count`).
@inlinable
@discardableResult
public mutating func removeFirst() -> Element {
precondition(!isEmpty, "Cannot remove first element of an empty Deque")
_storage.ensureUnique()
return _storage.update { $0.uncheckedRemoveFirst() }
}
/// Removes the specified number of elements from the beginning of the deque.
///
/// - Parameter n: The number of elements to remove from the deque. `n` must
/// be greater than or equal to zero and must not exceed the number of
/// elements in the deque.
///
/// - Complexity: O(`n`) if the underlying storage isn't shared; otherwise
/// O(`count`).
@inlinable
public mutating func removeFirst(_ n: Int) {
precondition(n >= 0, "Can't remove a negative number of elements")
precondition(n <= count, "Can't remove more elements than there are in the Collection")
_storage.ensureUnique()
return _storage.update { $0.uncheckedRemoveFirst(n) }
}
/// Removes all elements from the deque.
///
/// - Parameter keepCapacity: Pass true to keep the existing storage capacity
/// of the deque after removing its elements. The default value is false.
///
/// - Complexity: O(`count`)
@inlinable
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
if keepCapacity {
_storage.ensureUnique()
_storage.update { $0.uncheckedRemoveAll() }
} else {
self = Deque()
}
}
}
+160
View File
@@ -0,0 +1,160 @@
//===----------------------------------------------------------------------===//
//
// 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: Index) {
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))
}
}
}
+76
View File
@@ -0,0 +1,76 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// This file contains exported but non-public entry points to support clear box
// testing.
extension Deque {
/// The maximum number of elements this deque is currently able to store
/// without reallocating its storage buffer.
///
/// This information isn't exposed as public, as the returned value isn't
/// guaranteed to be stable, and may even differ between equal deques,
/// violating value semantics.
///
/// This property isn't intended to be used outside of `Deque`'s own test
/// target.
@_spi(Testing)
public var _capacity: Int {
_storage.capacity
}
/// The number of the storage slot in this deque that holds the first element.
/// (Or would hold it after an insertion in case the deque is currently
/// empty.)
///
/// This property isn't intended to be used outside of `Deque`'s own test
/// target.
@_spi(Testing)
public var _startSlot: Int {
_storage.startSlot.position
}
/// Constructs a deque instance of the specified contents and layout. Exposed
/// as public to allow exhaustive input/output tests for `Deque`'s members.
/// This isn't intended to be used outside of `Deque`'s own test target.
@_spi(Testing)
public init<S: Sequence>(
_capacity capacity: Int,
startSlot: Int,
contents: S
) where S.Element == Element {
let contents = ContiguousArray(contents)
precondition(capacity >= 0)
precondition(startSlot >= 0 && (startSlot < capacity || (capacity == 0 && startSlot == 0)))
precondition(contents.count <= capacity)
let startSlot = _Slot(at: startSlot)
let buffer = _DequeBuffer<Element>.create(minimumCapacity: capacity) { _ in
_DequeBufferHeader(capacity: capacity, count: contents.count, startSlot: startSlot)
}
let storage = Deque<Element>._Storage(unsafeDowncast(buffer, to: _DequeBuffer.self))
if contents.count > 0 {
contents.withUnsafeBufferPointer { source in
storage.update { target in
let segments = target.mutableSegments()
let c = segments.first.count
segments.first._initialize(from: source.prefix(c)._rebased())
if let second = segments.second {
second._initialize(from: source.dropFirst(c)._rebased())
}
}
}
}
self.init(_storage: storage)
assert(self._capacity == capacity)
assert(self._startSlot == startSlot.position)
assert(self.count == contents.count)
}
}
+208
View File
@@ -0,0 +1,208 @@
//===----------------------------------------------------------------------===//
//
// 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 {
@usableFromInline
struct _Storage {
@usableFromInline
internal typealias _Buffer = ManagedBufferPointer<_DequeBufferHeader, Element>
@usableFromInline
internal var _buffer: _Buffer
@inlinable
@inline(__always)
internal init(_buffer: _Buffer) {
self._buffer = _buffer
}
}
}
extension Deque._Storage: CustomStringConvertible {
@usableFromInline
internal var description: String {
"Deque<\(Element.self)>._Storage\(_buffer.header)"
}
}
extension Deque._Storage {
@inlinable
internal init() {
self.init(_buffer: _Buffer(unsafeBufferObject: _emptyDequeStorage))
}
@inlinable
internal init(_ object: _DequeBuffer<Element>) {
self.init(_buffer: _Buffer(unsafeBufferObject: object))
}
@inlinable
internal init(minimumCapacity: Int) {
let object = _DequeBuffer<Element>.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: { object in
_DequeBufferHeader(capacity: object.capacity, count: 0, startSlot: .zero)
})
self.init(_buffer: _Buffer(unsafeBufferObject: object))
}
}
extension Deque._Storage {
#if COLLECTIONS_INTERNAL_CHECKS
@usableFromInline @inline(never) @_effects(releasenone)
internal func _checkInvariants() {
_buffer.withUnsafeMutablePointerToHeader { $0.pointee._checkInvariants() }
}
#else
@inlinable @inline(__always)
internal func _checkInvariants() {}
#endif // COLLECTIONS_INTERNAL_CHECKS
}
extension Deque._Storage {
@inlinable
@inline(__always)
internal var identity: AnyObject { _buffer.buffer }
@inlinable
@inline(__always)
internal var capacity: Int {
_buffer.withUnsafeMutablePointerToHeader { $0.pointee.capacity }
}
@inlinable
@inline(__always)
internal var count: Int {
_buffer.withUnsafeMutablePointerToHeader { $0.pointee.count }
}
@inlinable
@inline(__always)
internal var startSlot: _DequeSlot {
_buffer.withUnsafeMutablePointerToHeader { $0.pointee.startSlot
}
}
}
extension Deque._Storage {
@usableFromInline
internal typealias Index = Int
@usableFromInline
internal typealias _UnsafeHandle = Deque._UnsafeHandle
@inlinable
@inline(__always)
internal func read<R>(_ body: (_UnsafeHandle) throws -> R) rethrows -> R {
try _buffer.withUnsafeMutablePointers { header, elements in
let handle = _UnsafeHandle(header: header,
elements: elements,
isMutable: false)
return try body(handle)
}
}
@inlinable
@inline(__always)
internal func update<R>(_ body: (_UnsafeHandle) throws -> R) rethrows -> R {
try _buffer.withUnsafeMutablePointers { header, elements in
let handle = _UnsafeHandle(header: header,
elements: elements,
isMutable: true)
return try body(handle)
}
}
}
extension Deque._Storage {
/// Return a boolean indicating whether this storage instance is known to have
/// a single unique reference. If this method returns true, then it is safe to
/// perform in-place mutations on the deque.
@inlinable
@inline(__always)
internal mutating func isUnique() -> Bool {
_buffer.isUniqueReference()
}
/// Ensure that this storage refers to a uniquely held buffer by copying
/// elements if necessary.
@inlinable
@inline(__always)
internal mutating func ensureUnique() {
if isUnique() { return }
self._makeUniqueCopy()
}
@inlinable
@inline(never)
internal mutating func _makeUniqueCopy() {
self = self.read { $0.copyElements() }
}
/// The growth factor to use to increase storage size to make place for an
/// insertion.
@inlinable
@inline(__always)
internal static var growthFactor: Double { 1.5 }
@usableFromInline
internal func _growCapacity(
to minimumCapacity: Int,
linearly: Bool
) -> Int {
if linearly { return Swift.max(capacity, minimumCapacity) }
return Swift.max(Int((Self.growthFactor * Double(capacity)).rounded(.up)),
minimumCapacity)
}
/// Ensure that we have a uniquely referenced buffer with enough space to
/// store at least `minimumCapacity` elements.
///
/// - Parameter minimumCapacity: The minimum number of elements the buffer
/// needs to be able to hold on return.
///
/// - Parameter linearGrowth: If true, then don't use an exponential growth
/// factor when reallocating the buffer -- just allocate space for the
/// requested number of elements
@inlinable
@inline(__always)
internal mutating func ensureUnique(
minimumCapacity: Int,
linearGrowth: Bool = false
) {
let unique = isUnique()
if _slowPath(capacity < minimumCapacity || !unique) {
_ensureUnique(minimumCapacity: minimumCapacity, linearGrowth: linearGrowth)
}
}
@inlinable
internal mutating func _ensureUnique(
minimumCapacity: Int,
linearGrowth: Bool
) {
if capacity >= minimumCapacity {
assert(!self.isUnique())
self = self.read { $0.copyElements() }
} else if isUnique() {
let minimumCapacity = _growCapacity(to: minimumCapacity, linearly: linearGrowth)
self = self.update { source in
source.moveElements(minimumCapacity: minimumCapacity)
}
} else {
let minimumCapacity = _growCapacity(to: minimumCapacity, linearly: linearGrowth)
self = self.read { source in
source.copyElements(minimumCapacity: minimumCapacity)
}
}
}
}
@@ -0,0 +1,822 @@
//===----------------------------------------------------------------------===//
//
// 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 {
@usableFromInline
internal struct _UnsafeHandle {
@usableFromInline
let _header: UnsafeMutablePointer<_DequeBufferHeader>
@usableFromInline
let _elements: UnsafeMutablePointer<Element>
#if DEBUG
@usableFromInline
let _isMutable: Bool
#endif
@inlinable
@inline(__always)
init(
header: UnsafeMutablePointer<_DequeBufferHeader>,
elements: UnsafeMutablePointer<Element>,
isMutable: Bool
) {
self._header = header
self._elements = elements
#if DEBUG
self._isMutable = isMutable
#endif
}
}
}
extension Deque._UnsafeHandle {
@inlinable
@inline(__always)
func assertMutable() {
#if DEBUG
assert(_isMutable)
#endif
}
}
extension Deque._UnsafeHandle {
@usableFromInline
internal typealias Slot = _DequeSlot
@inlinable
@inline(__always)
var header: _DequeBufferHeader {
_header.pointee
}
@inlinable
@inline(__always)
var capacity: Int {
_header.pointee.capacity
}
@inlinable
@inline(__always)
var count: Int {
get { _header.pointee.count }
nonmutating set { _header.pointee.count = newValue }
}
@inlinable
@inline(__always)
var startSlot: Slot {
get { _header.pointee.startSlot }
nonmutating set { _header.pointee.startSlot = newValue }
}
@inlinable
@inline(__always)
func ptr(at slot: Slot) -> UnsafeMutablePointer<Element> {
assert(slot.position >= 0 && slot.position <= capacity)
return _elements + slot.position
}
}
extension Deque._UnsafeHandle {
@inlinable
@inline(__always)
var mutableBuffer: UnsafeMutableBufferPointer<Element> {
assertMutable()
return .init(start: _elements, count: _header.pointee.capacity)
}
@inlinable
internal func buffer(for range: Range<Slot>) -> UnsafeBufferPointer<Element> {
assert(range.upperBound.position <= capacity)
return .init(start: _elements + range.lowerBound.position, count: range._count)
}
@inlinable
@inline(__always)
internal func mutableBuffer(for range: Range<Slot>) -> UnsafeMutableBufferPointer<Element> {
assertMutable()
return .init(mutating: buffer(for: range))
}
}
extension Deque._UnsafeHandle {
/// The slot immediately following the last valid one. (`endSlot` refers to
/// the valid slot corresponding to `endIndex`, which is a different thing
/// entirely.)
@inlinable
@inline(__always)
internal var limSlot: Slot {
Slot(at: capacity)
}
@inlinable
internal func slot(after slot: Slot) -> Slot {
assert(slot.position < capacity)
let position = slot.position + 1
if position >= capacity {
return Slot(at: 0)
}
return Slot(at: position)
}
@inlinable
internal func slot(before slot: Slot) -> Slot {
assert(slot.position < capacity)
if slot.position == 0 { return Slot(at: capacity - 1) }
return Slot(at: slot.position - 1)
}
@inlinable
internal func slot(_ slot: Slot, offsetBy delta: Int) -> Slot {
assert(slot.position <= capacity)
let position = slot.position + delta
if delta >= 0 {
if position >= capacity { return Slot(at: position - capacity) }
} else {
if position < 0 { return Slot(at: position + capacity) }
}
return Slot(at: position)
}
@inlinable
@inline(__always)
internal var endSlot: Slot {
slot(startSlot, offsetBy: count)
}
/// Return the storage slot corresponding to the specified offset, which may
/// or may not address an existing element.
@inlinable
internal func slot(forOffset offset: Int) -> Slot {
assert(offset >= 0)
assert(offset <= capacity) // Not `count`!
// Note: The use of wrapping addition/subscription is justified here by the
// fact that `offset` is guaranteed to fall in the range `0 ..< capacity`.
// Eliminating the overflow checks leads to a measurable speedup for
// random-access subscript operations. (Up to 2x on some microbenchmarks.)
let position = startSlot.position &+ offset
guard position < capacity else { return Slot(at: position &- capacity) }
return Slot(at: position)
}
}
extension Deque._UnsafeHandle {
@inlinable
internal func segments() -> _UnsafeWrappedBuffer<Element> {
let wrap = capacity - startSlot.position
if count <= wrap {
return .init(start: ptr(at: startSlot), count: count)
}
return .init(first: ptr(at: startSlot), count: wrap,
second: ptr(at: .zero), count: count - wrap)
}
@inlinable
internal func segments(
forOffsets offsets: Range<Int>
) -> _UnsafeWrappedBuffer<Element> {
assert(offsets.lowerBound >= 0 && offsets.upperBound <= count)
let lower = slot(forOffset: offsets.lowerBound)
let upper = slot(forOffset: offsets.upperBound)
if offsets.count == 0 || lower < upper {
return .init(start: ptr(at: lower), count: offsets.count)
}
return .init(first: ptr(at: lower), count: capacity - lower.position,
second: ptr(at: .zero), count: upper.position)
}
@inlinable
@inline(__always)
internal func mutableSegments() -> _UnsafeMutableWrappedBuffer<Element> {
assertMutable()
return .init(mutating: segments())
}
@inlinable
@inline(__always)
internal func mutableSegments(
forOffsets range: Range<Int>
) -> _UnsafeMutableWrappedBuffer<Element> {
assertMutable()
return .init(mutating: segments(forOffsets: range))
}
}
extension Deque._UnsafeHandle {
@inlinable
internal func availableSegments() -> _UnsafeMutableWrappedBuffer<Element> {
assertMutable()
let endSlot = self.endSlot
guard count < capacity else { return .init(start: ptr(at: endSlot), count: 0) }
if endSlot < startSlot { return .init(mutableBuffer(for: endSlot ..< startSlot)) }
return .init(mutableBuffer(for: endSlot ..< limSlot),
mutableBuffer(for: .zero ..< startSlot))
}
}
extension Deque._UnsafeHandle {
@inlinable
@discardableResult
func initialize(
at start: Slot,
from source: UnsafeBufferPointer<Element>
) -> Slot {
assert(start.position + source.count <= capacity)
guard source.count > 0 else { return start }
ptr(at: start).initialize(from: source.baseAddress!, count: source.count)
return Slot(at: start.position + source.count)
}
@inlinable
@inline(__always)
@discardableResult
func moveInitialize(
at start: Slot,
from source: UnsafeMutableBufferPointer<Element>
) -> Slot {
assert(start.position + source.count <= capacity)
guard source.count > 0 else { return start }
ptr(at: start).moveInitialize(from: source.baseAddress!, count: source.count)
return Slot(at: start.position + source.count)
}
@inlinable
@inline(__always)
@discardableResult
public func move(
from source: Slot,
to target: Slot,
count: Int
) -> (source: Slot, target: Slot) {
assert(count >= 0)
assert(source.position + count <= self.capacity)
assert(target.position + count <= self.capacity)
guard count > 0 else { return (source, target) }
ptr(at: target).moveInitialize(from: ptr(at: source), count: count)
return (slot(source, offsetBy: count), slot(target, offsetBy: count))
}
}
extension Deque._UnsafeHandle {
/// Copy elements into a new storage instance without changing capacity or
/// layout.
@inlinable
internal func copyElements() -> Deque._Storage {
let object = _DequeBuffer<Element>.create(
minimumCapacity: capacity,
makingHeaderWith: { _ in header })
let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object))
guard self.count > 0 else { return result }
result.update { target in
let source = self.segments()
target.initialize(at: startSlot, from: source.first)
if let second = source.second {
target.initialize(at: .zero, from: second)
}
}
return result
}
/// Copy elements into a new storage instance with the specified minimum
/// capacity.
@inlinable
internal func copyElements(minimumCapacity: Int) -> Deque._Storage {
assert(minimumCapacity >= count)
let object = _DequeBuffer<Element>.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: {
_DequeBufferHeader(
capacity: $0.capacity,
count: count,
startSlot: .zero)
})
let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object))
guard count > 0 else { return result }
result.update { target in
assert(target.count == count && target.startSlot.position == 0)
let source = self.segments()
let next = target.initialize(at: .zero, from: source.first)
if let second = source.second {
target.initialize(at: next, from: second)
}
}
return result
}
/// Move elements into a new storage instance with the specified minimum
/// capacity. Existing indices in `self` won't necessarily be valid in the
/// result. `self` is left empty.
@inlinable
internal func moveElements(minimumCapacity: Int) -> Deque._Storage {
assertMutable()
let count = self.count
assert(minimumCapacity >= count)
let object = _DequeBuffer<Element>.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: {
_DequeBufferHeader(
capacity: $0.capacity,
count: count,
startSlot: .zero)
})
let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object))
guard count > 0 else { return result }
result.update { target in
let source = self.mutableSegments()
let next = target.moveInitialize(at: .zero, from: source.first)
if let second = source.second {
target.moveInitialize(at: next, from: second)
}
}
self.count = 0
return result
}
}
extension Deque._UnsafeHandle {
@inlinable
internal func withUnsafeSegment<R>(
startingAt start: Int,
maximumCount: Int?,
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> (end: Int, result: R) {
assert(start <= count)
guard start < count else {
return try (count, body(UnsafeBufferPointer(start: nil, count: 0)))
}
let endSlot = self.endSlot
let segmentStart = self.slot(forOffset: start)
let segmentEnd = segmentStart < endSlot ? endSlot : limSlot
let count = Swift.min(maximumCount ?? Int.max, segmentEnd.position - segmentStart.position)
let result = try body(UnsafeBufferPointer(start: ptr(at: segmentStart), count: count))
return (start + count, result)
}
}
// MARK: Replacement
extension Deque._UnsafeHandle {
/// Replace the elements in `range` with `newElements`. The deque's count must
/// not change as a result of calling this function.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func uncheckedReplaceInPlace<C: Collection>(
inOffsets range: Range<Int>,
with newElements: C
) where C.Element == Element {
assertMutable()
assert(range.upperBound <= count)
assert(newElements.count == range.count)
guard !range.isEmpty else { return }
let target = mutableSegments(forOffsets: range)
target.assign(from: newElements)
}
}
// MARK: Appending
extension Deque._UnsafeHandle {
/// Append `element` to this buffer. The buffer must have enough free capacity
/// to insert one new element.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func uncheckedAppend(_ element: Element) {
assertMutable()
assert(count < capacity)
ptr(at: endSlot).initialize(to: element)
count += 1
}
/// Append the contents of `source` to this buffer. The buffer must have
/// enough free capacity to insert the new elements.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func uncheckedAppend(contentsOf source: UnsafeBufferPointer<Element>) {
assertMutable()
assert(count + source.count <= capacity)
guard source.count > 0 else { return }
let c = self.count
count += source.count
let gap = mutableSegments(forOffsets: c ..< count)
gap.initialize(from: source)
}
}
// MARK: Prepending
extension Deque._UnsafeHandle {
@inlinable
internal func uncheckedPrepend(_ element: Element) {
assertMutable()
assert(count < capacity)
let slot = self.slot(before: startSlot)
ptr(at: slot).initialize(to: element)
startSlot = slot
count += 1
}
/// Prepend the contents of `source` to this buffer. The buffer must have
/// enough free capacity to insert the new elements.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func uncheckedPrepend(contentsOf source: UnsafeBufferPointer<Element>) {
assertMutable()
assert(count + source.count <= capacity)
guard source.count > 0 else { return }
let oldStart = startSlot
let newStart = self.slot(startSlot, offsetBy: -source.count)
startSlot = newStart
count += source.count
let gap = mutableWrappedBuffer(between: newStart, and: oldStart)
gap.initialize(from: source)
}
}
// MARK: Insertion
extension Deque._UnsafeHandle {
/// Insert all elements from `newElements` into this deque, starting at
/// `offset`.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
///
/// - Parameter newElements: The elements to insert.
/// - Parameter newCount: Must be equal to `newElements.count`. Used to
/// prevent calling `count` more than once.
/// - Parameter offset: The desired offset from the start at which to place
/// the first element.
@inlinable
internal func uncheckedInsert<C: Collection>(
contentsOf newElements: __owned C,
count newCount: Int,
atOffset offset: Int
) where C.Element == Element {
assertMutable()
assert(offset <= count)
assert(newElements.count == newCount)
guard newCount > 0 else { return }
let gap = openGap(ofSize: newCount, atOffset: offset)
gap.initialize(from: newElements)
}
@inlinable
internal func mutableWrappedBuffer(
between start: Slot,
and end: Slot
) -> _UnsafeMutableWrappedBuffer<Element> {
assert(start.position <= capacity)
assert(end.position <= capacity)
if start < end {
return .init(start: ptr(at: start), count: end.position - start.position)
}
return .init(
first: ptr(at: start), count: capacity - start.position,
second: ptr(at: .zero), count: end.position)
}
/// Slide elements around so that there is a gap of uninitialized slots of
/// size `gapSize` starting at `offset`, and return a (potentially wrapped)
/// buffer holding the newly inserted slots.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
///
/// - Parameter gapSize: The number of uninitialized slots to create.
/// - Parameter offset: The offset from the start at which the uninitialized
/// slots should start.
@inlinable
internal func openGap(
ofSize gapSize: Int,
atOffset offset: Int
) -> _UnsafeMutableWrappedBuffer<Element> {
assertMutable()
assert(offset >= 0 && offset <= self.count)
assert(self.count + gapSize <= capacity)
assert(gapSize > 0)
let headCount = offset
let tailCount = count - offset
if tailCount <= headCount {
// Open the gap by sliding elements to the right.
let originalEnd = self.slot(startSlot, offsetBy: count)
let newEnd = self.slot(startSlot, offsetBy: count + gapSize)
let gapStart = self.slot(forOffset: offset)
let gapEnd = self.slot(gapStart, offsetBy: gapSize)
let sourceIsContiguous = gapStart <= originalEnd.orIfZero(capacity)
let targetIsContiguous = gapEnd <= newEnd.orIfZero(capacity)
if sourceIsContiguous && targetIsContiguous {
// No need to deal with wrapping; we just need to slide
// elements after the gap.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) ....ABCDE̲F̲G̲H..... EFG̲H̲.̲........ABCD .̲.......ABCDEFGH̲.̲
// 1) ....ABCD.̲.̲.̲EFGH.. EF.̲.̲.̲GH......ABCD .̲H......ABCDEFG.̲.̲
move(from: gapStart, to: gapEnd, count: tailCount)
} else if targetIsContiguous {
// The gap itself will be wrapped.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) E̲FGH.........ABC̲D̲
// 1) .̲..EFGH......ABC̲D̲
// 2) .̲CDEFGH......AB.̲.̲
assert(startSlot > originalEnd.orIfZero(capacity))
move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position)
move(from: gapStart, to: gapEnd, count: capacity - gapStart.position)
} else if sourceIsContiguous {
// Opening the gap pushes subsequent elements across the wrap.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) ........ABC̲D̲E̲FGH.
// 1) GH......ABC̲D̲E̲F...
// 2) GH......AB.̲.̲.̲CDEF
move(from: limSlot.advanced(by: -gapSize), to: .zero, count: newEnd.position)
move(from: gapStart, to: gapEnd, count: tailCount - newEnd.position)
} else {
// The rest of the items are wrapped, and will remain so.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) GH.........AB̲C̲D̲EF
// 1) ...GH......AB̲C̲D̲EF
// 2) DEFGH......AB̲C̲.̲..
// 3) DEFGH......A.̲.̲.̲BC
move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position)
move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize)
move(from: gapStart, to: gapEnd, count: tailCount - gapSize - originalEnd.position)
}
count += gapSize
return mutableWrappedBuffer(between: gapStart, and: gapEnd.orIfZero(capacity))
}
// Open the gap by sliding elements to the left.
let originalStart = self.startSlot
let newStart = self.slot(originalStart, offsetBy: -gapSize)
let gapEnd = self.slot(forOffset: offset)
let gapStart = self.slot(gapEnd, offsetBy: -gapSize)
let sourceIsContiguous = originalStart <= gapEnd.orIfZero(capacity)
let targetIsContiguous = newStart <= gapStart.orIfZero(capacity)
if sourceIsContiguous && targetIsContiguous {
// No need to deal with any wrapping.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) ....A̲B̲C̲DEFGH... GH.........̲A̲B̲CDEF .̲A̲B̲CDEFGH.......̲.̲
// 1) .ABC.̲.̲.̲DEFGH... GH......AB.̲.̲.̲CDEF .̲.̲.̲CDEFGH....AB.̲.̲
move(from: originalStart, to: newStart, count: headCount)
} else if targetIsContiguous {
// The gap itself will be wrapped.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) C̲D̲EFGH.........A̲B̲
// 1) C̲D̲EFGH.....AB...̲.̲
// 2) .̲.̲EFGH.....ABCD.̲.̲
assert(originalStart >= newStart)
move(from: originalStart, to: newStart, count: capacity - originalStart.position)
move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapEnd.position)
} else if sourceIsContiguous {
// Opening the gap pushes preceding elements across the wrap.
// Illustrated steps: (underscores mark eventual gap position)
//
// 0) .AB̲C̲D̲EFGH.........
// 1) ...̲C̲D̲EFGH.......AB
// 2) CD.̲.̲.̲EFGH.......AB
move(from: originalStart, to: newStart, count: capacity - newStart.position)
move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position)
} else {
// The preceding of the items are wrapped, and will remain so.
// Illustrated steps: (underscores mark eventual gap position)
// 0) CD̲E̲F̲GHIJKL.........AB
// 1) CD̲E̲F̲GHIJKL......AB...
// 2) ..̲.̲F̲GHIJKL......ABCDE
// 3) F.̲.̲.̲GHIJKL......ABCDE
move(from: originalStart, to: newStart, count: capacity - originalStart.position)
move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapSize)
move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position)
}
startSlot = newStart
count += gapSize
return mutableWrappedBuffer(between: gapStart, and: gapEnd.orIfZero(capacity))
}
}
// MARK: Removal
extension Deque._UnsafeHandle {
@inlinable
internal func uncheckedRemoveFirst() -> Element {
assertMutable()
assert(count > 0)
let result = ptr(at: startSlot).move()
startSlot = slot(after: startSlot)
count -= 1
return result
}
@inlinable
internal func uncheckedRemoveLast() -> Element {
assertMutable()
assert(count > 0)
let slot = self.slot(forOffset: count - 1)
let result = ptr(at: slot).move()
count -= 1
return result
}
@inlinable
internal func uncheckedRemoveFirst(_ n: Int) {
assertMutable()
assert(count >= n)
guard n > 0 else { return }
let target = mutableSegments(forOffsets: 0 ..< n)
target.deinitialize()
startSlot = slot(startSlot, offsetBy: n)
count -= n
}
@inlinable
internal func uncheckedRemoveLast(_ n: Int) {
assertMutable()
assert(count >= n)
guard n > 0 else { return }
let target = mutableSegments(forOffsets: count - n ..< count)
target.deinitialize()
count -= n
}
/// Remove all elements stored in this instance, deinitializing their storage.
///
/// This method does not ensure that the storage buffer is uniquely
/// referenced.
@inlinable
internal func uncheckedRemoveAll() {
assertMutable()
guard count > 0 else { return }
let target = mutableSegments()
target.deinitialize()
count = 0
startSlot = .zero
}
/// Remove all elements in `bounds`, deinitializing their storage and sliding
/// remaining elements to close the resulting gap.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func uncheckedRemove(offsets bounds: Range<Int>) {
assertMutable()
assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count)
// Deinitialize elements in `bounds`.
mutableSegments(forOffsets: bounds).deinitialize()
closeGap(offsets: bounds)
}
/// Close the gap of already uninitialized elements in `bounds`, sliding
/// elements outside of the gap to eliminate it.
///
/// This function does not validate its input arguments in release builds. Nor
/// does it ensure that the storage buffer is uniquely referenced.
@inlinable
internal func closeGap(offsets bounds: Range<Int>) {
assertMutable()
assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count)
let gapSize = bounds.count
guard gapSize > 0 else { return }
let gapStart = self.slot(forOffset: bounds.lowerBound)
let gapEnd = self.slot(forOffset: bounds.upperBound)
let headCount = bounds.lowerBound
let tailCount = count - bounds.upperBound
if headCount >= tailCount {
// Close the gap by sliding elements to the left.
let originalEnd = endSlot
let newEnd = self.slot(forOffset: count - gapSize)
let sourceIsContiguous = gapEnd < originalEnd.orIfZero(capacity)
let targetIsContiguous = gapStart <= newEnd.orIfZero(capacity)
if tailCount == 0 {
// No need to move any elements.
} else if sourceIsContiguous && targetIsContiguous {
// No need to deal with wrapping.
// 0) ....ABCD.̲.̲.̲EFGH.. EF.̲.̲.̲GH........ABCD .̲.̲.̲E..........ABCD.̲.̲ .̲.̲.̲EF........ABCD .̲.̲.̲DE.......ABC
// 1) ....ABCDE̲F̲G̲H..... EFG̲H̲.̲..........ABCD .̲.̲.̲...........ABCDE̲.̲ E̲F̲.̲..........ABCD D̲E̲.̲.........ABC
move(from: gapEnd, to: gapStart, count: tailCount)
} else if sourceIsContiguous {
// The gap lies across the wrap from the subsequent elements.
// 0) .̲.̲.̲EFGH.......ABCD.̲.̲ EFGH.......ABCD.̲.̲.̲
// 1) .̲.̲.̲..GH.......ABCDE̲F̲ ..GH.......ABCDE̲F̲G̲
// 2) G̲H̲.̲...........ABCDE̲F̲ GH.........ABCDE̲F̲G̲
let c = capacity - gapStart.position
assert(tailCount > c)
let next = move(from: gapEnd, to: gapStart, count: c)
move(from: next.source, to: .zero, count: tailCount - c)
} else if targetIsContiguous {
// We need to move elements across a wrap, but the wrap will
// disappear when we're done.
// 0) HI....ABCDE.̲.̲.̲FG
// 1) HI....ABCDEF̲G̲.̲..
// 2) ......ABCDEF̲G̲H̲I.
let next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position)
move(from: .zero, to: next.target, count: originalEnd.position)
} else {
// We need to move elements across a wrap that won't go away.
// 0) HIJKL....ABCDE.̲.̲.̲FG
// 1) HIJKL....ABCDEF̲G̲.̲..
// 2) ...KL....ABCDEF̲G̲H̲IJ
// 3) KL.......ABCDEF̲G̲H̲IJ
var next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position)
next = move(from: .zero, to: next.target, count: gapSize)
move(from: next.source, to: .zero, count: newEnd.position)
}
count -= gapSize
} else {
// Close the gap by sliding elements to the right.
let originalStart = startSlot
let newStart = slot(startSlot, offsetBy: gapSize)
let sourceIsContiguous = originalStart < gapStart.orIfZero(capacity)
let targetIsContiguous = newStart <= gapEnd.orIfZero(capacity)
if headCount == 0 {
// No need to move any elements.
} else if sourceIsContiguous && targetIsContiguous {
// No need to deal with wrapping.
// 0) ....ABCD.̲.̲.̲EFGH..... EFGH........AB.̲.̲.̲CD .̲.̲.̲CDEFGH.......AB.̲.̲ DEFGH.......ABC.̲.̲
// 1) .......AB̲C̲D̲EFGH..... EFGH...........̲A̲B̲CD .̲A̲B̲CDEFGH..........̲.̲ DEFGH.........AB̲C̲ ABCDEFGH........̲.̲.̲
move(from: originalStart, to: newStart, count: headCount)
} else if sourceIsContiguous {
// The gap lies across the wrap from the preceding elements.
// 0) .̲.̲DEFGH.......ABC.̲.̲ .̲.̲.̲EFGH.......ABCD
// 1) B̲C̲DEFGH.......A...̲.̲ B̲C̲D̲DEFGH......A...
// 2) B̲C̲DEFGH...........̲A̲ B̲C̲D̲DEFGH.........A
move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapEnd.position)
move(from: startSlot, to: newStart, count: headCount - gapEnd.position)
} else if targetIsContiguous {
// We need to move elements across a wrap, but the wrap will
// disappear when we're done.
// 0) CD.̲.̲.̲EFGHI.....AB
// 1) ...̲C̲D̲EFGHI.....AB
// 1) .AB̲C̲D̲EFGHI.......
move(from: .zero, to: gapEnd.advanced(by: -gapStart.position), count: gapStart.position)
move(from: startSlot, to: newStart, count: headCount - gapStart.position)
} else {
// We need to move elements across a wrap that won't go away.
// 0) FG.̲.̲.̲HIJKLMNO....ABCDE
// 1) ...̲F̲G̲HIJKLMNO....ABCDE
// 2) CDE̲F̲G̲HIJKLMNO....AB...
// 3) CDE̲F̲G̲HIJKLMNO.......AB
move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: gapStart.position)
move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize)
move(from: startSlot, to: newStart, count: headCount - gapEnd.position)
}
startSlot = newStart
count -= gapSize
}
}
}
+105
View File
@@ -0,0 +1,105 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A collection implementing a double-ended queue. `Deque` (pronounced "deck")
/// implements an ordered random-access collection that supports efficient
/// insertions and removals from both ends.
///
/// var colors: Deque = ["red", "yellow", "blue"]
///
/// Deques implement the same indexing semantics as arrays: they use integer
/// indices, and the first element of a nonempty deque is always at index zero.
/// Like arrays, deques conform to `RangeReplaceableCollection`,
/// `MutableCollection` and `RandomAccessCollection`, providing a familiar
/// interface for manipulating their contents:
///
/// print(colors[1]) // "yellow"
/// print(colors[3]) // Runtime error: Index out of range
///
/// colors.insert("green", at: 1)
/// // ["red", "green", "yellow", "blue"]
///
/// colors.remove(at: 2) // "yellow"
/// // ["red", "green", "blue"]
///
/// Like all variable-size collections on the standard library, `Deque`
/// implements value semantics: each deque has an independent value that
/// includes the values of its elements. Modifying one deque does not affect any
/// others:
///
/// var copy = deque
/// copy[1] = "violet"
/// print(copy) // ["red", "violet", "blue"]
/// print(deque) // ["red", "green", "blue"]
///
/// This is implemented with the copy-on-write optimization. Multiple copies of
/// a deque share the same underlying storage until you modify one of the
/// copies. When that happens, the deque being modified replaces its storage
/// with a uniquely owned copy of itself, which is then modified in place.
///
/// `Deque` stores its elements in a circular buffer, which allows efficient
/// insertions and removals at both ends of the collection; however, this comes
/// at the cost of potentially discontiguous storage. In contrast, `Array` is
/// (usually) backed by a contiguous buffer, where new data can be efficiently
/// appended to the end, but inserting at the front is relatively slow, as
/// existing elements need to be shifted to make room.
///
/// This difference in implementation means that while the interface of a deque
/// is very similar to an array, the operations have different performance
/// characteristics. Mutations near the front are expected to be significantly
/// faster in deques, but arrays may measure slightly faster for general
/// random-access lookups.
///
/// Deques provide a handful of additional operations that make it easier to
/// insert and remove elements at the front. This includes queue operations such
/// as `popFirst` and `prepend`, including the ability to directly prepend a
/// sequence of elements:
///
/// colors.append("green")
/// colors.prepend("orange")
/// // colors: ["orange", "red", "blue", "yellow", "green"]
///
/// colors.popLast() // "green"
/// colors.popFirst() // "orange"
/// // colors: ["red", "blue", "yellow"]
///
/// colors.prepend(contentsOf: ["purple", "teal"])
/// // colors: ["purple", "teal", "red", "blue", "yellow"]
///
/// Unlike arrays, deques do not currently provide direct unsafe access to their
/// underlying storage. They also lack a `capacity` property -- the size of the
/// storage buffer at any given point is an unstable implementation detail that
/// should not affect application logic. (However, deques do provide a
/// `reserveCapacity` method.)
@frozen
public struct Deque<Element> {
@usableFromInline
internal typealias _Slot = _DequeSlot
@usableFromInline
internal var _storage: _Storage
@inlinable
internal init(_storage: _Storage) {
self._storage = _storage
}
/// Creates and empty deque with preallocated space for at least the specified
/// number of elements.
///
/// - Parameter minimumCapacity: The minimum number of elements that the
/// newly created deque should be able to store without reallocating its
/// storage buffer.
@inlinable
public init(minimumCapacity: Int) {
self._storage = _Storage(minimumCapacity: minimumCapacity)
}
}
@@ -0,0 +1,65 @@
//===----------------------------------------------------------------------===//
//
// 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 Collection {
@inlinable
@inline(__always)
internal func _rebased<Element>() -> UnsafeBufferPointer<Element>
where Self == UnsafeBufferPointer<Element>.SubSequence {
.init(rebasing: self)
}
}
extension Collection {
@inlinable
@inline(__always)
internal func _rebased<Element>() -> UnsafeMutableBufferPointer<Element>
where Self == UnsafeMutableBufferPointer<Element>.SubSequence {
.init(rebasing: self)
}
}
extension UnsafeMutableBufferPointer {
@inlinable
@inline(__always)
internal func _initialize(from source: UnsafeBufferPointer<Element>) {
assert(source.count == count)
guard source.count > 0 else { return }
baseAddress!.initialize(from: source.baseAddress!, count: source.count)
}
@inlinable
@inline(__always)
internal func _initialize<C: Collection>(
from elements: C
) where C.Element == Element {
assert(elements.count == count)
var (it, copied) = elements._copyContents(initializing: self)
precondition(copied == count)
precondition(it.next() == nil)
}
@inlinable
@inline(__always)
internal func _deinitializeAll() {
guard count > 0 else { return }
baseAddress!.deinitialize(count: count)
}
@inlinable
internal func _assign<C: Collection>(
from replacement: C
) where C.Element == Element {
guard self.count > 0 else { return }
self[0 ..< count]._rebased()._deinitializeAll()
_initialize(from: replacement)
}
}
+51
View File
@@ -0,0 +1,51 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@usableFromInline
internal class _DequeBuffer<Element>: ManagedBuffer<_DequeBufferHeader, Element> {
@inlinable
deinit {
let storage = Deque<Element>._Storage(self)
storage.update { handle in
}
self.withUnsafeMutablePointers { header, elements in
header.pointee._checkInvariants()
let capacity = header.pointee.capacity
let count = header.pointee.count
let startSlot = header.pointee.startSlot
if startSlot.position + count <= capacity {
(elements + startSlot.position).deinitialize(count: count)
} else {
let firstRegion = capacity - startSlot.position
(elements + startSlot.position).deinitialize(count: firstRegion)
elements.deinitialize(count: count - firstRegion)
}
}
}
}
extension _DequeBuffer: CustomStringConvertible {
@usableFromInline
internal var description: String {
withUnsafeMutablePointerToHeader { "_DequeStorage<\(Element.self)>\($0.pointee)" }
}
}
/// The type-punned empty singleton storage instance.
@usableFromInline
internal let _emptyDequeStorage = _DequeBuffer<Void>.create(
minimumCapacity: 0,
makingHeaderWith: { _ in
_DequeBufferHeader(capacity: 0, count: 0, startSlot: .init(at: 0))
})
@@ -0,0 +1,49 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@usableFromInline
internal struct _DequeBufferHeader {
@usableFromInline
var capacity: Int
@usableFromInline
var count: Int
@usableFromInline
var startSlot: _DequeSlot
@usableFromInline
init(capacity: Int, count: Int, startSlot: _DequeSlot) {
self.capacity = capacity
self.count = count
self.startSlot = startSlot
_checkInvariants()
}
#if COLLECTIONS_INTERNAL_CHECKS
@usableFromInline @inline(never) @_effects(releasenone)
internal func _checkInvariants() {
precondition(capacity >= 0)
precondition(count >= 0 && count <= capacity)
precondition(startSlot.position >= 0 && startSlot.position <= capacity)
}
#else
@inlinable @inline(__always)
internal func _checkInvariants() {}
#endif // COLLECTIONS_INTERNAL_CHECKS
}
extension _DequeBufferHeader: CustomStringConvertible {
@usableFromInline
internal var description: String {
"(capacity: \(capacity), count: \(count), startSlot: \(startSlot))"
}
}
+72
View File
@@ -0,0 +1,72 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@usableFromInline
@frozen
internal struct _DequeSlot {
@usableFromInline
internal var position: Int
@inlinable
@inline(__always)
init(at position: Int) {
assert(position >= 0)
self.position = position
}
}
extension _DequeSlot {
@inlinable
@inline(__always)
internal static var zero: Self { Self(at: 0) }
@inlinable
@inline(__always)
internal func advanced(by delta: Int) -> Self {
Self(at: position &+ delta)
}
@inlinable
@inline(__always)
internal func orIfZero(_ value: Int) -> Self {
guard position > 0 else { return Self(at: value) }
return self
}
}
extension _DequeSlot: CustomStringConvertible {
@usableFromInline
internal var description: String {
"@\(position)"
}
}
extension _DequeSlot: Equatable {
@inlinable
@inline(__always)
static func ==(left: Self, right: Self) -> Bool {
left.position == right.position
}
}
extension _DequeSlot: Comparable {
@inlinable
@inline(__always)
static func <(left: Self, right: Self) -> Bool {
left.position < right.position
}
}
extension Range where Bound == _DequeSlot {
@inlinable
@inline(__always)
internal var _count: Int { upperBound.position - lowerBound.position }
}
@@ -0,0 +1,215 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@usableFromInline
internal struct _UnsafeWrappedBuffer<Element> {
@usableFromInline
internal let first: UnsafeBufferPointer<Element>
@usableFromInline
internal let second: UnsafeBufferPointer<Element>?
@inlinable
@inline(__always)
internal init(
_ first: UnsafeBufferPointer<Element>,
_ second: UnsafeBufferPointer<Element>? = nil
) {
self.first = first
self.second = second
assert(first.count > 0 || second == nil)
}
@inlinable
internal init(
start: UnsafePointer<Element>,
count: Int
) {
self.init(UnsafeBufferPointer(start: start, count: count))
}
@inlinable
internal init(
first start1: UnsafePointer<Element>,
count count1: Int,
second start2: UnsafePointer<Element>,
count count2: Int
) {
self.init(UnsafeBufferPointer(start: start1, count: count1),
UnsafeBufferPointer(start: start2, count: count2))
}
@inlinable
internal var count: Int { first.count + (second?.count ?? 0) }
}
@usableFromInline
internal struct _UnsafeMutableWrappedBuffer<Element> {
@usableFromInline
internal let first: UnsafeMutableBufferPointer<Element>
@usableFromInline
internal let second: UnsafeMutableBufferPointer<Element>?
@inlinable
@inline(__always)
internal init(
_ first: UnsafeMutableBufferPointer<Element>,
_ second: UnsafeMutableBufferPointer<Element>? = nil
) {
self.first = first
self.second = second?.count == 0 ? nil : second
assert(first.count > 0 || second == nil)
}
@inlinable
@inline(__always)
internal init(
start: UnsafeMutablePointer<Element>,
count: Int
) {
self.init(UnsafeMutableBufferPointer(start: start, count: count))
}
@inlinable
@inline(__always)
internal init(
first start1: UnsafeMutablePointer<Element>,
count count1: Int,
second start2: UnsafeMutablePointer<Element>,
count count2: Int
) {
self.init(UnsafeMutableBufferPointer(start: start1, count: count1),
UnsafeMutableBufferPointer(start: start2, count: count2))
}
@inlinable
@inline(__always)
internal init(mutating buffer: _UnsafeWrappedBuffer<Element>) {
self.init(.init(mutating: buffer.first),
buffer.second.map { .init(mutating: $0) })
}
}
extension _UnsafeMutableWrappedBuffer {
@inlinable
@inline(__always)
internal var count: Int { first.count + (second?.count ?? 0) }
@inlinable
internal func prefix(_ n: Int) -> Self {
assert(n >= 0)
if n >= self.count {
return self
}
if n <= first.count {
return Self(first.prefix(n)._rebased())
}
return Self(first, second!.prefix(n - first.count)._rebased())
}
@inlinable
internal func suffix(_ n: Int) -> Self {
assert(n >= 0)
if n >= self.count {
return self
}
guard let second = second else {
return Self(first.suffix(n)._rebased())
}
if n <= second.count {
return Self(second.suffix(n)._rebased())
}
return Self(first.suffix(n - second.count)._rebased(), second)
}
}
extension _UnsafeMutableWrappedBuffer {
@inlinable
internal func deinitialize() {
first._deinitializeAll()
second?._deinitializeAll()
}
@inlinable
@discardableResult
internal func initialize<I: IteratorProtocol>(
fromPrefixOf iterator: inout I
) -> Int
where I.Element == Element {
var copied = 0
var gap = first
var wrapped = false
while true {
if copied == gap.count {
guard !wrapped, let second = second, second.count > 0 else { break }
gap = second
copied = 0
wrapped = true
}
guard let next = iterator.next() else { break }
(gap.baseAddress! + copied).initialize(to: next)
copied += 1
}
return wrapped ? first.count + copied : copied
}
@inlinable
internal func initialize<S: Sequence>(
fromSequencePrefix elements: __owned S
) -> (iterator: S.Iterator, count: Int)
where S.Element == Element {
guard second == nil || first.count >= elements.underestimatedCount else {
var it = elements.makeIterator()
let copied = initialize(fromPrefixOf: &it)
return (it, copied)
}
// Note: Array._copyContents traps when not given enough space, so we
// need to check if we have enough contiguous space available above.
//
// FIXME: Add suppport for segmented (a.k.a. piecewise contiguous)
// collections to the stdlib.
var (it, copied) = elements._copyContents(initializing: first)
if copied == first.count, let second = second {
var i = 0
while i < second.count {
guard let next = it.next() else { break }
(second.baseAddress! + i).initialize(to: next)
i += 1
}
copied += i
}
return (it, copied)
}
@inlinable
internal func initialize<C: Collection>(
from elements: __owned C
) where C.Element == Element {
assert(self.count == elements.count)
if let second = second {
let wrap = elements.index(elements.startIndex, offsetBy: first.count)
first._initialize(from: elements[..<wrap])
second._initialize(from: elements[wrap...])
} else {
first._initialize(from: elements)
}
}
@inlinable
internal func assign<C: Collection>(
from elements: C
) where C.Element == Element {
assert(elements.count == self.count)
deinitialize()
initialize(from: elements)
}
}