BitArray and BitSet data structures (#83)

* Create Screen Shot 2021-05-17 at 7.15.09 PM.png

* Delete Screen Shot 2021-05-17 at 7.15.09 PM.png

* Create BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Added BitArray as a product to the package

* Update Package.swift

* Update Package.swift

* Update Package.swift

* Update BitArray.swift

* Update Package.swift

* Update Collections.swift

* Update Collections.swift

* Update Package.swift

* Create BitArray.xcscheme

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* build: add a CMake based build system (#42)

Add a CMake based build system to enable bootstrapping the toolchain
with the ability to use Swift Collections in SPM.

* Update BitArray.swift

* Update BitArray.swift

* git: ignore vim swap files (#41)

* Initial conformation to Collection. Lots of faulty code right now

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* Update BitArray.swift

* [Deque] Work around stdlib issue with Array.withContiguousStorageIfAvailable (#44)

Resolves #27.

* [manifest] Ignore CMake files (#47)

The package manager doesn’t like it when it finds unexpected non-source files in source directories.

* [meta] Update dependencies (#48)

(This only affects local development.)

* [Deque][NFC] Remove unused code (#49)

* Changes to support OpenBSD. (#52)

* [cmake] Support amd64 architecture name.

On OpenBSD, "x86_64" is called "amd64", and therefore recognition of this
name is required for the cmake build.

* [cmake] Add missing file.

This is required since, for example, `Deque+Extras` requires
`_withContiguousStorageIfAvailable_SR14663`.

* ManagedBuffer.capacity is unavailable on OpenBSD.

ManagedBuffer requires nonstandard API to implement `capacity` and
subsequently is unavailable on OpenBSD. For portability, just use
`minimumCapacity` on this platform.

* Fixed subscript to have bit manipulations

* Update BitArray.swift

* Update BitArray.swift

* Moved Collection Conformance into appropriate file

* Implements some bit manip

* Fixed issue with endIndex resetting when storage element is full

When an element of the storage array in the BitArray filled, the endIndex would reset to 0, but then would be the correct value at any other time. This was due to a calculation error in endIndex

* Update invalid OrderedDictionary invariant check. (#53)

* Added XCTests, MutableCollection Conformance, Fixed endIndex bug

MutableCollection conformance still has bugs to be fixed
Additionally, the code is still very rough
endIndex had an issue where it was 0 when the array was empty. Fixed this by switching the code for count and endIndex, and making endIndex = 1 when count is 0

* Update BitArrayTests.swift

* Fixed subscript bug

Wouldn't work sometimes when current value was true because the return for `storage[index] & mask` could be anything >= 1, and not == 1, hence resulting in a unwanted toggle of the value. Fixed by comparing a boolean value of the current value to the boolean value of the newValue instead of the integers

* Code clean up ish

* Fixing a small typo on quick help documentation. (#55)

* Modifying Existing Code From Feedback

- `endIndex` corrected
- changed `remaining` in `count` to use ternary operator instead of being a computed local variable
- added `_split` as a helper function to `subscript`
- modified `set{...}` portion of `subscript` and included comments of the different options
- removed `clear()` as `removeAll()` seems to already exist somewhere
- modified unit tests to have a new BitArray for every test instead of a shared one
- Improved `testSubscriptSetOnly()` to hopefully be more thorough

* Added Bitwise Operations (No Tests)

Both mutable and immutable OR, AND, XOR operations

* Mark OrderedSetDiffingTests with availability (#54)

* Added Rough Bitwise Operation UnitTests

* Added BitSet Files

Did not add methods as I know a lot will go in BitStorage, which Im still figuring out

* Beginning implementations for BitSet

* Mutating Bitwise Operations

Performance-UNfriendly starter implementations

* Fixed subscript set mask for the &= operation and changed fatalErrors to preconditions

changed mask on &= operation from 0 to ~mask

* Also corrected subscript set test to fail if mask of 0 was used (instead of ~mask)

* Implemented BitSet with BitArray storage type and some tests

Tests are not yet passing. Pushing early so mentor can see progress
So sorry for waiting to push so late!

* Fixed error in first BitSet test ( which is testAppend() ) so it passes!

* BitSet formUnion initial implementation

* formUnion() test added and implementation modified to pass test

formUnion() is still incomplete and needs more tests atm

* Finished formUnion() for BitSet

* Modified formUnion() to use bit shifts instead

* Initial formIntersection function for BitSet

Untested

* Added an array view for BitSet, fixed BitSet.count bug, added and modified tests

* Initial Cartesian Product implementation and unfinished test

* Update BitArrayConformances.swift

* [CMake] swift-collections → SwiftCollections (#60)

* [CMake] swift-collections → SwiftCollections

This is an integration FIXME for SwiftPM: https://github.com/apple/swift-package-manager/pull/3595#issuecomment-875201764

* [CMake] Generate exports under cmake/modules/SwiftCollectionsConfig.cmake

* Work around another MergeModules crash (#62)

* [utils] Add utility for shuffling sources to help reproduce MergeModules issues

* [Deque] Collapse Sequence/Collection conformances into a single file

The MergeModules phase in the compiler is broken: it isn’t always able to correctly handle circular dependencies across source files, like the ones that keep organically popping up with Sequence/Collection conformances that are defined in separate files.

Such dependencies sometimes triggers a compiler crash, depending on some (unknown) environmental parameters.

Trying to manually find and eliminate these circular dependencies has not proved productive. Instead, roll all Collection conformances into a single, huge source file.

* [Deque] Update CMakeLists

* [test] checkCollection: Don’t pass decreasing indices to distance(from:to:) (#63)

Also, try running the conformance checkers on the minimal collection types to catch similar issues.

* Attempting to make an Index

* First steps in implementing Index struct for BitSet

* Fixed up endIndex

* Last tweaks of tonight

Tomorrow: fix up Index implementations, SetAlgebra, Unit Testing

* Adding index function preconditions

* Altered index(_ index: Index, offsetBy distance: Int) -> Index

* Update BitSetConformances.swift

* Update BitSetBitwiseOperations.swift

* Time for SetAlgebra!

* Transitioning to using CollectionsTestSupport

* Conformance to Set Algebra (without bringing in bitarray methods)

* Overloaded Bitwise Operators on BitArray

* Tilday (bitwiseNOT operations)

* Fixed coding style - 2 space indents

* Initial implementation od initializers

Bug found

* Fixed count bug

* Completed and XCTested BitArray initializers

By"XCTested" I mean using my own XCTests without the thorough CollectionsTestSupport

* Update BitArray.swift

* BitSet Initializers -- XCTested

By "XCTested" I mean not thoroughly tested with the CollectionsTestSupport methods

* BitSet's "custom" SetAlgebra

* contains(Int) and dropExcessFalses() methods for BitSet

* Consistently use UNIT.bitWidth instead of the number 8

This will be useful for benchmarking purposes

* Modified BitArray.swift according to feedback

Also added more typealias consistencies (using `UNIT.max` instead of hardcoded 255)

* Modified BitArray bitwise operations according to feedback

Added overloaded mutating operators

* Modified BitArrayConformances.swift according to feedback

* Modified BitArrayOperations.swift according to feedbacl

* Adjust Bitwise Operations' naming to be consistent with that of the atomics package

* .

* Modified According to Feedback

* testing

* First working test using CollectionsTestSupport

Testing sequence initializer

* All initializer tests for BitArray (except using BitSet)

* Update BitArrayTests.swift

* BitArray Append test

* Improved BitArray append() test to test multiple appends

* Untested remove functions

Also updated any UInt8 usages to use the UNIT typealias instead

* BitArray removeLast() Test

* Update BitArrayTests.swift

* BitArray removeAll() test

* BitArray removeLast(_ rangeSize: Int) function test and bug fix

* BitArray removet(at: Int) tests

Also added test for discardable results for current and existing remove tests

* BitArray removeFirst(_ rangeSize: Int) test implemented and passing

Current method has terrible run time for now as I can't get the optimized version to work yet

* BitArray first and last true index functions TEST and BUG FIX

firstTrueIndex()
lastTrueIndex()

* Failing OR and AND bitwise operations test on BitArray

* Update BitArrayTests.swift

* Update BitArrayTests.swift

* Update BitArrayTests.swift

* PUSHHHHH

* removeFirst(_ rangeSize: Int) optimization/bugFix

* BitArray bitwise operations tests and bug fixes

* BitSet tests, bug fixes, and name changes

sequence init test and bug fix
change "UNIT" to "WORD"

* Update BitArrayTests.swift

* add BitSet layout to test support

* BitSet testExpressibleByArrayLiteralAndArrayLiteralInit()

* testExpressibleByArrayLiteralAndArrayLiteralInit()

* BitSet insert and contains functions test + bug fixes

* forceInsert test for BitSet

* BitSet remove function test and improvements

* Update BitSetSetAlgebra.swift

* BitSet intersection tests and bug fixes

* BitSet symmetricDifference test and bug fix

* starting index test and found interesting bug...

* BitArray init(BitSet) test

* Update BitSetTests.swift

* patch

* bug fix in BitSet index after

* BitSet index before test

* Clean up unneeded code

* Delete BitArrayBenchmarks.swift

* My added, not-working benchmark

* BitSet init from BitArray benchmark

* BiSet insert benchmark

* BitSet forceInsert benchmark

* Passing BitSet index offset by test

I plan to add more to the test to test offsets from indices in the middle and not just start and end

* BitArray testing modification to accommodate varying WORD sizes

* Minor comment clean-up

* Correcting bitset tests for varying WORD sizes

* Headers with License info

* simple set operation comparison

incomplete

* .

* adjustments

* Update BitSetOperations.swift

* Benchmarks and preconditions

* Update BitArrayOperations.swift

* Update BitSetTests.swift

* quick edits

* .

* Documentation for bitwise operations and some initializers

* Testing `==` operator to ensure bug fix

* BitSet SetAlgebra and Operations Documentation

* Update BitSetOperations.swift

Co-authored-by: Saleem Abdulrasool <compnerd@compnerd.org>
Co-authored-by: Karoy Lorentey <klorentey@apple.com>
Co-authored-by: 3405691582 <dsk@google.com>
Co-authored-by: Vihan <vihan_bhargava@apple.com>
Co-authored-by: Rodrigo Kreutz <8869678+rkreutz@users.noreply.github.com>
Co-authored-by: Andrew Monshizadeh <1282845+amonshiz@users.noreply.github.com>
This commit is contained in:
66 files changed
+4107 -969

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
#[[
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
#]]
add_library(DequeModule
_DequeBuffer.swift
_DequeBufferHeader.swift
_DequeSlot.swift
_UnsafeWrappedBuffer.swift
Compatibility.swift
Deque._Storage.swift
Deque._UnsafeHandle.swift
Deque.swift
Deque+Codable.swift
Deque+Collection.swift
Deque+CustomDebugStringConvertible.swift
Deque+CustomReflectable.swift
Deque+CustomStringConvertible.swift
Deque+Equatable.swift
Deque+ExpressibleByArrayLiteral.swift
Deque+Extras.swift
Deque+Hashable.swift
Deque+Testing.swift
UnsafeMutableBufferPointer+Utilities.swift)
set_target_properties(DequeModule PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
_install_target(DequeModule)
set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS DequeModule)
+62
View File
@@ -0,0 +1,62 @@
//===----------------------------------------------------------------------===//
//
// 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 Array {
/// Returns true if `Array.withContiguousStorageIfAvailable` is broken
/// in the stdlib we're currently running on.
///
/// See https://bugs.swift.org/browse/SR-14663.
@inlinable
internal static func _isWCSIABroken() -> Bool {
#if _runtime(_ObjC)
guard _isBridgedVerbatimToObjectiveC(Element.self) else {
// SR-14663 only triggers on array values that are verbatim bridged
// from Objective-C, so it cannot ever trigger for element types
// that aren't verbatim bridged.
return false
}
// SR-14663 was introduced in Swift 5.1. Check if we have a broken stdlib.
// The bug is caused by a bogus precondition inside a non-inlinable stdlib
// method, so to determine if we're affected, we need to check the currently
// running OS version.
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
guard #available(macOS 10.15, iOS 13, watchOS 6, tvOS 13, *) else {
// The OS is too old to be affected by this bug.
return false
}
#endif
// FIXME: When a stdlib is released that contains a fix, add a check for it.
return true
#else
// Platforms that don't have an Objective-C runtime don't have verbatim
// bridged array values, so the bug doesn't apply to them.
return false
#endif
}
}
extension Sequence {
// An adjusted version of the standard `withContiguousStorageIfAvailable`
// method that works around https://bugs.swift.org/browse/SR-14663.
@inlinable
internal func _withContiguousStorageIfAvailable_SR14663<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
if Self.self == Array<Element>.self && Array<Element>._isWCSIABroken() {
return nil
}
return try self.withContiguousStorageIfAvailable(body)
}
}
+901
View File
@@ -0,0 +1,901 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: Sequence {
// Implementation note: we could also use the default `IndexingIterator` here.
// This custom implementation performs direct storage access to eliminate any
// and all index validation overhead. It also optimizes away repeated
// conversions from indices to storage slots.
/// An iterator over the members of a deque.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _storage: Deque._Storage
@usableFromInline
internal var _nextSlot: _Slot
@usableFromInline
internal var _endSlot: _Slot
@inlinable
internal init(_storage: Deque._Storage, start: _Slot, end: _Slot) {
self._storage = _storage
self._nextSlot = start
self._endSlot = end
}
@inlinable
internal init(_base: Deque) {
self = _base._storage.read { handle in
let start = handle.startSlot
let end = Swift.min(start.advanced(by: handle.count), handle.limSlot)
return Self(_storage: _base._storage, start: start, end: end)
}
}
@inlinable
internal init(_base: Deque, from index: Int) {
self = _base._storage.read { handle in
assert(index >= 0 && index <= handle.count)
let start = handle.slot(forOffset: index)
if index == handle.count {
return Self(_storage: _base._storage, start: start, end: start)
}
var end = handle.endSlot
if start >= end { end = handle.limSlot }
return Self(_storage: _base._storage, start: start, end: end)
}
}
@inlinable
@inline(never)
internal mutating func _swapSegment() -> Bool {
assert(_nextSlot == _endSlot)
return _storage.read { handle in
let end = handle.endSlot
if end == .zero || end == _nextSlot {
return false
}
_endSlot = end
_nextSlot = .zero
return true
}
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable
public mutating func next() -> Element? {
if _nextSlot == _endSlot {
guard _swapSegment() else { return nil }
}
assert(_nextSlot < _endSlot)
let slot = _nextSlot
_nextSlot = _nextSlot.advanced(by: 1)
return _storage.read { handle in
return handle.ptr(at: slot).pointee
}
}
}
/// Returns an iterator over the elements of the deque.
///
/// - Complexity: O(1)
@inlinable
public func makeIterator() -> Iterator {
Iterator(_base: self)
}
@inlinable
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
ContiguousArray(unsafeUninitializedCapacity: _storage.count) { target, count in
_storage.read { source in
let segments = source.segments()
let c = segments.first.count
target[..<c]._rebased()._initialize(from: segments.first)
count += segments.first.count
if let second = segments.second {
target[c ..< c + second.count]._rebased()._initialize(from: second)
count += second.count
}
assert(count == source.count)
}
}
}
@inlinable
public __consuming func _copyContents(
initializing target: UnsafeMutableBufferPointer<Element>
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
_storage.read { source in
let segments = source.segments()
let c1 = Swift.min(segments.first.count, target.count)
target[..<c1]._rebased()._initialize(from: segments.first.prefix(c1)._rebased())
guard target.count > c1, let second = segments.second else {
return (Iterator(_base: self, from: c1), c1)
}
let c2 = Swift.min(second.count, target.count - c1)
target[c1 ..< c1 + c2]._rebased()._initialize(from: second.prefix(c2)._rebased())
return (Iterator(_base: self, from: c1 + c2), c1 + c2)
}
}
/// Call `body(b)`, where `b` is an unsafe buffer pointer to the deque's
/// contiguous storage, if available. If the deque's contents aren't stored
/// contiguously, `body` is not called and `nil` is returned. The supplied
/// buffer pointer is only valid for the duration of the call.
///
/// Often, the optimizer can eliminate bounds- and uniqueness-checks within an
/// algorithm, but when that fails, invoking the same algorithm on the unsafe
/// buffer supplied to `body` lets you trade safety for speed.
///
/// - Parameters:
/// - body: The function to invoke.
///
/// - Returns: The value returned by `body`, or `nil` if `body` wasn't called.
///
/// - Complexity: O(1) when this instance has a unique reference to its
/// underlying storage; O(`count`) otherwise.
@inlinable
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try _storage.read { handle in
let endSlot = handle.startSlot.advanced(by: handle.count)
guard endSlot.position <= handle.capacity else { return nil }
return try body(handle.buffer(for: handle.startSlot ..< endSlot))
}
}
}
extension Deque: RandomAccessCollection {
public typealias Index = Int
public typealias SubSequence = Slice<Self>
public typealias Indices = Range<Int>
/// The number of elements in the deque.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var count: Int { _storage.count }
/// The position of the first element in a nonempty deque.
///
/// For an instance of `Deque`, `startIndex` is always zero. If the deque is
/// empty, `startIndex` is equal to `endIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var startIndex: Int { 0 }
/// The deque’s “past the end” position—that is, the position one greater than
/// the last valid subscript argument.
///
/// For an instance of `Deque`, `endIndex` is always equal to its `count`. If
/// the deque is empty, `endIndex` is equal to `startIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var endIndex: Int { count }
/// The indices that are valid for subscripting this deque, in ascending order.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var indices: Range<Int> { 0 ..< count }
/// Returns the position immediately after the given index.
///
/// - Parameter `i`: A valid index of the deque. `i` must be less than
/// `endIndex`.
///
/// - Returns: The next valid index immediately after `i`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func index(after i: Int) -> Int {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
return i + 1
}
/// Replaces the given index with its successor.
///
/// - Parameter `i`: A valid index of the deque. `i` must be less than
/// `endIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func formIndex(after i: inout Int) {
// Note: Like `Array`, index manipulation methods on deques
// don't trap on invalid indices.
// (Indices are still validated on element access.)
i += 1
}
/// Returns the position immediately before the given index.
///
/// - Parameter `i`: A valid index of the deque. `i` must be greater than
/// `startIndex`.
///
/// - Returns: The preceding valid index immediately before `i`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func index(before i: Int) -> Int {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
return i - 1
}
/// Replaces the given index with its predecessor.
///
/// - Parameter `i`: A valid index of the deque. `i` must be greater than `startIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func formIndex(before i: inout Int) {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
i -= 1
}
/// Returns an index that is the specified distance from the given index.
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection.
///
/// - Parameters:
/// - i: A valid index of the deque.
/// - `distance`: The distance by which to offset `i`.
///
/// - Returns: An index offset by `distance` from the index `i`. If `distance`
/// is positive, this is the same value as the result of `distance` calls
/// to `index(after:)`. If `distance` is negative, this is the same value
/// as the result of `abs(distance)` calls to `index(before:)`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func index(_ i: Int, offsetBy distance: Int) -> Int {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
return i + distance
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the deque to use as a limit.
/// If `distance > 0`, then `limit` has no effect it is less than `i`.
/// Likewise, if `distance < 0`, then `limit` has no effect if it is
/// greater than `i`.
///
/// - Returns: An index offset by `distance` from the index `i`, unless that
/// index would be beyond `limit` in the direction of movement. In that
/// case, the method returns `nil`.
///
/// - Complexity: O(1)
@inlinable
public func index(
_ i: Int,
offsetBy distance: Int,
limitedBy limit: Int
) -> Int? {
// Note: Like `Array`, index manipulation methods on deques
// don't trap on invalid indices.
// (Indices are still validated on element access.)
let l = limit - i
if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l {
return nil
}
return i + distance
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection.
///
/// - Returns: The distance between `start` and `end`. If `end` is equal to
/// `start`, the result is zero. Otherwise the result is positive if `end`
/// is greater than `start`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func distance(from start: Int, to end: Int) -> Int {
// Note: Like `Array`, index manipulation method on deques
// don't trap on invalid indices.
// (Indices are still validated on element access.)
return end - start
}
/// Accesses the element at the specified position.
///
/// - Parameters:
/// - index: The position of the element to access. `index` must be greater
/// than or equal to `startIndex` and less than `endIndex`.
///
/// - Complexity: Reading an element from a deque is O(1). Writing is O(1)
/// unless the deque’s storage is shared with another deque, in which case
/// writing is O(`count`).
@inlinable
public subscript(index: Int) -> Element {
get {
precondition(index >= 0 && index < count, "Index out of bounds")
return _storage.read { $0.ptr(at: $0.slot(forOffset: index)).pointee }
}
set {
precondition(index >= 0 && index < count, "Index out of bounds")
_storage.ensureUnique()
_storage.update { handle in
let slot = handle.slot(forOffset: index)
handle.ptr(at: slot).pointee = newValue
}
}
_modify {
precondition(index >= 0 && index < count, "Index out of bounds")
_storage.ensureUnique()
// We technically aren't supposed to escape storage pointers out of a
// managed buffer, so we escape a `(slot, value)` pair instead, leaving
// the corresponding slot temporarily uninitialized.
var (slot, value) = _storage.update { handle -> (_Slot, Element) in
let slot = handle.slot(forOffset: index)
return (slot, handle.ptr(at: slot).move())
}
defer {
_storage.update { handle in
handle.ptr(at: slot).initialize(to: value)
}
}
yield &value
}
}
/// Accesses a contiguous subrange of the deque's elements.
///
/// - Parameters:
/// - bounds: A range of the deque's indices. The bounds of the range must
/// be valid indices of the deque (including the `endIndex`).
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection.
@inlinable
public subscript(bounds: Range<Int>) -> Slice<Self> {
get {
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
"Invalid bounds")
return Slice(base: self, bounds: bounds)
}
set(source) {
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
"Invalid bounds")
self.replaceSubrange(bounds, with: source)
}
}
}
extension Deque: MutableCollection {
/// Exchanges the values at the specified indices of the collection.
///
/// Both parameters must be valid indices of the collection and not equal to
/// `endIndex`. Passing the same index as both `i` and `j` has no effect.
///
/// - Parameters:
/// - i: The index of the first value to swap.
/// - j: The index of the second value to swap.
///
/// - Complexity: O(1) when this instance has a unique reference to its
/// underlying storage; O(`count`) otherwise.
@inlinable
public mutating func swapAt(_ i: Int, _ j: Int) {
precondition(i >= 0 && i < count, "Index out of bounds")
precondition(j >= 0 && j < count, "Index out of bounds")
_storage.ensureUnique()
_storage.update { handle in
let slot1 = handle.slot(forOffset: i)
let slot2 = handle.slot(forOffset: j)
handle.mutableBuffer.swapAt(slot1.position, slot2.position)
}
}
// FIXME: Implement `partition(by:)` by making storage contiguous,
// and partitioning that.
/// Call `body(b)`, where `b` is an unsafe buffer pointer to the deque's
/// mutable contiguous storage. If the deque's contents aren't stored
/// contiguously, `body` is not called and `nil` is returned. The supplied
/// buffer pointer is only valid for the duration of the call.
///
/// Often, the optimizer can eliminate bounds- and uniqueness-checks within an
/// algorithm, but when that fails, invoking the same algorithm on the unsafe
/// buffer supplied to `body` lets you trade safety for speed.
///
/// - Parameters:
/// - body: The function to invoke.
///
/// - Returns: The value returned by `body`, or `nil` if `body` wasn't called.
///
/// - Complexity: O(1) when this instance has a unique reference to its
/// underlying storage; O(`count`) otherwise. (Not counting the call to
/// `body`.)
@inlinable
public mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
_storage.ensureUnique()
return try _storage.update { handle in
let endSlot = handle.startSlot.advanced(by: handle.count)
guard endSlot.position <= handle.capacity else {
// FIXME: Rotate storage such that it becomes contiguous.
return nil
}
let original = handle.mutableBuffer(for: handle.startSlot ..< endSlot)
var extract = original
defer {
precondition(extract.baseAddress == original.baseAddress && extract.count == original.count,
"Closure must not replace the provided buffer")
}
return try body(&extract)
}
}
@inlinable
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try withContiguousMutableStorageIfAvailable(body)
}
}
extension Deque: RangeReplaceableCollection {
/// Creates a new, empty deque.
///
/// 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()
}
/// Reserves enough space to store the specified number of elements.
///
/// If you are adding a known number of elements to a deque, use this method
/// to avoid multiple reallocations. It ensures that the deque has unique
/// storage, with space allocated for at least the requested number of
/// elements.
///
/// - Parameters:
/// - minimumCapacity: The requested number of elements to store.
///
/// - Complexity: O(`count`)
@inlinable
public mutating func reserveCapacity(_ minimumCapacity: Int) {
_storage.ensureUnique(minimumCapacity: minimumCapacity, linearGrowth: true)
}
/// Replaces a range of elements with the elements in the specified
/// collection.
///
/// 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<Int>,
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)
}
}
}
/// 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_SR14663 { 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_SR14663 { 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_SR14663 { 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: Int) {
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: Int
) 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: Int) -> 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<Int>) {
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()
}
}
}
+7 -1
View File
@@ -131,7 +131,7 @@ extension Deque {
/// - SeeAlso: `append(contentsOf:)`
@inlinable
public mutating func prepend<C: Collection>(contentsOf newElements: C) where C.Element == Element {
let done: Void? = newElements.withContiguousStorageIfAvailable { source in
let done: Void? = newElements._withContiguousStorageIfAvailable_SR14663 { source in
_storage.ensureUnique(minimumCapacity: count + source.count)
_storage.update { $0.uncheckedPrepend(contentsOf: source) }
}
@@ -166,6 +166,12 @@ extension Deque {
/// - SeeAlso: `append(contentsOf:)`
@inlinable
public mutating func prepend<S: Sequence>(contentsOf newElements: S) where S.Element == Element {
let done: Void? = newElements._withContiguousStorageIfAvailable_SR14663 { source in
_storage.ensureUnique(minimumCapacity: count + source.count)
_storage.update { $0.uncheckedPrepend(contentsOf: source) }
}
guard done == nil else { return }
let originalCount = self.count
self.append(contentsOf: newElements)
let newCount = self.count
@@ -1,83 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: MutableCollection {
/// Exchanges the values at the specified indices of the collection.
///
/// Both parameters must be valid indices of the collection and not equal to
/// `endIndex`. Passing the same index as both `i` and `j` has no effect.
///
/// - Parameters:
/// - i: The index of the first value to swap.
/// - j: The index of the second value to swap.
///
/// - Complexity: O(1) when this instance has a unique reference to its
/// underlying storage; O(`count`) otherwise.
@inlinable
public mutating func swapAt(_ i: Int, _ j: Int) {
precondition(i >= 0 && i < count, "Index out of bounds")
precondition(j >= 0 && j < count, "Index out of bounds")
_storage.ensureUnique()
_storage.update { handle in
let slot1 = handle.slot(forOffset: i)
let slot2 = handle.slot(forOffset: j)
handle.mutableBuffer.swapAt(slot1.position, slot2.position)
}
}
// FIXME: Implement `partition(by:)` by making storage contiguous,
// and partitioning that.
/// Call `body(b)`, where `b` is an unsafe buffer pointer to the deque's
/// mutable contiguous storage. If the deque's contents aren't stored
/// contiguously, `body` is not called and `nil` is returned. The supplied
/// buffer pointer is only valid for the duration of the call.
///
/// Often, the optimizer can eliminate bounds- and uniqueness-checks within an
/// algorithm, but when that fails, invoking the same algorithm on the unsafe
/// buffer supplied to `body` lets you trade safety for speed.
///
/// - Parameters:
/// - body: The function to invoke.
///
/// - Returns: The value returned by `body`, or `nil` if `body` wasn't called.
///
/// - Complexity: O(1) when this instance has a unique reference to its
/// underlying storage; O(`count`) otherwise. (Not counting the call to
/// `body`.)
@inlinable
public mutating func withContiguousMutableStorageIfAvailable<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
_storage.ensureUnique()
return try _storage.update { handle in
let endSlot = handle.startSlot.advanced(by: handle.count)
guard endSlot.position <= handle.capacity else {
// FIXME: Rotate storage such that it becomes contiguous.
return nil
}
let original = handle.mutableBuffer(for: handle.startSlot ..< endSlot)
var extract = original
defer {
precondition(extract.baseAddress == original.baseAddress && extract.count == original.count,
"Closure must not replace the provided buffer")
}
return try body(&extract)
}
}
@inlinable
public mutating func _withUnsafeMutableBufferPointerIfSupported<R>(
_ body: (inout UnsafeMutableBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try withContiguousMutableStorageIfAvailable(body)
}
}
@@ -1,243 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: RandomAccessCollection {
public typealias Index = Int
public typealias SubSequence = Slice<Self>
/// The number of elements in the deque.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var count: Int { _storage.count }
/// The position of the first element in a nonempty deque.
///
/// For an instance of `Deque`, `startIndex` is always zero. If the deque is
/// empty, `startIndex` is equal to `endIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var startIndex: Int { 0 }
/// The deque’s “past the end” position—that is, the position one greater than
/// the last valid subscript argument.
///
/// For an instance of `Deque`, `endIndex` is always equal to its `count`. If
/// the deque is empty, `endIndex` is equal to `startIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var endIndex: Int { count }
/// Returns the position immediately after the given index.
///
/// - Parameter `i`: A valid index of the deque. `i` must be less than
/// `endIndex`.
///
/// - Returns: The next valid index immediately after `i`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func index(after i: Int) -> Int {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
return i + 1
}
/// Replaces the given index with its successor.
///
/// - Parameter `i`: A valid index of the deque. `i` must be less than
/// `endIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func formIndex(after i: inout Int) {
// Note: Like `Array`, index manipulation methods on deques
// don't trap on invalid indices.
// (Indices are still validated on element access.)
i += 1
}
/// Returns the position immediately before the given index.
///
/// - Parameter `i`: A valid index of the deque. `i` must be greater than
/// `startIndex`.
///
/// - Returns: The preceding valid index immediately before `i`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func index(before i: Int) -> Int {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
return i - 1
}
/// Replaces the given index with its predecessor.
///
/// - Parameter `i`: A valid index of the deque. `i` must be greater than `startIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func formIndex(before i: inout Int) {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
i -= 1
}
/// Returns an index that is the specified distance from the given index.
///
/// The value passed as `distance` must not offset `i` beyond the bounds of
/// the collection.
///
/// - Parameters:
/// - i: A valid index of the deque.
/// - `distance`: The distance by which to offset `i`.
///
/// - Returns: An index offset by `distance` from the index `i`. If `distance`
/// is positive, this is the same value as the result of `distance` calls
/// to `index(after:)`. If `distance` is negative, this is the same value
/// as the result of `abs(distance)` calls to `index(before:)`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func index(_ i: Int, offsetBy distance: Int) -> Int {
// Note: Like `Array`, index manipulation methods on deques don't trap on
// invalid indices. (Indices are still validated on element access.)
return i + distance
}
/// Returns an index that is the specified distance from the given index,
/// unless that distance is beyond a given limiting index.
///
/// - Parameters:
/// - i: A valid index of the array.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the deque to use as a limit.
/// If `distance > 0`, then `limit` has no effect it is less than `i`.
/// Likewise, if `distance < 0`, then `limit` has no effect if it is
/// greater than `i`.
///
/// - Returns: An index offset by `distance` from the index `i`, unless that
/// index would be beyond `limit` in the direction of movement. In that
/// case, the method returns `nil`.
///
/// - Complexity: O(1)
@inlinable
public func index(
_ i: Int,
offsetBy distance: Int,
limitedBy limit: Int
) -> Int? {
// Note: Like `Array`, index manipulation methods on deques
// don't trap on invalid indices.
// (Indices are still validated on element access.)
let l = limit - i
if distance > 0 ? l >= 0 && l < distance : l <= 0 && distance < l {
return nil
}
return i + distance
}
/// Returns the distance between two indices.
///
/// - Parameters:
/// - start: A valid index of the collection.
/// - end: Another valid index of the collection.
///
/// - Returns: The distance between `start` and `end`. If `end` is equal to
/// `start`, the result is zero. Otherwise the result is positive if `end`
/// is greater than `start`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public func distance(from start: Int, to end: Int) -> Int {
// Note: Like `Array`, index manipulation method on deques
// don't trap on invalid indices.
// (Indices are still validated on element access.)
return end - start
}
/// Accesses the element at the specified position.
///
/// - Parameters:
/// - index: The position of the element to access. `index` must be greater
/// than or equal to `startIndex` and less than `endIndex`.
///
/// - Complexity: Reading an element from a deque is O(1). Writing is O(1)
/// unless the deque’s storage is shared with another deque, in which case
/// writing is O(`count`).
@inlinable
public subscript(index: Int) -> Element {
get {
precondition(index >= 0 && index < count, "Index out of bounds")
return _storage.read { $0.ptr(at: $0.slot(forOffset: index)).pointee }
}
set {
precondition(index >= 0 && index < count, "Index out of bounds")
_storage.ensureUnique()
_storage.update { handle in
let slot = handle.slot(forOffset: index)
handle.ptr(at: slot).pointee = newValue
}
}
_modify {
precondition(index >= 0 && index < count, "Index out of bounds")
_storage.ensureUnique()
// We technically aren't supposed to escape storage pointers out of a
// managed buffer, so we escape a `(slot, value)` pair instead, leaving
// the corresponding slot temporarily uninitialized.
var (slot, value) = _storage.update { handle -> (_Slot, Element) in
let slot = handle.slot(forOffset: index)
return (slot, handle.ptr(at: slot).move())
}
defer {
_storage.update { handle in
handle.ptr(at: slot).initialize(to: value)
}
}
yield &value
}
}
/// Accesses a contiguous subrange of the deque's elements.
///
/// - Parameters:
/// - bounds: A range of the deque's indices. The bounds of the range must
/// be valid indices of the deque (including the `endIndex`).
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection.
@inlinable
public subscript(bounds: Range<Int>) -> Slice<Self> {
get {
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
"Invalid bounds")
return Slice(base: self, bounds: bounds)
}
set(source) {
precondition(bounds.lowerBound >= 0 && bounds.upperBound <= count,
"Invalid bounds")
self.replaceSubrange(bounds, with: source)
}
}
}
@@ -1,437 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: 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<Int>,
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: Int) {
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: Int
) 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: Int) -> 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<Int>) {
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
@@ -1,160 +0,0 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension Deque: Sequence {
// Implementation note: we could also use the default `IndexingIterator` here.
// This custom implementation performs direct storage access to eliminate any
// and all index validation overhead. It also optimizes away repeated
// conversions from indices to storage slots.
/// An iterator over the members of a deque.
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _storage: Deque._Storage
@usableFromInline
internal var _nextSlot: _Slot
@usableFromInline
internal var _endSlot: _Slot
@inlinable
internal init(_storage: Deque._Storage, start: _Slot, end: _Slot) {
self._storage = _storage
self._nextSlot = start
self._endSlot = end
}
@inlinable
internal init(_base: Deque) {
self = _base._storage.read { handle in
let start = handle.startSlot
let end = Swift.min(start.advanced(by: handle.count), handle.limSlot)
return Self(_storage: _base._storage, start: start, end: end)
}
}
@inlinable
internal init(_base: Deque, from index: Int) {
assert(index <= _base.count)
self = _base._storage.read { handle in
let start = handle.slot(forOffset: index)
if index == _base.count {
return Self(_storage: _base._storage, start: start, end: start)
}
var end = handle.endSlot
if start >= end { end = handle.limSlot }
return Self(_storage: _base._storage, start: start, end: end)
}
}
@inlinable
@inline(never)
internal mutating func _swapSegment() -> Bool {
assert(_nextSlot == _endSlot)
return _storage.read { handle in
let end = handle.endSlot
if end == .zero || end == _nextSlot {
return false
}
_endSlot = end
_nextSlot = .zero
return true
}
}
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable
public mutating func next() -> Element? {
if _nextSlot == _endSlot {
guard _swapSegment() else { return nil }
}
assert(_nextSlot < _endSlot)
let slot = _nextSlot
_nextSlot = _nextSlot.advanced(by: 1)
return _storage.read { handle in
return handle.ptr(at: slot).pointee
}
}
}
/// Returns an iterator over the elements of the deque.
///
/// - Complexity: O(1)
@inlinable
public func makeIterator() -> Iterator {
Iterator(_base: self)
}
@inlinable
public __consuming func _copyToContiguousArray() -> ContiguousArray<Element> {
ContiguousArray(unsafeUninitializedCapacity: count) { target, count in
_storage.read { source in
let segments = source.segments()
let c = segments.first.count
target[..<c]._rebased()._initialize(from: segments.first)
count += segments.first.count
if let second = segments.second {
target[c ..< c + second.count]._rebased()._initialize(from: second)
count += second.count
}
assert(count == self.count)
}
}
}
@inlinable
public __consuming func _copyContents(
initializing target: UnsafeMutableBufferPointer<Element>
) -> (Iterator, UnsafeMutableBufferPointer<Element>.Index) {
_storage.read { source in
let segments = source.segments()
let c1 = Swift.min(segments.first.count, target.count)
target[..<c1]._rebased()._initialize(from: segments.first.prefix(c1)._rebased())
guard target.count > c1, let second = segments.second else {
return (Iterator(_base: self, from: c1), c1)
}
let c2 = Swift.min(second.count, target.count - c1)
target[c1 ..< c1 + c2]._rebased()._initialize(from: second.prefix(c2)._rebased())
return (Iterator(_base: self, from: c1 + c2), c1 + c2)
}
}
/// Call `body(b)`, where `b` is an unsafe buffer pointer to the deque's
/// contiguous storage, if available. If the deque's contents aren't stored
/// contiguously, `body` is not called and `nil` is returned. The supplied
/// buffer pointer is only valid for the duration of the call.
///
/// Often, the optimizer can eliminate bounds- and uniqueness-checks within an
/// algorithm, but when that fails, invoking the same algorithm on the unsafe
/// buffer supplied to `body` lets you trade safety for speed.
///
/// - Parameters:
/// - body: The function to invoke.
///
/// - Returns: The value returned by `body`, or `nil` if `body` wasn't called.
///
/// - Complexity: O(1) when this instance has a unique reference to its
/// underlying storage; O(`count`) otherwise.
@inlinable
public func withContiguousStorageIfAvailable<R>(
_ body: (UnsafeBufferPointer<Element>) throws -> R
) rethrows -> R? {
return try _storage.read { handle in
let endSlot = handle.startSlot.advanced(by: handle.count)
guard endSlot.position <= handle.capacity else { return nil }
return try body(handle.buffer(for: handle.startSlot ..< endSlot))
}
}
}
+7 -2
View File
@@ -48,8 +48,13 @@ extension Deque._Storage {
internal init(minimumCapacity: Int) {
let object = _DequeBuffer<Element>.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: { object in
_DequeBufferHeader(capacity: object.capacity, count: 0, startSlot: .zero)
makingHeaderWith: {
#if os(OpenBSD)
let capacity = minimumCapacity
#else
let capacity = $0.capacity
#endif
return _DequeBufferHeader(capacity: capacity, count: 0, startSlot: .zero)
})
self.init(_buffer: _Buffer(unsafeBufferObject: object))
}
+14 -4
View File
@@ -298,8 +298,13 @@ extension Deque._UnsafeHandle {
let object = _DequeBuffer<Element>.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: {
_DequeBufferHeader(
capacity: $0.capacity,
#if os(OpenBSD)
let capacity = minimumCapacity
#else
let capacity = $0.capacity
#endif
return _DequeBufferHeader(
capacity: capacity,
count: count,
startSlot: .zero)
})
@@ -327,8 +332,13 @@ extension Deque._UnsafeHandle {
let object = _DequeBuffer<Element>.create(
minimumCapacity: minimumCapacity,
makingHeaderWith: {
_DequeBufferHeader(
capacity: $0.capacity,
#if os(OpenBSD)
let capacity = minimumCapacity
#else
let capacity = $0.capacity
#endif
return _DequeBufferHeader(
capacity: capacity,
count: count,
startSlot: .zero)
})
-3
View File
@@ -13,9 +13,6 @@
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()