diff --git a/Package.swift b/Package.swift index 663276ad..cb91a8ba 100644 --- a/Package.swift +++ b/Package.swift @@ -193,7 +193,7 @@ let targets: [CustomTarget] = [ .target( kind: .testSupport, name: "_CollectionsTestSupport", - dependencies: ["InternalCollectionsUtilities"]), + dependencies: ["InternalCollectionsUtilities", "ContainersPreview"]), .target( kind: .test, name: "CollectionsTestSupportTests", @@ -215,9 +215,27 @@ let targets: [CustomTarget] = [ "UnsafeBitSet/_UnsafeBitSet.swift.gyb", "UnsafeBufferPointer+Extras.swift.gyb", "UnsafeMutableBufferPointer+Extras.swift.gyb", + "UnsafeRawBufferPointer+Extras.swift.gyb", + "UnsafeMutableRawBufferPointer+Extras.swift.gyb", "LifetimeOverride.swift.gyb", ]), + .target( + kind: .exported, + name: "ArrayModule", + dependencies: [ + "InternalCollectionsUtilities", + "ContainersPreview", + ], + exclude: ["CMakeLists.txt"] + ), + .target( + kind: .test, + name: "ArrayTests", + dependencies: [ + "ArrayModule", "_CollectionsTestSupport" + ]), + .target( kind: .exported, name: "BitCollections", diff --git a/Sources/ArrayModule/CMakeLists.txt b/Sources/ArrayModule/CMakeLists.txt new file mode 100644 index 00000000..cd2dc1e3 --- /dev/null +++ b/Sources/ArrayModule/CMakeLists.txt @@ -0,0 +1,28 @@ +#[[ +This source file is part of the Swift Collections Open Source Project + +Copyright (c) 2022 - 2025 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 +#]] + +if(COLLECTIONS_SINGLE_MODULE) + set(module_name ${COLLECTIONS_MODULE_NAME}) +else() + set(module_name ArrayModule) + add_library(ArrayModule + ${COLLECTIONS_ARRAY_SOURCES}) + target_link_libraries(ArrayModule PRIVATE + InternalCollectionsUtilities ContainersPreview) + set_target_properties(ArrayModule PROPERTIES + INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY}) + + _install_target(ArrayModule) + set_property(GLOBAL APPEND PROPERTY SWIFT_COLLECTIONS_EXPORTS ArrayModule) +endif() + +target_sources(${module_name} PRIVATE + "DynamicArray.swift" + "RigidArray.swift" +) diff --git a/Sources/ArrayModule/DynamicArray.swift b/Sources/ArrayModule/DynamicArray.swift new file mode 100644 index 00000000..549b7703 --- /dev/null +++ b/Sources/ArrayModule/DynamicArray.swift @@ -0,0 +1,1044 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 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 +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + +#if compiler(<6.2) +/// A dynamically self-resizing, heap allocated, noncopyable array +/// of potentially noncopyable elements. +@frozen +@available(*, unavailable, message: "DynamicArray requires a Swift 6.2 toolchain") +public struct DynamicArray: ~Copyable { + @usableFromInline + internal var _storage: RigidArray + + @inlinable + public init() { + fatalError() + } +} + +#else + +/// A dynamically self-resizing, heap allocated, noncopyable array of +/// potentially noncopyable elements. +/// +/// `DynamicArray` instances automatically resize their underlying storage as +/// needed to accommodate newly inserted items, using a geometric growth curve. +/// This frees code using `DynamicArray` from having to allocate enough +/// capacity in advance; on the other hand, it makes it difficult to tell +/// when and where such reallocations may happen. +/// +/// For example, appending an element to a dynamic array has highly variable +/// complexity; often, it runs at a constant cost, but if the operation has to +/// resize storage, then the cost of an individual append suddenly becomes +/// proportional to the size of the whole array. +/// +/// The geometric growth curve allows the cost of such latency spikes to +/// get amortized across repeated invocations, bringing the average cost back +/// to O(1); but they make this construct less suitable for use cases that +/// expect predictable, consistent performance on every operation. +/// +/// Implicit growth also makes it more difficult to predict/analyze the amount +/// of memory an algorithm would need. Developers targeting environments with +/// stringent limits on heap allocations may prefer to avoid using dynamically +/// resizing array types as a matter of policy. The type `RigidArray` provides +/// a fixed-capacity array variant that caters specifically for these use cases, +/// trading ease-of-use for more consistent/predictable execution. +@frozen +public struct DynamicArray: ~Copyable { + @usableFromInline + internal var _storage: RigidArray + + @inlinable + public init() { + _storage = .init(capacity: 0) + } +} +extension DynamicArray: Sendable where Element: Sendable & ~Copyable {} + +//MARK: - Initializers + +extension DynamicArray where Element: ~Copyable { + @inlinable + public init(capacity: Int) { + _storage = .init(capacity: capacity) + } +} + +extension DynamicArray where Element: ~Copyable { + @available(SwiftStdlib 5.0, *) + @inlinable + public init( + capacity: Int, + initializedWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + self.init(capacity: capacity) + try edit(body) + } +} + +extension DynamicArray where Element: ~Copyable { + @inlinable + public init(consuming storage: consuming RigidArray) { + self._storage = storage + } +} + +extension DynamicArray /*where Element: Copyable*/ { + /// Creates a new array containing the specified number of a single, + /// repeated value. + /// + /// - Parameters: + /// - repeatedValue: The element to repeat. + /// - count: The number of times to repeat the value passed in the + /// `repeating` parameter. `count` must be zero or greater. + public init(repeating repeatedValue: Element, count: Int) { + self.init(consuming: RigidArray(repeating: repeatedValue, count: count)) + } +} + +extension DynamicArray /*where Element: Copyable*/ { + @_alwaysEmitIntoClient + @inline(__always) + public init(capacity: Int? = nil, copying contents: some Sequence) { + self.init(capacity: capacity ?? 0) + self.append(copying: contents) + } +} + +//MARK: - Basics + +extension DynamicArray where Element: ~Copyable { + @inlinable + @inline(__always) + public var capacity: Int { _storage.capacity } + + @inlinable + @inline(__always) + public var freeCapacity: Int { _storage.capacity - _storage.count } +} + +//MARK: - Span creation + +extension DynamicArray where Element: ~Copyable { + @available(SwiftStdlib 6.2, *) + public var span: Span { + @_lifetime(borrow self) + @inlinable + get { + _storage.span + } + } + + @available(SwiftStdlib 6.2, *) + public var mutableSpan: MutableSpan { + @_lifetime(&self) + @inlinable + mutating get { + _storage.mutableSpan + } + } +} + +extension DynamicArray where Element: ~Copyable { + /// Arbitrarily edit the storage underlying this array by invoking a + /// user-supplied closure with a mutable `OutputSpan` view over it. + /// This method calls its function argument precisely once, allowing it to + /// arbitrarily modify the contents of the output span it is given. + /// The argument is free to add, remove or reorder any items; however, + /// it is not allowed to replace the span or change its capacity. + /// + /// When the function argument finishes (whether by returning or throwing an + /// error) the rigid array instance is updated to match the final contents of + /// the output span. + /// + /// - Parameter body: A function that edits the contents of this array through + /// an `OutputSpan` argument. This method invokes this function + /// precisely once. + /// - Returns: This method returns the result of its function argument. + /// - Complexity: Adds O(1) overhead to the complexity of the function + /// argument. + @available(SwiftStdlib 5.0, *) + @inlinable @inline(__always) + public mutating func edit( + _ body: (inout OutputSpan) throws(E) -> R + ) throws(E) -> R { + try _storage.edit(body) + } +} + +//MARK: - Random-access & mutable container primitives + +extension DynamicArray where Element: ~Copyable { + public typealias Index = Int + + @inlinable + @inline(__always) + public var isEmpty: Bool { _storage.isEmpty } + + @inlinable + @inline(__always) + public var count: Int { _storage.count } + + @inlinable + @inline(__always) + public var startIndex: Int { _storage.startIndex } + + @inlinable + @inline(__always) + public var endIndex: Int { _storage.count } + + @inlinable + @inline(__always) + public var indices: Range { _storage.indices } + + @inlinable + public subscript(position: Int) -> Element { + unsafeAddress { + _storage._ptr(to: position) + } + unsafeMutableAddress { + _storage._mutablePtr(to: position) + } + } +} + +extension DynamicArray where Element: ~Copyable { + @inlinable + public mutating func swapAt(_ i: Int, _ j: Int) { + _storage.swapAt(i, j) + } +} + +extension DynamicArray where Element: ~Copyable { + @available(SwiftStdlib 5.0, *) + @inlinable + @_lifetime(borrow self) + public func span(after index: inout Int) -> Span { + _storage.span(after: &index) + } + + @available(SwiftStdlib 5.0, *) + @inlinable + @_lifetime(borrow self) + public func span(before index: inout Int) -> Span { + _storage.span(before: &index) + } +} + +extension DynamicArray where Element: ~Copyable { + @available(SwiftStdlib 5.0, *) + @_lifetime(&self) + public mutating func mutableSpan( + after index: inout Int + ) -> MutableSpan { + _storage.mutableSpan(after: &index) + } + + @available(SwiftStdlib 5.0, *) + @_lifetime(&self) + public mutating func mutableSpan( + before index: inout Int + ) -> MutableSpan { + _storage.mutableSpan(before: &index) + } +} + +//MARK: - Resizing + +@inlinable +@_transparent +internal func _growDynamicArrayCapacity(_ capacity: Int) -> Int { + 2 * capacity +} + +extension DynamicArray where Element: ~Copyable { + @inlinable @inline(never) + public mutating func reallocate(capacity: Int) { + _storage.reallocate(capacity: capacity) + } + + @inlinable @inline(never) + public mutating func reserveCapacity(_ n: Int) { + _storage.reserveCapacity(n) + } + + @inlinable + @_transparent + public mutating func _ensureFreeCapacity(_ freeCapacity: Int) { + guard _storage.freeCapacity < freeCapacity else { return } + _ensureFreeCapacitySlow(freeCapacity) + } + + @inlinable + @_transparent + internal func _grow(freeCapacity: Int) -> Int { + Swift.max( + count + freeCapacity, + _growDynamicArrayCapacity(capacity)) + } + + @inlinable + internal mutating func _ensureFreeCapacitySlow(_ freeCapacity: Int) { + let newCapacity = _grow(freeCapacity: freeCapacity) + reallocate(capacity: newCapacity) + } +} + +//MARK: - Removal operations + +extension DynamicArray where Element: ~Copyable { + /// Removes all elements from the array, optionally preserving its + /// allocated capacity. + /// + /// - Complexity: O(*n*), where *n* is the original count of the array. + @inlinable + @inline(__always) + public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + if keepCapacity { + _storage.removeAll() + } else { + _storage = RigidArray(capacity: 0) + } + } + + /// Removes and returns the last element of the array. + /// + /// The array must not be empty. + /// + /// - Returns: The last element of the original array. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + @discardableResult + public mutating func removeLast() -> Element { + _storage.removeLast() + } + + /// Removes and discards the specified number of elements from the end of the + /// array. + /// + /// Attempting to remove more elements than exist in the array triggers a + /// runtime error. + /// + /// - Parameter k: The number of elements to remove from the array. + /// `k` must be greater than or equal to zero and must not exceed + /// the count of the array. + /// + /// - Complexity: O(`k`) + @inlinable + public mutating func removeLast(_ k: Int) { + _storage.removeLast(k) + } + + /// Removes and returns the element at the specified position. + /// + /// All the elements following the specified position are moved to close the + /// gap. + /// + /// - Parameter i: The position of the element to remove. `index` must be + /// a valid index of the array that is not equal to the end index. + /// - Returns: The removed element. + /// + /// - Complexity: O(`self.count`) + @inlinable + @inline(__always) + @discardableResult + public mutating func remove(at index: Int) -> Element { + _storage.remove(at: index) + } + + /// Removes the specified subrange of elements from the array. + /// + /// All the elements following the specified subrange are moved to close the + /// resulting gap. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds + /// of the range must be valid indices of the array. + /// + /// - Complexity: O(`self.count`) + @inlinable + public mutating func removeSubrange(_ bounds: Range) { + _storage.removeSubrange(bounds) + } + + /// Removes the specified subrange of elements from the array. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds + /// of the range must be valid indices of the array. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + public mutating func removeSubrange(_ bounds: some RangeExpression) { + // FIXME: Remove this in favor of a standard algorithm. + removeSubrange(bounds.relative(to: indices)) + } +} + +extension DynamicArray where Element: ~Copyable { + /// Removes and returns the last element of the array, if there is one. + /// + /// - Returns: The last element of the array if the array is not empty; + /// otherwise, `nil`. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + public mutating func popLast() -> Element? { + if isEmpty { return nil } + return removeLast() + } +} + +//MARK: - Append operations + +extension DynamicArray where Element: ~Copyable { + /// Adds an element to the end of the array. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this reallocates the array's storage to grow its capacity. + /// + /// - Parameter item: The element to append to the collection. + /// + /// - Complexity: O(1) when amortized over many invocations on the same array + @inlinable + public mutating func append(_ item: consuming Element) { + _ensureFreeCapacity(1) + _storage.append(item) + } +} + +extension DynamicArray where Element: ~Copyable { + /// Moves the elements of a buffer to the end of this array, leaving the + /// buffer uninitialized. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this reallocates the array's storage to grow its capacity. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`items.count`) when amortized over many invocations on + /// the same array + @_alwaysEmitIntoClient + public mutating func append( + moving items: UnsafeMutableBufferPointer + ) { + _ensureFreeCapacity(items.count) + _storage.append(moving: items) + } + + /// Appends the elements of a given array to the end of this array by moving + /// them between the containers. On return, the input array becomes empty, but + /// it is not destroyed, and it preserves its original storage capacity. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this automatically grows the target array's + /// capacity. + /// + /// - Parameters + /// - items: An array whose items to move to the end of this array. + /// + /// - Complexity: O(`items.count`) when amortized over many invocations on + /// the same array + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout RigidArray + ) { + // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers + _ensureFreeCapacity(items.count) + _storage.append(moving: &items) + } +} + +extension DynamicArray where Element: ~Copyable { + /// Appends the elements of a given container to the end of this array by + /// consuming the source container. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this triggers a runtime error. + /// + /// - Parameters + /// - items: An array whose items to move to the end of this array. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + consuming items: consuming RigidArray + ) { + // FIXME: Remove this in favor of a generic algorithm over consumable containers + var items = items + self.append(moving: &items) + } +} + +extension DynamicArray { + /// Copies the elements of a buffer to the end of this array. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: A fully initialized buffer whose contents to copy into + /// the array. + /// + /// - Complexity: O(`newElements.count`) when amortized over many + /// invocations on the same array. + @_alwaysEmitIntoClient + public mutating func append( + copying newElements: UnsafeBufferPointer + ) { + _ensureFreeCapacity(newElements.count) + unsafe _storage.append(copying: newElements) + } + + /// Copies the elements of a buffer to the end of this array. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: A fully initialized buffer whose contents to copy into + /// the array. + /// + /// - Complexity: O(`newElements.count`) when amortized over many + /// invocations on the same array. + @_alwaysEmitIntoClient + public mutating func append( + copying newElements: UnsafeMutableBufferPointer + ) { + unsafe self.append(copying: UnsafeBufferPointer(newElements)) + } + + /// Copies the elements of a span to the end of this array. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: A span whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`) when amortized over many + /// invocations on the same array. + @available(SwiftStdlib 6.2, *) + @_alwaysEmitIntoClient + public mutating func append(copying newElements: Span) { + _ensureFreeCapacity(newElements.count) + _storage.append(copying: newElements) + } + + /// Copies the elements of a sequence to the end of this array. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. This + /// reallocation can happen multiple times. + /// + /// - Parameters + /// - newElements: The new elements to copy into the array. + /// + /// - Complexity: O(*m*), where *m* is the length of `newElements`, when + /// amortized over many invocations over the same array. + @_alwaysEmitIntoClient + public mutating func append(copying newElements: some Sequence) { + let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in + _ensureFreeCapacity(buffer.count) + unsafe _storage.append(copying: buffer) + return + } + if done != nil { return } + + _ensureFreeCapacity(newElements.underestimatedCount) + var it = _storage._append(prefixOf: newElements) + while let item = it.next() { + _ensureFreeCapacity(1) + _storage.append(item) + } + } +} + +//MARK: - Insert operations + +extension DynamicArray where Element: ~Copyable { + /// Inserts a new element into the array at the specified position. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this reallocates storage to extend its capacity. + /// + /// The new element is inserted before the element currently at the specified + /// index. If you pass the array's `endIndex` as the `index` parameter, then + /// the new element is appended to the container. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// - Parameter item: The new element to insert into the array. + /// - Parameter i: The position at which to insert the new element. + /// `index` must be a valid index in the array. + /// + /// - Complexity: O(`self.count`) + @inlinable + public mutating func insert(_ item: consuming Element, at index: Int) { + precondition(index >= 0 && index <= count) + // FIXME: Avoiding moving the subsequent elements twice. + _ensureFreeCapacity(1) + _storage.insert(item, at: index) + } +} + +extension DynamicArray where Element: ~Copyable { + /// Moves the elements of a fully initialized buffer into this array, + /// starting at the specified position, and leaving the buffer + /// uninitialized. + /// + /// If the array does not have sufficient capacity to hold all elements, + /// then this reallocates storage to extend its capacity. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: UnsafeMutableBufferPointer, + at index: Int + ) { + // FIXME: Avoiding moving the subsequent elements twice. + _ensureFreeCapacity(items.count) + _storage.insert(moving: items, at: index) + } + + /// Inserts the elements of a given array into the given position in this + /// array by moving them between the containers. On return, the input array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// If the array does not have sufficient capacity to hold all elements, + /// then this reallocates storage to extend its capacity. + /// + /// - Parameters + /// - items: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout RigidArray, + at index: Int + ) { + // FIXME: Avoiding moving the subsequent elements twice. + _ensureFreeCapacity(items.count) + _storage.insert(moving: &items, at: index) + } +} + +extension DynamicArray where Element: ~Copyable { + /// Inserts the elements of a given array into the given position in this + /// array by consuming the source container. + /// + /// If the array does not have sufficient capacity to hold all elements, + /// then this reallocates storage to extend its capacity. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + consuming items: consuming RigidArray, + at index: Int + ) { + // FIXME: Avoiding moving the subsequent elements twice. + _ensureFreeCapacity(items.count) + _storage.insert(consuming: items, at: index) + } +} + +extension DynamicArray { + /// Copyies the elements of a fully initialized buffer pointer into this + /// array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeBufferPointer, at index: Int + ) { + // FIXME: Avoiding moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count) + unsafe _storage.insert(copying: newElements, at: index) + } + + /// Copyies the elements of a fully initialized buffer pointer into this + /// array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeMutableBufferPointer, + at index: Int + ) { + unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) + } + + /// Copies the elements of a span into this array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @available(SwiftStdlib 6.2, *) + @inlinable + public mutating func insert( + copying newElements: Span, at index: Int + ) { + // FIXME: Avoiding moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count) + _storage.insert(copying: newElements, at: index) + } + + /// Copies the elements of a collection into this array at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved + /// to make room for the new item. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: some Collection, at index: Int + ) { + // FIXME: Avoiding moving the subsequent elements twice. + let newCount = newElements.count + _ensureFreeCapacity(newCount) + _storage._insertCollection( + at: index, copying: newElements, newCount: newCount) + } +} + +//MARK: - Range replacement + +extension DynamicArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// fully initialized buffer into their place. On return, the buffer is left + /// in an uninitialized state. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: UnsafeMutableBufferPointer, + ) { + // FIXME: Avoiding moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count - subrange.count) + _storage.replaceSubrange(subrange, moving: newElements) + } + + /// Replaces the specified range of elements by moving the elements of a + /// another array into their place. On return, the source array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: inout RigidArray, + ) { + // FIXME: Avoiding moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count - subrange.count) + _storage.replaceSubrange(subrange, moving: &newElements) + } +} + +extension DynamicArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// given array into their place, consuming it in the process. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + consuming newElements: consuming RigidArray, + ) { + replaceSubrange(subrange, moving: &newElements) + } +} + +extension DynamicArray { + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeBufferPointer + ) { + // FIXME: Avoiding moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count) + unsafe _storage.replaceSubrange(subrange, copying: newElements) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeMutableBufferPointer + ) { + unsafe self.replaceSubrange( + subrange, copying: UnsafeBufferPointer(newElements)) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given span. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length span as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @available(SwiftStdlib 6.2, *) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: Span + ) { + // FIXME: Avoiding moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count) + _storage.replaceSubrange(subrange, copying: newElements) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given collection. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same location. + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length collection as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: __owned some Collection + ) { + // FIXME: Avoiding moving the subsequent elements twice. + let c = newElements.count + _ensureFreeCapacity(c) + _storage._replaceSubrange( + subrange, copyingCollection: newElements, newCount: c) + } +} +#endif diff --git a/Sources/ArrayModule/RigidArray.swift b/Sources/ArrayModule/RigidArray.swift new file mode 100644 index 00000000..4282367b --- /dev/null +++ b/Sources/ArrayModule/RigidArray.swift @@ -0,0 +1,1361 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 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 +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + + +#if compiler(<6.2) +/// A fixed capacity, heap allocated, noncopyable array of potentially +/// noncopyable elements. +@frozen +@available(*, unavailable, message: "RigidArray requires a Swift 6.2 toolchain") +public struct RigidArray: ~Copyable { + @usableFromInline + internal var _storage: UnsafeMutableBufferPointer + + @usableFromInline + internal var _count: Int + + deinit { + _storage.extracting(0 ..< _count).deinitialize() + _storage.deallocate() + } + + public init() { + fatalError() + } +} + +#else + +/// A fixed capacity, heap allocated, noncopyable array of potentially +/// noncopyable elements. +/// +/// `RigidArray` instances are created with a certain maximum capacity. Elements +/// can be added to the array up to that capacity, but no more: trying to add an +/// item to a full array results in a runtime trap. +/// +/// var items = RigidArray(capacity: 2) +/// items.append(1) +/// items.append(2) +/// items.append(3) // Runtime error: RigidArray capacity overflow +/// +/// Rigid arrays provide convenience properties to help verify that it has +/// enough available capacity: `isFull` and `freeCapacity`. +/// +/// guard items.freeCapacity >= 4 else { throw CapacityOverflow() } +/// items.append(copying: newItems) +/// +/// It is possible to extend or shrink the capacity of a rigid array instance, +/// but this needs to be done explicitly, with operations dedicated to this +/// purpose (such as ``reserveCapacity`` and ``reallocate(capacity:)``). +/// The array never resizes itself automatically. +/// +/// It therefore requires careful manual analysis or up front runtime capacity +/// checks to prevent the array from overflowing its storage. This makes +/// this type more difficult to use than a dynamic array. However, it allows +/// this construct to provide predictably stable performance. +/// +/// This trading of usability in favor of stable performance limits `RigidArray` +/// to the most resource-constrained of use cases, such as space-constrained +/// environments that require carefully accounting of every heap allocation, or +/// time-constrained applications that cannot accommodate unexpected latency +/// spikes due to a reallocation getting triggered at an inopportune moment. +/// +/// For use cases outside of these narrow domains, we generally recommmend +/// the use of ``DynamicArray`` rather than `RigidArray`. +@safe +@frozen +public struct RigidArray: ~Copyable { + @usableFromInline + internal var _storage: UnsafeMutableBufferPointer + + @usableFromInline + internal var _count: Int + + deinit { + unsafe _storage.extracting(0 ..< _count).deinitialize() + unsafe _storage.deallocate() + } + + /// Initializes a new rigid array with the specified capacity and no elements. + @inlinable + public init(capacity: Int) { + precondition(capacity >= 0, "Array capacity must be nonnegative") + if capacity > 0 { + unsafe _storage = .allocate(capacity: capacity) + } else { + unsafe _storage = .init(start: nil, count: 0) + } + _count = 0 + } + + /// Initializes a new rigid array with zero capacity and no elements. + @inlinable + public init() { + unsafe _storage = .init(start: nil, count: 0) + _count = 0 + } +} +extension RigidArray: @unchecked Sendable where Element: Sendable & ~Copyable {} + +//MARK: - Initializers + +extension RigidArray where Element: ~Copyable { + @available(SwiftStdlib 5.0, *) + @inlinable + public init( + capacity: Int, + initializedWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + self.init(capacity: capacity) + try edit(body) + } +} + +extension RigidArray /*where Element: Copyable*/ { + /// Creates a new array containing the specified number of a single, + /// repeated value. + /// + /// - Parameters: + /// - repeatedValue: The element to repeat. + /// - count: The number of times to repeat the value passed in the + /// `repeating` parameter. `count` must be zero or greater. + public init(repeating repeatedValue: Element, count: Int) { + self.init(capacity: count) + unsafe _freeSpace.initialize(repeating: repeatedValue) + _count = count + } +} + +extension RigidArray /*where Element: Copyable*/ { + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int, + copying contents: some Sequence + ) { + self.init(capacity: capacity) + self.append(copying: contents) + } + + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int? = nil, + copying contents: some Collection + ) { + self.init(capacity: capacity ?? contents.count) + self.append(copying: contents) + } +} + +// FIXME: init(moving:), init(consuming:) + +//MARK: - Basics + +extension RigidArray where Element: ~Copyable { + @inlinable + @inline(__always) + public var capacity: Int { unsafe _storage.count } + + @inlinable + @inline(__always) + public var freeCapacity: Int { capacity - count } + + @inlinable + @inline(__always) + public var isFull: Bool { freeCapacity == 0 } +} + +extension RigidArray where Element: ~Copyable { + @inlinable + internal var _items: UnsafeMutableBufferPointer { + unsafe _storage.extracting(Range(uncheckedBounds: (0, _count))) + } + + @inlinable + internal var _freeSpace: UnsafeMutableBufferPointer { + unsafe _storage.extracting(Range(uncheckedBounds: (_count, capacity))) + } +} + +//MARK: - Span creation + +extension RigidArray where Element: ~Copyable { + @available(SwiftStdlib 5.0, *) + public var span: Span { + @_lifetime(borrow self) + @inlinable + get { + let result = unsafe Span(_unsafeElements: _items) + return unsafe _overrideLifetime(result, borrowing: self) + } + } + + @available(SwiftStdlib 5.0, *) + public var mutableSpan: MutableSpan { + @_lifetime(&self) + @inlinable + mutating get { + let result = unsafe MutableSpan(_unsafeElements: _items) + return unsafe _overrideLifetime(result, mutating: &self) + } + } + + @available(SwiftStdlib 5.0, *) + @inlinable + @_lifetime(borrow self) + internal func _span(in range: Range) -> Span { + span.extracting(range) + } + + @available(SwiftStdlib 5.0, *) + @inlinable + @_lifetime(&self) + internal mutating func _mutableSpan( + in range: Range + ) -> MutableSpan { + let result = unsafe MutableSpan(_unsafeElements: _items.extracting(range)) + return unsafe _overrideLifetime(result, mutating: &self) + } +} + +extension RigidArray where Element: ~Copyable { + /// Arbitrarily edit the storage underlying this array by invoking a + /// user-supplied closure with a mutable `OutputSpan` view over it. + /// This method calls its function argument precisely once, allowing it to + /// arbitrarily modify the contents of the output span it is given. + /// The argument is free to add, remove or reorder any items; however, + /// it is not allowed to replace the span or change its capacity. + /// + /// When the function argument finishes (whether by returning or throwing an + /// error) the rigid array instance is updated to match the final contents of + /// the output span. + /// + /// - Parameter body: A function that edits the contents of this array through + /// an `OutputSpan` argument. This method invokes this function + /// precisely once. + /// - Returns: This method returns the result of its function argument. + /// - Complexity: Adds O(1) overhead to the complexity of the function + /// argument. + @available(SwiftStdlib 5.0, *) + @inlinable + public mutating func edit( + _ body: (inout OutputSpan) throws(E) -> R + ) throws(E) -> R { + var span = OutputSpan(buffer: _storage, initializedCount: _count) + defer { + _count = span.finalize(for: _storage) + span = OutputSpan() + } + return try body(&span) + } + + // FIXME: Stop using and remove this in favor of `edit` + @unsafe + @inlinable + internal mutating func _unsafeEdit( + _ body: (UnsafeMutableBufferPointer, inout Int) throws(E) -> R + ) throws(E) -> R { + defer { precondition(_count >= 0 && _count <= capacity) } + return unsafe try body(_storage, &_count) + } +} + +extension RigidArray where Element: ~Copyable { + @inlinable + internal func _contiguousSubrange(following index: inout Int) -> Range { + precondition(index >= 0 && index <= _count, "Index out of bounds") + defer { index = _count } + return unsafe Range(uncheckedBounds: (index, _count)) + } + + @inlinable + internal func _contiguousSubrange(preceding index: inout Int) -> Range { + precondition(index >= 0 && index <= _count, "Index out of bounds") + defer { index = 0 } + return unsafe Range(uncheckedBounds: (0, index)) + } +} + +//MARK: - Random-access & mutable container primitives + +extension RigidArray where Element: ~Copyable { + public typealias Index = Int + + @inlinable + @inline(__always) + public var isEmpty: Bool { count == 0 } + + @inlinable + @inline(__always) + public var count: Int { _count } + + @inlinable + @inline(__always) + public var startIndex: Int { 0 } + + @inlinable + @inline(__always) + public var endIndex: Int { count } + + @inlinable + @inline(__always) + public var indices: Range { unsafe Range(uncheckedBounds: (0, count)) } +} + +extension RigidArray where Element: ~Copyable { + @inlinable @inline(__always) + internal func _ptr(to index: Int) -> UnsafePointer { + precondition(index >= 0 && index < _count, "Index out of bounds") + let p = _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) + return UnsafePointer(p) + } + + @inlinable @inline(__always) + internal mutating func _mutablePtr( + to index: Int + ) -> UnsafeMutablePointer { + precondition(index >= 0 && index < _count, "Index out of bounds") + return _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) + } + + @inlinable + public subscript(position: Int) -> Element { + unsafeAddress { + _ptr(to: position) + } + unsafeMutableAddress { + _mutablePtr(to: position) + } + } +} + +extension RigidArray where Element: ~Copyable { + @inlinable + public mutating func swapAt(_ i: Int, _ j: Int) { + precondition( + i >= 0 && i < _count && j >= 0 && j < _count, + "Index out of bounds") + unsafe _items.swapAt(i, j) + } +} + +extension RigidArray where Element: ~Copyable { + @available(SwiftStdlib 5.0, *) + @inlinable + @_lifetime(borrow self) + public func span(after index: inout Int) -> Span { + _span(in: _contiguousSubrange(following: &index)) + } + + @available(SwiftStdlib 5.0, *) + @inlinable + @_lifetime(borrow self) + public func span(before index: inout Int) -> Span { + _span(in: _contiguousSubrange(preceding: &index)) + } +} + +extension RigidArray where Element: ~Copyable { + @available(SwiftStdlib 5.0, *) + @_lifetime(&self) + public mutating func mutableSpan( + after index: inout Int + ) -> MutableSpan { + _mutableSpan(in: _contiguousSubrange(following: &index)) + } + + @available(SwiftStdlib 5.0, *) + @_lifetime(&self) + public mutating func mutableSpan( + before index: inout Int + ) -> MutableSpan { + _mutableSpan(in: _contiguousSubrange(preceding: &index)) + } +} + +//MARK: - Resizing + +extension RigidArray where Element: ~Copyable { + @inlinable + public mutating func reallocate(capacity newCapacity: Int) { + precondition(newCapacity >= count, "RigidArray capacity overflow") + guard newCapacity != capacity else { return } + let newStorage: UnsafeMutableBufferPointer = .allocate( + capacity: newCapacity) + let i = unsafe newStorage.moveInitialize(fromContentsOf: self._items) + assert(i == count) + unsafe _storage.deallocate() + unsafe _storage = newStorage + } + + @inlinable + public mutating func reserveCapacity(_ n: Int) { + guard capacity < n else { return } + reallocate(capacity: n) + } +} + +//MARK: - Copying helpers + +extension RigidArray { + @inlinable + public func copy() -> Self { + copy(capacity: capacity) + } + + @inlinable + public func copy(capacity: Int) -> Self { + precondition(capacity >= count, "RigidArray capacity overflow") + var result = RigidArray(capacity: capacity) + let initialized = unsafe result._storage.initialize(fromContentsOf: _items) + precondition(initialized == count) + result._count = count + return result + } +} + + +//MARK: - Opening and closing gaps + +extension RigidArray where Element: ~Copyable { + @inlinable + internal mutating func _closeGap( + at index: Int, count: Int + ) { + guard count > 0 else { return } + let source = unsafe _storage.extracting( + Range(uncheckedBounds: (index + count, _count))) + let target = unsafe _storage.extracting( + Range(uncheckedBounds: (index, index + source.count))) + let i = unsafe target.moveInitialize(fromContentsOf: source) + assert(i == target.endIndex) + } + + @inlinable + @unsafe + internal mutating func _openGap( + at index: Int, count: Int + ) -> UnsafeMutableBufferPointer { + assert(index >= 0 && index <= _count) + assert(count <= freeCapacity) + guard count > 0 else { return unsafe _storage.extracting(index ..< index) } + let source = unsafe _storage.extracting( + Range(uncheckedBounds: (index, _count))) + let target = unsafe _storage.extracting( + Range(uncheckedBounds: (index + count, _count + count))) + let i = unsafe target.moveInitialize(fromContentsOf: source) + assert(i == target.count) + return unsafe _storage.extracting( + Range(uncheckedBounds: (index, index + count))) + } +} + +//MARK: - Removal operations + +extension RigidArray where Element: ~Copyable { + /// Removes all elements from the array, preserving its allocated capacity. + /// + /// - Complexity: O(*n*), where *n* is the original count of the array. + @inlinable + public mutating func removeAll() { + unsafe _items.deinitialize() + _count = 0 + } + + /// Removes and returns the last element of the array. + /// + /// The array must not be empty. + /// + /// - Returns: The last element of the original array. + /// + /// - Complexity: O(1) + @inlinable + @discardableResult + public mutating func removeLast() -> Element { + precondition(!isEmpty, "Cannot remove last element from an empty array") + let old = unsafe _storage.moveElement(from: _count - 1) + _count -= 1 + return old + } + + /// Removes and discards the specified number of elements from the end of the + /// array. + /// + /// Attempting to remove more elements than exist in the array + /// triggers a runtime error. + /// + /// - Parameter k: The number of elements to remove from the array. + /// `k` must be greater than or equal to zero and must not exceed + /// the count of the array. + /// + /// - Complexity: O(`k`) + @inlinable + public mutating func removeLast(_ k: Int) { + if k == 0 { return } + precondition( + k >= 0 && k <= _count, + "Count of elements to remove is out of bounds") + unsafe _storage.extracting( + Range(uncheckedBounds: (_count - k, _count)) + ).deinitialize() + _count &-= k + } + + /// Removes and returns the element at the specified position. + /// + /// All the elements following the specified position are moved to close the + /// gap. + /// + /// - Parameter i: The position of the element to remove. `index` must be + /// a valid index of the array that is not equal to the end index. + /// - Returns: The removed element. + /// + /// - Complexity: O(`count`) + @inlinable + @discardableResult + public mutating func remove(at index: Int) -> Element { + precondition(index >= 0 && index < _count, "Index out of bounds") + let old = unsafe _storage.moveElement(from: index) + _closeGap(at: index, count: 1) + _count -= 1 + return old + } + + /// Removes the specified subrange of elements from the array. + /// + /// All the elements following the specified subrange are moved to close the + /// resulting gap. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds + /// of the range must be valid indices of the array. + /// + /// - Complexity: O(`count`) + @inlinable + public mutating func removeSubrange(_ bounds: Range) { + precondition( + bounds.lowerBound >= 0 && bounds.upperBound <= _count, + "Subrange out of bounds") + guard !bounds.isEmpty else { return } + unsafe _storage.extracting(bounds).deinitialize() + _closeGap(at: bounds.lowerBound, count: bounds.count) + _count -= bounds.count + } + + /// Removes the specified subrange of elements from the array. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds of the + /// range must be valid indices of the array. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + public mutating func removeSubrange(_ bounds: some RangeExpression) { + // FIXME: Remove this in favor of a standard algorithm. + removeSubrange(bounds.relative(to: indices)) + } +} + +extension RigidArray where Element: ~Copyable { + /// Removes and returns the last element of the array, if there is one. + /// + /// - Returns: The last element of the array if the array is not empty; + /// otherwise, `nil`. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + public mutating func popLast() -> Element? { + // FIXME: Remove this in favor of a standard algorithm. + if isEmpty { return nil } + return removeLast() + } +} + +//MARK: - Append operations + +extension RigidArray where Element: ~Copyable { + /// Adds an element to the end of the array. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this triggers a runtime error. + /// + /// - Parameter item: The element to append to the collection. + /// + /// - Complexity: O(1) + @inlinable + public mutating func append(_ item: consuming Element) { + precondition(!isFull, "RigidArray capacity overflow") + unsafe _storage.initializeElement(at: _count, to: item) + _count &+= 1 + } + + /// Adds an element to the end of the array, if possible. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this returns the given item without appending it; otherwise it + /// returns nil. + /// + /// - Parameter item: The element to append to the collection. + /// - Returns: `item` if the array is full; otherwise nil. + /// + /// - Complexity: O(1) + @inlinable + public mutating func pushLast(_ item: consuming Element) -> Element? { + // FIXME: Remove this in favor of a standard algorithm. + if isFull { return item } + append(item) + return nil + } +} + +extension RigidArray where Element: ~Copyable { + /// Moves the elements of a buffer to the end of this array, leaving the + /// buffer uninitialized. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + moving items: UnsafeMutableBufferPointer + ) { + precondition(items.count <= freeCapacity, "RigidArray capacity overflow") + guard items.count > 0 else { return } + let c = unsafe _freeSpace._moveInitializePrefix(from: items) + assert(c == items.count) + _count &+= items.count + } + + /// Appends the elements of a given array to the end of this array by moving + /// them between the containers. On return, the input array becomes empty, but + /// it is not destroyed, and it preserves its original storage capacity. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this triggers a runtime error. + /// + /// - Parameters + /// - items: An array whose items to move to the end of this array. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout RigidArray + ) { + // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers + unsafe items._unsafeEdit { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.append(moving: source) + count = 0 + } + } +} + +extension RigidArray where Element: ~Copyable { + /// Appends the elements of a given container to the end of this array by + /// consuming the source container. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this triggers a runtime error. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + consuming items: consuming RigidArray + ) { + // FIXME: Remove this in favor of a generic algorithm over consumable containers + var items = items + self.append(moving: &items) + } +} + +extension RigidArray { + /// Copies the elements of a buffer to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A fully initialized buffer whose contents to copy into + /// the array. + /// + /// - Complexity: O(`newElements.count`) + @_alwaysEmitIntoClient + public mutating func append( + copying newElements: UnsafeBufferPointer + ) { + precondition( + newElements.count <= freeCapacity, + "RigidArray capacity overflow") + guard newElements.count > 0 else { return } + unsafe _freeSpace.baseAddress.unsafelyUnwrapped.initialize( + from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count) + _count &+= newElements.count + } + + /// Copies the elements of a buffer to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A fully initialized buffer whose contents to copy into + /// the array. + /// + /// - Complexity: O(`newElements.count`) + @_alwaysEmitIntoClient + public mutating func append( + copying items: UnsafeMutableBufferPointer + ) { + unsafe self.append(copying: UnsafeBufferPointer(items)) + } + + /// Copies the elements of a span to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// span, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A span whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`) + @available(SwiftStdlib 5.0, *) + @_alwaysEmitIntoClient + public mutating func append(copying items: Span) { + unsafe items.withUnsafeBufferPointer { source in + unsafe self.append(copying: source) + } + } + + @_alwaysEmitIntoClient + @inline(__always) + internal mutating func _append>( + prefixOf items: S + ) -> S.Iterator { + let (it, c) = unsafe items._copyContents(initializing: _freeSpace) + _count += c + return it + } + + /// Copies the elements of a sequence to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// sequence, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to copy into the array. + /// + /// - Complexity: O(*m*), where *m* is the length of `newElements`. + @_alwaysEmitIntoClient + public mutating func append(copying newElements: some Sequence) { + let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in + unsafe self.append(copying: buffer) + return + } + if done != nil { return } + + var it = self._append(prefixOf: newElements) + precondition(it.next() == nil, "RigidArray capacity overflow") + } +} + +//MARK: - Insert operations + + +extension RigidArray where Element: ~Copyable { + /// Inserts a new element into the array at the specified position. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this triggers a runtime error. + /// + /// The new element is inserted before the element currently at the specified + /// index. If you pass the array's `endIndex` as the `index` parameter, then + /// the new element is appended to the container. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// - Parameter item: The new element to insert into the array. + /// - Parameter i: The position at which to insert the new element. + /// `index` must be a valid index in the array. + /// + /// - Complexity: O(`count`) + @inlinable + public mutating func insert(_ item: consuming Element, at index: Int) { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(!isFull, "RigidArray capacity overflow") + if index < count { + let source = unsafe _storage.extracting(index ..< count) + let target = unsafe _storage.extracting(index + 1 ..< count + 1) + let last = unsafe target.moveInitialize(fromContentsOf: source) + assert(last == target.endIndex) + } + unsafe _storage.initializeElement(at: index, to: item) + _count += 1 + } +} + +extension RigidArray where Element: ~Copyable { + /// Moves the elements of a fully initialized buffer into this array, + /// starting at the specified position, and leaving the buffer + /// uninitialized. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: UnsafeMutableBufferPointer, + at index: Int + ) { + precondition(items.count <= freeCapacity, "RigidArray capacity overflow") + guard items.count > 0 else { return } + let target = unsafe _openGap(at: index, count: items.count) + let c = unsafe target._moveInitializePrefix(from: items) + assert(c == items.count) + _count &+= items.count + } + + /// Inserts the elements of a given array into the given position in this + /// array by moving them between the containers. On return, the input array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this triggers a runtime error. + /// + /// - Parameters + /// - items: An array whose contents to move into `self`. + /// + /// - Complexity: O(`count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout RigidArray, + at index: Int + ) { + precondition(items.count <= freeCapacity, "RigidArray capacity overflow") + guard items.count > 0 else { return } + unsafe items._unsafeEdit { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.insert(moving: source, at: index) + count = 0 + } + } +} + +extension RigidArray where Element: ~Copyable { + /// Inserts the elements of a given array into the given position in this + /// array by consuming the source container. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this triggers a runtime error. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + consuming items: consuming RigidArray, + at index: Int + ) { + var items = items + self.insert(moving: &items, at: index) + } +} + +extension RigidArray { + /// Copies the elements of a fully initialized buffer pointer into this + /// array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeBufferPointer, at index: Int + ) { + guard newElements.count > 0 else { return } + precondition( + newElements.count <= freeCapacity, + "RigidArray capacity overflow") + let gap = unsafe _openGap(at: index, count: newElements.count) + unsafe gap.baseAddress.unsafelyUnwrapped.initialize( + from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count) + _count += newElements.count + } + + /// Copies the elements of a fully initialized buffer pointer into this + /// array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeMutableBufferPointer, + at index: Int + ) { + unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) + } + + /// Copies the elements of a span into this array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`count` + `newElements.count`) + @available(SwiftStdlib 5.0, *) + @inlinable + public mutating func insert( + copying newElements: Span, at index: Int + ) { + unsafe newElements.withUnsafeBufferPointer { + unsafe self.insert(copying: $0, at: index) + } + } + + @inlinable + internal mutating func _insertCollection( + at index: Int, + copying items: some Collection, + newCount: Int + ) { + precondition(index >= 0 && index <= _count, "Index out of bounds") + precondition(newCount <= freeCapacity, "RigidArray capacity overflow") + let gap = unsafe _openGap(at: index, count: newCount) + + let done: Void? = items.withContiguousStorageIfAvailable { buffer in + let i = unsafe gap._initializePrefix(copying: buffer) + precondition( + i == newCount, + "Broken Collection: count doesn't match contents") + _count += newCount + } + if done != nil { return } + + var (it, copied) = unsafe items._copyContents(initializing: gap) + precondition( + it.next() == nil && copied == newCount, + "Broken Collection: count doesn't match contents") + _count += newCount + } + + /// Copies the elements of a collection into this array at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved + /// to make room for the new item. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + @inline(__always) + public mutating func insert( + copying newElements: some Collection, at index: Int + ) { + _insertCollection( + at: index, copying: newElements, newCount: newElements.count) + } +} + +//MARK: - Range replacement + +extension RigidArray where Element: ~Copyable { + /// Perform a range replacement up to populating the newly opened gap. This + /// deinitializes existing elements in the specified subrange, rearranges + /// following elements to be at their final location, and sets the container's + /// new count. + /// + /// - Returns: A buffer pointer addressing the newly opened gap, to be + /// initialized by the caller. + @inlinable + @unsafe + internal mutating func _gapForReplacement( + of subrange: Range, withNewCount newCount: Int + ) -> UnsafeMutableBufferPointer { + // FIXME: Replace this with a public variant based on OutputSpan. + precondition( + subrange.lowerBound >= 0 && subrange.upperBound <= _count, + "Index range out of bounds") + precondition( + newCount - subrange.count <= freeCapacity, + "RigidArray capacity overflow") + unsafe _items.extracting(subrange).deinitialize() + if newCount > subrange.count { + _ = unsafe _openGap( + at: subrange.upperBound, count: newCount - subrange.count) + } else if newCount < subrange.count { + _closeGap( + at: subrange.lowerBound + newCount, count: subrange.count - newCount) + } + _count += newCount - subrange.count + let gapRange = unsafe Range( + uncheckedBounds: (subrange.lowerBound, subrange.lowerBound + newCount)) + return unsafe _storage.extracting(gapRange) + } +} + +extension RigidArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// fully initialized buffer into their place. On return, the buffer is left + /// in an uninitialized state. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: UnsafeMutableBufferPointer, + ) { + let gap = unsafe _gapForReplacement( + of: subrange, withNewCount: newElements.count) + let c = unsafe gap._moveInitializePrefix(from: newElements) + assert(c == newElements.count) + } + + /// Replaces the specified range of elements by moving the elements of a + /// another array into their place. On return, the source array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: inout RigidArray, + ) { + unsafe newElements._unsafeEdit { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.replaceSubrange(subrange, moving: source) + count = 0 + } + } +} + +extension RigidArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// given array into their place, consuming it in the process. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + consuming newElements: consuming RigidArray, + ) { + replaceSubrange(subrange, moving: &newElements) + } +} + +extension RigidArray { + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeBufferPointer + ) { + let gap = unsafe _gapForReplacement( + of: subrange, withNewCount: newElements.count) + let i = unsafe gap._initializePrefix(copying: newElements) + assert(i == gap.count) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeMutableBufferPointer + ) { + unsafe self.replaceSubrange( + subrange, + copying: UnsafeBufferPointer(newElements)) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given span. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length span as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @available(SwiftStdlib 5.0, *) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: Span + ) { + unsafe newElements.withUnsafeBufferPointer { buffer in + unsafe self.replaceSubrange(subrange, copying: buffer) + } + } + + @inlinable + internal mutating func _replaceSubrange( + _ subrange: Range, + copyingCollection newElements: __owned some Collection, + newCount: Int + ) { + let gap = unsafe _gapForReplacement(of: subrange, withNewCount: newCount) + + let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in + let i = unsafe gap._initializePrefix(copying: buffer) + precondition( + i == newCount, + "Broken Collection: count doesn't match contents") + } + if done != nil { return } + + var (it, copied) = unsafe newElements._copyContents(initializing: gap) + precondition( + it.next() == nil && copied == newCount, + "Broken Collection: count doesn't match contents") + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given collection. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length collection as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: __owned some Collection + ) { + _replaceSubrange( + subrange, copyingCollection: newElements, newCount: newElements.count) + } +} +#endif diff --git a/Sources/CMakeLists.txt b/Sources/CMakeLists.txt index 7bb196d6..e98233cb 100644 --- a/Sources/CMakeLists.txt +++ b/Sources/CMakeLists.txt @@ -58,6 +58,7 @@ endif() add_subdirectory(InternalCollectionsUtilities) add_subdirectory(ContainersPreview) if(NOT COLLECTIONS_FOUNDATION_TOOLCHAIN_MODULE) + add_subdirectory(ArrayModule) add_subdirectory(BitCollections) add_subdirectory(HashTreeCollections) add_subdirectory(HeapModule) diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb index adc1b50c..29553931 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb +++ b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb @@ -73,6 +73,131 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { return extracting(Range(uncheckedBounds: (count - newCount, count))) } } + +extension UnsafeMutableBufferPointer where Element: ~Copyable { + @inlinable + ${modifier} func _moveInitializePrefix( + from source: UnsafeMutableBufferPointer + ) -> Int { + if source.isEmpty { return 0 } + precondition(source.count <= self.count) + self.baseAddress.unsafelyUnwrapped.moveInitialize( + from: source.baseAddress.unsafelyUnwrapped, count: source.count) + return source.count + } +} + +extension UnsafeMutableBufferPointer { + /// Initialize slots at the start of this buffer by copying data from `source`. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized, while `source` must be fully initialized. + /// + /// The `source` buffer must fit entirely in `self`. + /// + /// - Returns: The index after the last item that was initialized in this buffer. + @inlinable + ${modifier} func _initializePrefix( + copying source: UnsafeBufferPointer + ) -> Int { + if source.isEmpty { return 0 } + precondition(source.count <= self.count) + self.baseAddress.unsafelyUnwrapped.initialize( + from: source.baseAddress.unsafelyUnwrapped, count: source.count) + return source.count + } + + @inlinable + ${modifier} func _initializePrefix( + copying source: UnsafeMutableBufferPointer + ) -> Int { + _initializePrefix(copying: UnsafeBufferPointer(source)) + } + +#if compiler(>=6.2) + /// Initialize slots at the start of this buffer by copying data from `source`. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized. + /// + /// The `source` span must fit entirely in `self`. + /// + /// - Returns: The index after the last item that was initialized in this buffer. + @available(SwiftStdlib 6.2, *) + @inlinable + ${modifier} func _initializePrefix(copying source: Span) -> Int { + source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } + } +#endif + +#if compiler(>=6.2) && FIXME + /// Initialize all slots in this buffer by copying data from `items`, which must fit entirely + /// in this buffer. + /// + /// If `items` contains more elements than can fit into this buffer, then this function + /// will return an index other than `items.endIndex`. In that case, `self` may not be fully + /// populated. + /// + /// If `Element` is not bitwise copyable, then this function must be called on an + /// entirely uninitialized buffer. + /// + /// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were + /// successfully initialized, and `end` is the index into `items` after the last copied item. + @available(SwiftStdlib 6.2, *) + @inlinable + ${modifier} func _initializePrefix< + C: Container & ~Copyable & ~Escapable + >( + copying items: borrowing C + ) -> (copied: Int, end: C.Index) { + var target = self + var i = items.startIndex + while true { + let start = i + let span = items.span(after: &i) + if span.isEmpty { break } + guard span.count <= target.count else { + return (self.count - target.count, start) + } + target._initializeAndDropPrefix(copying: span) + } + return (self.count - target.count, i) + } +#endif + + /// Initialize slots at the start of this buffer by copying data from `buffer`, then + /// shrink `self` to drop all initialized items from its front, leaving it addressing the + /// uninitialized remainder. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized, while `buffer` must be fully initialized. + /// + /// The count of `buffer` must not be greater than `self.count`. + @inlinable + ${modifier} mutating func _initializeAndDropPrefix(copying source: UnsafeBufferPointer) { + let i = _initializePrefix(copying: source) + self = self.extracting(i...) + } + +#if compiler(>=6.2) + /// Initialize slots at the start of this buffer by copying data from `span`, then + /// shrink `self` to drop all initialized items from its front, leaving it addressing the + /// uninitialized remainder. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized. + /// + /// The count of `span` must not be greater than `self.count`. + @available(SwiftStdlib 5.0, *) + @inlinable + ${modifier} mutating func _initializeAndDropPrefix(copying span: Span) { + span.withUnsafeBufferPointer { buffer in + self._initializeAndDropPrefix(copying: buffer) + } + } +#endif +} + extension UnsafeMutableBufferPointer { @inlinable ${modifier} func initialize(fromContentsOf source: Self) -> Index { diff --git a/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift index dd833474..568b9fed 100644 --- a/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift @@ -79,6 +79,131 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { return extracting(Range(uncheckedBounds: (count - newCount, count))) } } + +extension UnsafeMutableBufferPointer where Element: ~Copyable { + @inlinable + internal func _moveInitializePrefix( + from source: UnsafeMutableBufferPointer + ) -> Int { + if source.isEmpty { return 0 } + precondition(source.count <= self.count) + self.baseAddress.unsafelyUnwrapped.moveInitialize( + from: source.baseAddress.unsafelyUnwrapped, count: source.count) + return source.count + } +} + +extension UnsafeMutableBufferPointer { + /// Initialize slots at the start of this buffer by copying data from `source`. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized, while `source` must be fully initialized. + /// + /// The `source` buffer must fit entirely in `self`. + /// + /// - Returns: The index after the last item that was initialized in this buffer. + @inlinable + internal func _initializePrefix( + copying source: UnsafeBufferPointer + ) -> Int { + if source.isEmpty { return 0 } + precondition(source.count <= self.count) + self.baseAddress.unsafelyUnwrapped.initialize( + from: source.baseAddress.unsafelyUnwrapped, count: source.count) + return source.count + } + + @inlinable + internal func _initializePrefix( + copying source: UnsafeMutableBufferPointer + ) -> Int { + _initializePrefix(copying: UnsafeBufferPointer(source)) + } + +#if compiler(>=6.2) + /// Initialize slots at the start of this buffer by copying data from `source`. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized. + /// + /// The `source` span must fit entirely in `self`. + /// + /// - Returns: The index after the last item that was initialized in this buffer. + @available(SwiftStdlib 6.2, *) + @inlinable + internal func _initializePrefix(copying source: Span) -> Int { + source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } + } +#endif + +#if compiler(>=6.2) && FIXME + /// Initialize all slots in this buffer by copying data from `items`, which must fit entirely + /// in this buffer. + /// + /// If `items` contains more elements than can fit into this buffer, then this function + /// will return an index other than `items.endIndex`. In that case, `self` may not be fully + /// populated. + /// + /// If `Element` is not bitwise copyable, then this function must be called on an + /// entirely uninitialized buffer. + /// + /// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were + /// successfully initialized, and `end` is the index into `items` after the last copied item. + @available(SwiftStdlib 6.2, *) + @inlinable + internal func _initializePrefix< + C: Container & ~Copyable & ~Escapable + >( + copying items: borrowing C + ) -> (copied: Int, end: C.Index) { + var target = self + var i = items.startIndex + while true { + let start = i + let span = items.span(after: &i) + if span.isEmpty { break } + guard span.count <= target.count else { + return (self.count - target.count, start) + } + target._initializeAndDropPrefix(copying: span) + } + return (self.count - target.count, i) + } +#endif + + /// Initialize slots at the start of this buffer by copying data from `buffer`, then + /// shrink `self` to drop all initialized items from its front, leaving it addressing the + /// uninitialized remainder. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized, while `buffer` must be fully initialized. + /// + /// The count of `buffer` must not be greater than `self.count`. + @inlinable + internal mutating func _initializeAndDropPrefix(copying source: UnsafeBufferPointer) { + let i = _initializePrefix(copying: source) + self = self.extracting(i...) + } + +#if compiler(>=6.2) + /// Initialize slots at the start of this buffer by copying data from `span`, then + /// shrink `self` to drop all initialized items from its front, leaving it addressing the + /// uninitialized remainder. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized. + /// + /// The count of `span` must not be greater than `self.count`. + @available(SwiftStdlib 5.0, *) + @inlinable + internal mutating func _initializeAndDropPrefix(copying span: Span) { + span.withUnsafeBufferPointer { buffer in + self._initializeAndDropPrefix(copying: buffer) + } + } +#endif +} + extension UnsafeMutableBufferPointer { @inlinable internal func initialize(fromContentsOf source: Self) -> Index { @@ -263,6 +388,131 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { return extracting(Range(uncheckedBounds: (count - newCount, count))) } } + +extension UnsafeMutableBufferPointer where Element: ~Copyable { + @inlinable + public func _moveInitializePrefix( + from source: UnsafeMutableBufferPointer + ) -> Int { + if source.isEmpty { return 0 } + precondition(source.count <= self.count) + self.baseAddress.unsafelyUnwrapped.moveInitialize( + from: source.baseAddress.unsafelyUnwrapped, count: source.count) + return source.count + } +} + +extension UnsafeMutableBufferPointer { + /// Initialize slots at the start of this buffer by copying data from `source`. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized, while `source` must be fully initialized. + /// + /// The `source` buffer must fit entirely in `self`. + /// + /// - Returns: The index after the last item that was initialized in this buffer. + @inlinable + public func _initializePrefix( + copying source: UnsafeBufferPointer + ) -> Int { + if source.isEmpty { return 0 } + precondition(source.count <= self.count) + self.baseAddress.unsafelyUnwrapped.initialize( + from: source.baseAddress.unsafelyUnwrapped, count: source.count) + return source.count + } + + @inlinable + public func _initializePrefix( + copying source: UnsafeMutableBufferPointer + ) -> Int { + _initializePrefix(copying: UnsafeBufferPointer(source)) + } + +#if compiler(>=6.2) + /// Initialize slots at the start of this buffer by copying data from `source`. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized. + /// + /// The `source` span must fit entirely in `self`. + /// + /// - Returns: The index after the last item that was initialized in this buffer. + @available(SwiftStdlib 6.2, *) + @inlinable + public func _initializePrefix(copying source: Span) -> Int { + source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } + } +#endif + +#if compiler(>=6.2) && FIXME + /// Initialize all slots in this buffer by copying data from `items`, which must fit entirely + /// in this buffer. + /// + /// If `items` contains more elements than can fit into this buffer, then this function + /// will return an index other than `items.endIndex`. In that case, `self` may not be fully + /// populated. + /// + /// If `Element` is not bitwise copyable, then this function must be called on an + /// entirely uninitialized buffer. + /// + /// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were + /// successfully initialized, and `end` is the index into `items` after the last copied item. + @available(SwiftStdlib 6.2, *) + @inlinable + public func _initializePrefix< + C: Container & ~Copyable & ~Escapable + >( + copying items: borrowing C + ) -> (copied: Int, end: C.Index) { + var target = self + var i = items.startIndex + while true { + let start = i + let span = items.span(after: &i) + if span.isEmpty { break } + guard span.count <= target.count else { + return (self.count - target.count, start) + } + target._initializeAndDropPrefix(copying: span) + } + return (self.count - target.count, i) + } +#endif + + /// Initialize slots at the start of this buffer by copying data from `buffer`, then + /// shrink `self` to drop all initialized items from its front, leaving it addressing the + /// uninitialized remainder. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized, while `buffer` must be fully initialized. + /// + /// The count of `buffer` must not be greater than `self.count`. + @inlinable + public mutating func _initializeAndDropPrefix(copying source: UnsafeBufferPointer) { + let i = _initializePrefix(copying: source) + self = self.extracting(i...) + } + +#if compiler(>=6.2) + /// Initialize slots at the start of this buffer by copying data from `span`, then + /// shrink `self` to drop all initialized items from its front, leaving it addressing the + /// uninitialized remainder. + /// + /// If `Element` is not bitwise copyable, then the memory region addressed by `self` must be + /// entirely uninitialized. + /// + /// The count of `span` must not be greater than `self.count`. + @available(SwiftStdlib 5.0, *) + @inlinable + public mutating func _initializeAndDropPrefix(copying span: Span) { + span.withUnsafeBufferPointer { buffer in + self._initializeAndDropPrefix(copying: buffer) + } + } +#endif +} + extension UnsafeMutableBufferPointer { @inlinable public func initialize(fromContentsOf source: Self) -> Index { diff --git a/Tests/ArrayTests/ArrayLayout.swift b/Tests/ArrayTests/ArrayLayout.swift new file mode 100644 index 00000000..49c98240 --- /dev/null +++ b/Tests/ArrayTests/ArrayLayout.swift @@ -0,0 +1,104 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import _CollectionsTestSupport +import ArrayModule +#endif + +struct ArrayLayout { + var capacity: Int + var count: Int + + init(capacity: Int, count: Int) { + precondition(count >= 0 && count <= capacity) + self.capacity = capacity + self.count = count + } +} + +func withSomeArrayLayouts( + _ label: String, + ofCapacities capacities: some Sequence, + file: StaticString = #filePath, + line: UInt = #line, + run body: (ArrayLayout) throws(E) -> Void +) throws(E) { + let context = TestContext.current + for capacity in capacities { + var counts: Set = [] + counts.insert(0) + counts.insert(capacity) + counts.insert(capacity / 2) + if capacity >= 1 { + counts.insert(1) + counts.insert(capacity - 1) + } + if capacity >= 2 { + counts.insert(2) + counts.insert(capacity - 2) + } + for count in counts { + let layout = ArrayLayout(capacity: capacity, count: count) + let entry = context.push("\(label): \(layout)", file: file, line: line) + + var done = false + defer { + context.pop(entry) + if !done { + print(context.currentTrace(title: "Throwing trace")) + } + } + try body(layout) + done = true + } + } +} + +#if compiler(>=6.2) +extension RigidArray where Element: ~Copyable { + init(layout: ArrayLayout, using generator: (Int) -> Element) { + self.init(capacity: layout.capacity) { span in + for i in 0 ..< layout.count { + span.append(generator(i)) + } + } + } +} + +extension DynamicArray where Element: ~Copyable { + init(layout: ArrayLayout, using generator: (Int) -> Element) { + self.init(consuming: RigidArray(layout: layout, using: generator)) + } +} + +extension LifetimeTracker { + func rigidArray( + layout: ArrayLayout, + using generator: (Int) -> Element = { $0 } + ) -> RigidArray> { + RigidArray(layout: layout, using: { self.instance(for: generator($0)) }) + } + + func dynamicArray( + layout: ArrayLayout, + using generator: (Int) -> Element = { $0 } + ) -> DynamicArray> { + let contents = RigidArray(layout: layout) { + self.instance(for: generator($0)) + } + return DynamicArray(consuming: contents) + } +} +#endif diff --git a/Tests/ArrayTests/DynamicArrayTests.swift b/Tests/ArrayTests/DynamicArrayTests.swift new file mode 100644 index 00000000..d35d6227 --- /dev/null +++ b/Tests/ArrayTests/DynamicArrayTests.swift @@ -0,0 +1,808 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +#if compiler(>=6.2) && FIXME +import XCTest +import _CollectionsTestSupport +import ArrayModule +//import Synchronization + +@available(SwiftStdlib 6.2, *) +class DynamicArrayTests: CollectionTestCase { + func test_validate_Container() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let items = DynamicArray(consuming: tracker.rigidArray(layout: layout)) + let expected = (0 ..< layout.count).map { tracker.instance(for: $0) } + expectEqual(tracker.instances, 2 * layout.count) + checkContainer(items, expectedContents: expected) + } + } + } + + func test_basics() { + withLifetimeTracking { tracker in + typealias Value = LifetimeTrackedStruct + + var array = DynamicArray() + expectTrue(array.isEmpty) + expectEqual(array.count, 0) + expectEqual(array.capacity, 0) + expectEqual(tracker.instances, 0) + + array.append(tracker.structInstance(for: 10)) + expectFalse(array.isEmpty) + expectEqual(array.count, 1) + expectEqual(array.capacity, 1) // This assumes a specific growth behavior + expectEqual(array[0].payload, 10) + expectEqual(tracker.instances, 1) + + array.append(tracker.structInstance(for: 20)) + expectFalse(array.isEmpty) + expectEqual(array.count, 2) + expectEqual(array.capacity, 2) // This assumes a specific growth behavior + expectEqual(array[0].payload, 10) + expectEqual(array[1].payload, 20) + expectEqual(tracker.instances, 2) + + let old = array.remove(at: 0) + expectEqual(old.payload, 10) + expectFalse(array.isEmpty) + expectEqual(array.count, 1) + expectEqual(array.capacity, 2) // This assumes a specific growth behavior + expectEqual(array[0].payload, 20) + expectEqual(tracker.instances, 2) + _ = consume old + expectEqual(tracker.instances, 1) + + let old2 = array.remove(at: 0) + expectEqual(old2.payload, 20) + expectEqual(array.count, 0) + expectEqual(array.capacity, 2) // This assumes a specific growth behavior + expectTrue(array.isEmpty) + expectEqual(tracker.instances, 1) + _ = consume old2 + expectEqual(tracker.instances, 0) + } + } + + func test_init_capacity() { + do { + let a = DynamicArray(capacity: 0) + expectEqual(a.capacity, 0) + expectEqual(a.count, 0) + expectEqual(a.freeCapacity, 0) + expectTrue(a.isEmpty) + } + + do { + let a = DynamicArray(capacity: 10) + expectEqual(a.capacity, 10) + expectEqual(a.count, 0) + expectEqual(a.freeCapacity, 10) + expectTrue(a.isEmpty) + } + } + + func test_init_generator() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.dynamicArray(layout: layout) + expectEqual(a.capacity, layout.capacity) + expectEqual(a.count, layout.count) + expectEqual(a.freeCapacity, layout.capacity - layout.count) + expectEqual(a.isEmpty, layout.count == 0) + expectContainerContents(a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + } + } + } + + func test_init_repeating() { + withEvery("c", in: [0, 10, 100]) { c in + withLifetimeTracking { tracker in + let value = tracker.instance(for: 0) + let a = DynamicArray(repeating: value, count: c) + expectEqual(a.capacity, c) + expectEqual(a.count, c) + expectEqual(a.freeCapacity, 0) + expectEqual(a.isEmpty, c == 0) + for i in 0 ..< c { + expectIdentical(a[i], value) + } + } + } + } + + func test_init_copying_Sequence() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = DynamicArray( + capacity: layout.capacity, + copying: (0 ..< layout.count).map { tracker.instance(for: $0) }) + expectEqual(tracker.instances, layout.count) + expectEqual(a.capacity, layout.capacity) + expectEqual(a.count, layout.count) + expectEqual(a.isEmpty, layout.count == 0) + for i in 0 ..< layout.count { + expectEqual(a[i].payload, i) + } + } + } + } + + func test_init_copying_Container() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("spanCounts", in: [ + [1], + [3, 5, 7], + [10, 3], + ] as [[Int]]) { spanCounts in + withLifetimeTracking { tracker in + let additions = StaccatoContainer( + contents: RigidArray( + copying: (0 ..< layout.count).map { tracker.instance(for: $0) }), + spanCounts: spanCounts) + + let array = DynamicArray( + capacity: layout.capacity, copying: additions) + expectEqual(tracker.instances, layout.count) + expectEqual(array.capacity, layout.capacity) + expectEqual(array.count, layout.count) + for i in 0 ..< layout.count { + expectEqual(array[i].payload, i) + } + } + } + } + } + + func test_span() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.dynamicArray(layout: layout) + let span = a.span + expectEqual(span.count, layout.count) + for i in 0 ..< span.count { + expectEqual(span[i].payload, i) + } + } + } + } + + func test_mutableSpan() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + var span = a.mutableSpan + expectEqual(span.count, layout.count) + for i in 0 ..< layout.count { + expectEqual(span[i].payload, i) + span[i] = tracker.instance(for: -i) + } + for i in 0 ..< layout.count { + expectEqual(span[i].payload, -i) + } + for i in 0 ..< layout.count { + expectEqual(a[i].payload, -i) + } + } + } + } + + func test_nextSpan() { + // DynamicArray is expected to have exactly one span. + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.dynamicArray(layout: layout) + let whole = a.span + var i = 0 + let first = a.span(after: &i) + expectEqual(i, layout.count) + expectTrue(first.isIdentical(to: whole)) + let second = a.span(after: &i) + expectEqual(i, layout.count) + expectTrue(second.isEmpty) + } + } + } + + func test_previousSpan() { + // RigidArray is expected to have exactly one span. + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.dynamicArray(layout: layout) + let whole = a.span + var i = layout.count + let first = a.span(before: &i) + expectEqual(i, 0) + expectTrue(first.isIdentical(to: whole)) + let second = a.span(before: &i) + expectEqual(i, 0) + expectTrue(second.isEmpty) + } + } + } + + func test_nextMutableSpan() { + // RigidArray is expected to have exactly one span. + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + var i = 0 + var span = a.nextMutableSpan(after: &i) + expectEqual(i, layout.count) + expectEqual(span.count, layout.count) + span = a.nextMutableSpan(after: &i) + expectEqual(i, layout.count) + expectTrue(span.isEmpty) + } + } + } + + func test_index_properties() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + let a = DynamicArray(layout: layout, using: { $0 }) + expectEqual(a.startIndex, 0) + expectEqual(a.endIndex, layout.count) + expectEqual(a.indices, 0 ..< layout.count) + } + } + + func test_swapAt() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + withEvery("i", in: 0 ..< layout.count / 2) { i in + a.swapAt(i, layout.count - 1 - i) + } + let expected = (0 ..< layout.count).reversed() + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count) + } + } + } + + func test_borrowElement() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.dynamicArray(layout: layout) + for i in 0 ..< layout.count { + let item = a.borrowElement(at: i) + expectEqual(item[].payload, i) + } + } + } + } + + func test_mutateElement() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + for i in 0 ..< layout.count { + var item = a.mutateElement(at: i) + expectEqual(item[].payload, i) + item[] = tracker.instance(for: -i) + expectEqual(tracker.instances, layout.count) + } + } + } + } + + func test_edit() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + a.edit { span in + expectEqual(span.capacity, layout.capacity) + expectEqual(span.count, layout.count) + span.removeAll() + expectEqual(tracker.instances, 0) + } + expectEqual(a.count, 0) + + a.edit { span in + expectEqual(span.capacity, layout.capacity) + expectEqual(span.count, 0) + for i in 0 ..< span.capacity { + span.append(tracker.instance(for: -i)) + } + expectEqual(tracker.instances, layout.capacity) + } + expectEqual(a.count, layout.capacity) + + struct TestError: Error {} + + expectThrows({ + try a.edit { span in + expectEqual(tracker.instances, layout.capacity) + while !span.isEmpty { + if span.count == layout.count { break } + let old = span.removeLast() + expectEqual(old.payload, -span.count) + } + throw TestError() + } + }) { error in + expectTrue(error is TestError) + } + expectEquivalentElements( + a.span, + (0 ..< layout.count).map { -$0 }, + by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count) + } + } + } + + func test_reallocate() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery( + "newCapacity", + in: [ + layout.capacity, layout.count, layout.count + 1, layout.capacity + 1 + ] as Set + ) { newCapacity in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + expectEqual(a.count, layout.count) + expectEqual(a.capacity, layout.capacity) + a.reallocate(capacity: newCapacity) + expectEqual(a.count, layout.count) + expectEqual(a.capacity, newCapacity) + expectEqual(tracker.instances, layout.count) + expectContainerContents( + a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + } + } + } + } + + func test_reserveCapacity() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery( + "newCapacity", + in: [ + 0, layout.count - 1, layout.count, layout.count + 1, + layout.capacity, layout.capacity + 1 + ] as Set + ) { newCapacity in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + expectEqual(a.count, layout.count) + expectEqual(a.capacity, layout.capacity) + a.reserveCapacity(newCapacity) + expectEqual(a.count, layout.count) + expectEqual(a.capacity, Swift.max(layout.capacity, newCapacity)) + expectEqual(tracker.instances, layout.count) + expectContainerContents( + a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + } + } + } + } + + func test_removeAll() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + a.removeAll() + expectTrue(a.isEmpty) + expectEqual(a.capacity, 0) + expectEqual(tracker.instances, 0) + } + } + } + + func test_removeAll_keepingCapacity() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + a.removeAll(keepingCapacity: true) + expectTrue(a.isEmpty) + expectEqual(a.capacity, layout.capacity) + expectEqual(tracker.instances, 0) + } + } + } + + func test_removeLast() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + withEvery("i", in: 0 ..< layout.count) { i in + let old = a.removeLast() + expectEqual(old.payload, layout.count - 1 - i) + expectEqual(a.count, layout.count - 1 - i) + expectEqual(a.capacity, layout.capacity) + } + expectEqual(tracker.instances, 0) + } + } + } + + func test_removeLast_k() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("k", in: 0 ..< layout.count) { k in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + expected.removeLast(k) + + var a = tracker.dynamicArray(layout: layout) + expectEqual(tracker.instances, layout.count) + a.removeLast(k) + expectEqual(tracker.instances, layout.count - k) + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + } + } + } + } + + func test_remove_at() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("i", in: 0 ..< layout.count) { i in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + expected.remove(at: i) + + var a = tracker.dynamicArray(layout: layout) + let old = a.remove(at: i) + expectEqual(old.payload, i) + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + } + } + } + } + + func test_removeSubrange() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEveryRange("range", in: 0 ..< layout.count) { range in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + expected.removeSubrange(range) + + var a = tracker.dynamicArray(layout: layout) + a.removeSubrange(range) + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + } + } + } + } + + func test_removeAll_where() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + expected.removeAll(where: { $0.isMultiple(of: 2) }) + + var a = tracker.dynamicArray(layout: layout) + a.removeAll(where: { $0.payload.isMultiple(of: 2) }) + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + } + } + } + + func test_popLast() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + let expectedItem = expected.popLast() + + var a = tracker.dynamicArray(layout: layout) + let item = a.popLast() + + expectEquivalent(item, expectedItem, by: { $0?.payload == $1 }) + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + } + } + } + + func test_append_geometric_growth() { + // This test depends on the precise growth curve of DynamicArray, + // which is not part of its stable API. The test may need to be updated + // accordingly. + withLifetimeTracking { tracker in + typealias Value = LifetimeTracked + + var array = DynamicArray() + expectEqual(array.capacity, 0) + + array.append(tracker.instance(for: 0)) + expectEqual(array.capacity, 1) + array.append(tracker.instance(for: 1)) + expectEqual(array.capacity, 2) + array.append(tracker.instance(for: 2)) + expectEqual(array.capacity, 4) + array.append(tracker.instance(for: 3)) + expectEqual(array.capacity, 4) + array.append(tracker.instance(for: 4)) + expectEqual(array.capacity, 8) + array.append(tracker.instance(for: 5)) + expectEqual(array.capacity, 8) + array.append(tracker.instance(for: 6)) + expectEqual(array.capacity, 8) + array.append(tracker.instance(for: 7)) + expectEqual(array.capacity, 8) + array.append(tracker.instance(for: 8)) + expectEqual(array.capacity, 16) + + for i in 9 ..< 100 { + array.append(tracker.instance(for: i)) + } + expectEqual(tracker.instances, 100) + expectEqual(array.count, 100) + expectEqual(array.capacity, 128) + + let additions = RigidArray(capacity: 300) { span in + for i in 0 ..< 300 { + span.append(tracker.instance(for: 100 + i)) + } + } + array.append(copying: additions.span) + expectEqual(array.capacity, 400) + + expectEqual(tracker.instances, 400) + for i in 0 ..< 400 { + expectEqual(array.borrowElement(at: i)[].payload, i) + expectEqual(array[i].payload, i) + } + + _ = consume array + expectEqual(tracker.instances, 0) + } + } + + func test_append() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let c = 2 * layout.capacity + 10 + var a = tracker.dynamicArray(layout: layout) + for i in layout.count ..< c { + a.append(tracker.instance(for: i)) + expectEqual(a.count, i + 1) + expectContainerContents(a, equivalentTo: 0 ..< i + 1, by: { $0.payload == $1 }) + } + expectEqual(tracker.instances, c) + } + } + } + + func test_append_copying_MinimalSequence() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("isContiguous", in: [false, true]) { isContiguous in + withLifetimeTracking { tracker in + let c = 2 * layout.capacity + 10 + var a = tracker.dynamicArray(layout: layout) + a.append(copying: MinimalSequence( + elements: (layout.count ..< c).map { tracker.instance(for: $0) }, + underestimatedCount: .half, + isContiguous: isContiguous)) + expectContainerContents( + a, equivalentTo: 0 ..< c, by: { $0.payload == $1}) + expectEqual(tracker.instances, c) + } + } + } + } + + func test_append_copying_Span() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("additions", in: [0, 1, 10, 100]) { additions in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + let b = RigidArray(count: additions) { + tracker.instance(for: layout.count + $0) + } + a.append(copying: b.span) + let c = layout.count + additions + expectContainerContents( + a, equivalentTo: 0 ..< c, by: { $0.payload == $1 }) + expectEqual(tracker.instances, c) + } + } + } + } + + func test_append_copying_Container() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("additions", in: [0, 1, 10, 100]) { additions in + withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + + let c = layout.count + additions + let addition = (layout.count ..< c).map { + tracker.instance(for: $0) + } + let b = StaccatoContainer( + contents: RigidArray(copying: addition), + spanCounts: [spanCount]) + a.append(copying: b) + expectContainerContents( + a, equivalentTo: 0 ..< c, by: { $0.payload == $1 }) + expectEqual(tracker.instances, c) + } + } + } + } + } + + func test_insert_at() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("i", in: 0 ... layout.count) { i in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + expected.insert(-1, at: i) + + var a = tracker.dynamicArray(layout: layout) + a.insert(tracker.instance(for: -1), at: i) + + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count + 1) + } + } + } + } + + func test_insert_copying_Collection() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("c", in: [0, 1, 10, 100]) { c in + withEvery("i", in: 0 ... layout.count) { i in + withLifetimeTracking { tracker in + let addition = (layout.count ..< layout.count + c) + + var expected = Array(0 ..< layout.count) + expected.insert(contentsOf: addition, at: i) + + let trackedAddition = addition.map { tracker.instance(for: $0) } + var a = tracker.dynamicArray(layout: layout) + a.insert(copying: trackedAddition, at: i) + + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count + c) + } + } + } + } + } + + func test_insert_copying_Span() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("i", in: 0 ... layout.count) { i in + withEvery("c", in: [0, 1, 10, 100]) { c in + withLifetimeTracking { tracker in + let addition = Array(layout.count ..< layout.count + c) + + var expected = Array(0 ..< layout.count) + expected.insert(contentsOf: addition, at: i) + + let rigidAddition = RigidArray(count: addition.count) { + tracker.instance(for: addition[$0]) + } + var a = tracker.dynamicArray(layout: layout) + a.insert(copying: rigidAddition.span, at: i) + + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count + c) + } + } + } + } + } + + func test_insert_copying_Container() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("i", in: 0 ... layout.count) { i in + withEvery("c", in: [0, 1, 10, 100]) { c in + withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in + withLifetimeTracking { tracker in + + var expected = Array(0 ..< layout.count) + let addition = Array(layout.count ..< layout.count + c) + expected.insert(contentsOf: addition, at: i) + + var a = tracker.dynamicArray(layout: layout) + let rigidAddition = StaccatoContainer( + contents: RigidArray(count: addition.count) { + tracker.instance(for: addition[$0]) + }, + spanCounts: [spanCount]) + a.insert(copying: rigidAddition, at: i) + + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count + c) + } + } + } + } + } + } + + func test_replaceSubrange_copying_Collection() { + withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in + withEveryRange("range", in: 0 ..< layout.count) { range in + withEvery("c", in: [0, 1, 10, 100]) { c in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + let addition = (0 ..< c).map { -100 - $0 } + expected.replaceSubrange(range, with: addition) + + var a = tracker.dynamicArray(layout: layout) + let trackedAddition = addition.map { tracker.instance(for: $0) } + a.replaceSubrange(range, copying: trackedAddition) + + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count - range.count + c) + } + } + } + } + } + + func test_replaceSubrange_copying_Span() { + withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in + withEveryRange("range", in: 0 ..< layout.count) { range in + withEvery("c", in: [0, 1, 10, 100]) { c in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + let addition = (0 ..< c).map { -100 - $0 } + expected.replaceSubrange(range, with: addition) + + var a = tracker.dynamicArray(layout: layout) + let trackedAddition = RigidArray( + copying: addition.map { tracker.instance(for: $0) }) + a.replaceSubrange(range, copying: trackedAddition.span) + + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count - range.count + c) + } + } + } + } + } + + func test_replaceSubrange_copying_Container() { + withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in + withEveryRange("range", in: 0 ..< layout.count) { range in + withEvery("c", in: [0, 1, 10, 100]) { c in + withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + let addition = (0 ..< c).map { -100 - $0 } + expected.replaceSubrange(range, with: addition) + + var a = tracker.dynamicArray(layout: layout) + let trackedAddition = StaccatoContainer( + contents: RigidArray( + copying: addition.map { tracker.instance(for: $0) }), + spanCounts: [spanCount]) + a.replaceSubrange(range, copying: trackedAddition) + + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count - range.count + c) + } + } + } + } + } + } +} +#endif diff --git a/Tests/ArrayTests/RigidArrayTests.swift b/Tests/ArrayTests/RigidArrayTests.swift new file mode 100644 index 00000000..b6f45152 --- /dev/null +++ b/Tests/ArrayTests/RigidArrayTests.swift @@ -0,0 +1,825 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2025 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 +// +//===----------------------------------------------------------------------===// + +import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import _CollectionsTestSupport +import ArrayModule +#endif + +#if compiler(>=6.2) + +#if !COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 5.0, *) +public func expectContainerContents< + Element: Equatable, + C2: Collection, +>( + _ left: borrowing RigidArray, + equalTo right: C2, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #file, + line: UInt = #line +) { + expectContainerContents( + left.span, + equalTo: right, + message(), trapping: trapping, file: file, line: line) +} + +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 5.0, *) +public func expectContainerContents< + E1: ~Copyable, + C2: Collection, +>( + _ left: borrowing RigidArray, + equivalentTo right: C2, + by areEquivalent: (borrowing E1, C2.Element) -> Bool, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #file, + line: UInt = #line +) { + expectContainerContents( + left.span, + equivalentTo: right, + by: areEquivalent, + message(), trapping: trapping, file: file, line: line) +} +#endif + +@available(SwiftStdlib 5.0, *) +class RigidArrayTests: CollectionTestCase { + func test_validate_Container() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let items = tracker.rigidArray(layout: layout) + let expected = (0 ..< layout.count).map { tracker.instance(for: $0) } + expectEqual(tracker.instances, 2 * layout.count) + expectContainerContents(items, equalTo: expected) +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + checkContainer(items, expectedContents: expected) +#endif + } + } + } + + func test_empty() { + let a = RigidArray() + expectEqual(a.capacity, 0) + expectEqual(a.count, 0) + expectEqual(a.freeCapacity, 0) + expectTrue(a.isEmpty) + expectTrue(a.isFull) + } + + func test_init_capacity() { + do { + let a = RigidArray(capacity: 0) + expectEqual(a.capacity, 0) + expectEqual(a.count, 0) + expectEqual(a.freeCapacity, 0) + expectTrue(a.isEmpty) + expectTrue(a.isFull) + } + + do { + let a = RigidArray(capacity: 10) + expectEqual(a.capacity, 10) + expectEqual(a.count, 0) + expectEqual(a.freeCapacity, 10) + expectTrue(a.isEmpty) + expectFalse(a.isFull) + } + } + + func test_init_generator() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layout) + expectEqual(a.capacity, layout.capacity) + expectEqual(a.count, layout.count) + expectEqual(a.freeCapacity, layout.capacity - layout.count) + expectEqual(a.isEmpty, layout.count == 0) + expectEqual(a.isFull, layout.count == layout.capacity) + expectContainerContents( + a, + equivalentTo: 0 ..< layout.count, + by: { $0.payload == $1 }) + } + } + } + + func test_init_repeating() { + withEvery("c", in: [0, 10, 100]) { c in + withLifetimeTracking { tracker in + let value = tracker.instance(for: 0) + let a = RigidArray(repeating: value, count: c) + expectEqual(a.capacity, c) + expectEqual(a.count, c) + expectEqual(a.freeCapacity, 0) + expectEqual(a.isEmpty, c == 0) + expectTrue(a.isFull) + for i in 0 ..< c { + expectIdentical(a[i], value) + } + } + } + } + + func test_init_copying_Collection() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = RigidArray( + capacity: layout.capacity, + copying: (0 ..< layout.count).map { tracker.instance(for: $0) }) + expectEqual(tracker.instances, layout.count) + expectEqual(a.capacity, layout.capacity) + expectEqual(a.count, layout.count) + expectEqual(a.freeCapacity, layout.capacity - layout.count) + expectEqual(a.isEmpty, layout.count == 0) + expectEqual(a.isFull, layout.count == layout.capacity) + for i in 0 ..< layout.count { + expectEqual(a[i].payload, i) + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_init_copying_Container() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("spanCounts", in: [ + [1], + [3, 5, 7], + [10, 3], + ] as [[Int]]) { spanCounts in + withLifetimeTracking { tracker in + let additions = StaccatoContainer( + contents: RigidArray( + copying: (0 ..< layout.count).map { tracker.instance(for: $0) }), + spanCounts: spanCounts) + + let array = RigidArray(capacity: layout.capacity, copying: additions) + expectEqual(tracker.instances, layout.count) + expectEqual(array.capacity, layout.capacity) + expectEqual(array.count, layout.count) + for i in 0 ..< layout.count { + expectEqual(array[i].payload, i) + } + } + } + } + } +#endif + + func test_span() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layout) + let span = a.span + expectEqual(span.count, layout.count) + for i in 0 ..< span.count { + expectEqual(span[i].payload, i) + } + } + } + } + + func test_mutableSpan() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + var span = a.mutableSpan + expectEqual(span.count, layout.count) + for i in 0 ..< layout.count { + expectEqual(span[i].payload, i) + span[i] = tracker.instance(for: -i) + } + for i in 0 ..< layout.count { + expectEqual(span[i].payload, -i) + } + for i in 0 ..< layout.count { + expectEqual(a[i].payload, -i) + } + } + } + } + + func test_nextSpan() { + // RigidArray is expected to have exactly one span. + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layout) + let whole = a.span + var i = 0 + let first = a.span(after: &i) + expectEqual(i, layout.count) + expectTrue(first.isIdentical(to: whole)) + let second = a.span(after: &i) + expectEqual(i, layout.count) + expectTrue(second.isEmpty) + } + } + } + + func test_previousSpan() { + // RigidArray is expected to have exactly one span. + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layout) + let whole = a.span + var i = layout.count + let first = a.span(before: &i) + expectEqual(i, 0) + expectTrue(first.isIdentical(to: whole)) + let second = a.span(before: &i) + expectEqual(i, 0) + expectTrue(second.isEmpty) + } + } + } + + func test_nextMutableSpan() { + // RigidArray is expected to have exactly one span. + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + var i = 0 + var span = a.mutableSpan(after: &i) + expectEqual(i, layout.count) + expectEqual(span.count, layout.count) + span = a.mutableSpan(after: &i) + expectEqual(i, layout.count) + expectTrue(span.isEmpty) + } + } + } + + func test_index_properties() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + let a = RigidArray(layout: layout, using: { $0 }) + expectEqual(a.startIndex, 0) + expectEqual(a.endIndex, layout.count) + expectEqual(a.indices, 0 ..< layout.count) + } + } + + func test_swapAt() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + withEvery("i", in: 0 ..< layout.count / 2) { i in + a.swapAt(i, layout.count - 1 - i) + } + let expected = (0 ..< layout.count).reversed() + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count) + } + } + } + + func test_subscript_borrow() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layout) + for i in 0 ..< layout.count { + expectEqual(a[i].payload, i) + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_borrowElement() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layout) + for i in 0 ..< layout.count { + let item = a.borrowElement(at: i) + expectEqual(item[].payload, i) + } + } + } + } +#endif + + func test_mutateElement() { + func modify(tracker: LifetimeTracker, i: Int, item: inout LifetimeTracked) { + expectEqual(item.payload, i) + item = tracker.instance(for: -i) + } + + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + for i in 0 ..< layout.count { + modify(tracker: tracker, i: i, item: &a[i]) + expectEqual(tracker.instances, layout.count) + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_mutateElement() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + for i in 0 ..< layout.count { + var item = a.mutateElement(at: i) + expectEqual(item[].payload, i) + item[] = tracker.instance(for: -i) + expectEqual(tracker.instances, layout.count) + } + } + } + } +#endif + + func test_edit() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + a.edit { span in + expectEqual(span.capacity, layout.capacity) + expectEqual(span.count, layout.count) + if span.count > 0 { // FIXME: rdar://158440246 + span.removeAll() + } + expectEqual(tracker.instances, 0) + } + expectEqual(a.count, 0) + + a.edit { span in + expectEqual(span.capacity, layout.capacity) + expectEqual(span.count, 0) + for i in 0 ..< span.capacity { + span.append(tracker.instance(for: -i)) + } + expectEqual(tracker.instances, layout.capacity) + } + expectEqual(a.count, layout.capacity) + + struct TestError: Error {} + + expectThrows { + try a.edit { span in + expectEqual(tracker.instances, layout.capacity) + while !span.isEmpty { + if span.count == layout.count { break } + let old = span.removeLast() + expectEqual(old.payload, -span.count) + } + throw TestError() + } + } + errorHandler: { error in + expectTrue(error is TestError) + } + expectContainerContents( + a, + equivalentTo: (0 ..< layout.count).map { -$0 }, + by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count) + } + } + } + + func test_reallocate() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery( + "newCapacity", + in: [ + layout.capacity, layout.count, layout.count + 1, layout.capacity + 1 + ] as Set + ) { newCapacity in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + expectEqual(a.count, layout.count) + expectEqual(a.capacity, layout.capacity) + a.reallocate(capacity: newCapacity) + expectEqual(a.count, layout.count) + expectEqual(a.capacity, newCapacity) + expectEqual(tracker.instances, layout.count) + expectContainerContents( + a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + } + } + } + } + + func test_reserveCapacity() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery( + "newCapacity", + in: [ + 0, layout.count - 1, layout.count, layout.count + 1, + layout.capacity, layout.capacity + 1 + ] as Set + ) { newCapacity in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + expectEqual(a.count, layout.count) + expectEqual(a.capacity, layout.capacity) + a.reserveCapacity(newCapacity) + expectEqual(a.count, layout.count) + expectEqual(a.capacity, Swift.max(layout.capacity, newCapacity)) + expectEqual(tracker.instances, layout.count) + expectContainerContents( + a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + } + } + } + } + + func test_copy() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layout) + let b = a.copy() + expectEqual(b.count, layout.count) + expectEqual(b.capacity, layout.capacity) + expectEqual(tracker.instances, layout.count) + expectContainerContents(a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + expectContainerContents(b, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + } + } + } + + func test_copy_capacity() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery( + "newCapacity", + in: [layout.count, layout.count + 1, layout.capacity, layout.capacity + 1] as Set + ) { newCapacity in + withLifetimeTracking { tracker in + let a = tracker.rigidArray(layout: layout) + let b = a.copy(capacity: newCapacity) + expectEqual(b.count, layout.count) + expectEqual(b.capacity, newCapacity) + expectEqual(tracker.instances, layout.count) + expectContainerContents(a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + expectContainerContents(b, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) + } + } + } + } + + func test_removeAll() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + a.removeAll() + expectTrue(a.isEmpty) + expectEqual(a.capacity, layout.capacity) + expectEqual(tracker.instances, 0) + } + } + } + + func test_removeLast() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + withEvery("i", in: 0 ..< layout.count) { i in + let old = a.removeLast() + expectEqual(old.payload, layout.count - 1 - i) + expectEqual(a.count, layout.count - 1 - i) + expectEqual(a.capacity, layout.capacity) + } + expectEqual(tracker.instances, 0) + } + } + } + + func test_removeLast_k() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("k", in: 0 ..< layout.count) { k in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + expected.removeLast(k) + + var a = tracker.rigidArray(layout: layout) + expectEqual(tracker.instances, layout.count) + a.removeLast(k) + expectEqual(tracker.instances, layout.count - k) + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + } + } + } + } + + func test_remove_at() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("i", in: 0 ..< layout.count) { i in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + expected.remove(at: i) + + var a = tracker.rigidArray(layout: layout) + let old = a.remove(at: i) + expectEqual(old.payload, i) + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + } + } + } + } + + func test_removeSubrange() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEveryRange("range", in: 0 ..< layout.count) { range in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + expected.removeSubrange(range) + + var a = tracker.rigidArray(layout: layout) + a.removeSubrange(range) + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_removeAll_where() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + expected.removeAll(where: { $0.isMultiple(of: 2) }) + + var a = tracker.rigidArray(layout: layout) + a.removeAll(where: { $0.payload.isMultiple(of: 2) }) + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + } + } + } +#endif + + func test_popLast() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + let expectedItem = expected.popLast() + + var a = tracker.rigidArray(layout: layout) + let item = a.popLast() + + expectEquivalent(item, expectedItem, by: { $0?.payload == $1 }) + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) + } + } + } + + func test_append() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + for i in layout.count ..< layout.capacity { + a.append(tracker.instance(for: i)) + expectEqual(a.count, i + 1) + expectContainerContents(a, equivalentTo: 0 ..< i + 1, by: { $0.payload == $1 }) + } + expectTrue(a.isFull) + expectEqual(tracker.instances, layout.capacity) + } + } + } + + func test_append_copying_MinimalSequence() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("isContiguous", in: [false, true]) { isContiguous in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + a.append(copying: MinimalSequence( + elements: (layout.count ..< layout.capacity).map { tracker.instance(for: $0) }, + underestimatedCount: .half, + isContiguous: isContiguous)) + expectTrue(a.isFull) + expectEqual(tracker.instances, layout.capacity) + } + } + } + } + + func test_append_copying_Span() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + let b = tracker.rigidArray( + layout: ArrayLayout( + capacity: layout.capacity - layout.count, + count: layout.capacity - layout.count), + using: { layout.count + $0 }) + a.append(copying: b.span) + expectTrue(a.isFull) + expectContainerContents(a, equivalentTo: 0 ..< layout.capacity, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.capacity) + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_append_copying_Container() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in + withLifetimeTracking { tracker in + var a = tracker.rigidArray(layout: layout) + + let addition = (layout.count ..< layout.capacity).map { tracker.instance(for: $0) } + let b = StaccatoContainer( + contents: RigidArray(copying: addition), + spanCounts: [spanCount]) + a.append(copying: b) + expectTrue(a.isFull) + expectContainerContents(a, equivalentTo: 0 ..< layout.capacity, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.capacity) + } + } + } + } +#endif + + func test_insert_at() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + guard layout.count < layout.capacity else { return } + withEvery("i", in: 0 ... layout.count) { i in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + expected.insert(-1, at: i) + + var a = tracker.rigidArray(layout: layout) + a.insert(tracker.instance(for: -1), at: i) + + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count + 1) + } + } + } + } + + func test_insert_copying_Collection() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("i", in: 0 ... layout.count) { i in + withEvery("isContiguous", in: [false, true]) { isContiguous in + withLifetimeTracking { tracker in + let addition = (layout.count ..< layout.capacity) + + var expected = Array(0 ..< layout.count) + expected.insert(contentsOf: addition, at: i) + + let trackedAddition = MinimalCollection( + addition.map { tracker.instance(for: $0) }, + isContiguous: isContiguous) + var a = tracker.rigidArray(layout: layout) + a.insert(copying: trackedAddition, at: i) + + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.capacity) + } + } + } + } + } + + func test_insert_copying_Span() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("i", in: 0 ... layout.count) { i in + withLifetimeTracking { tracker in + let addition = Array(layout.count ..< layout.capacity) + + var expected = Array(0 ..< layout.count) + expected.insert(contentsOf: addition, at: i) + + var a = tracker.rigidArray(layout: layout) + let rigidAddition = RigidArray(capacity: addition.count) { span in + for i in 0 ..< addition.count { + span.append(tracker.instance(for: addition[i])) + } + } + a.insert(copying: rigidAddition.span, at: i) + + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.capacity) + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_insert_copying_Container() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withEvery("i", in: 0 ... layout.count) { i in + withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in + withLifetimeTracking { tracker in + + var expected = Array(0 ..< layout.count) + let addition = Array(layout.count ..< layout.capacity) + expected.insert(contentsOf: addition, at: i) + + var a = tracker.rigidArray(layout: layout) + let rigidAddition = StaccatoContainer( + contents: RigidArray(count: addition.count) { + tracker.instance(for: addition[$0]) + }, + spanCounts: [Swift.max(spanCount, 1)]) + a.insert(copying: rigidAddition, at: i) + + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.capacity) + } + } + } + } + } +#endif + + func test_replaceSubrange_Collection() { + withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in + withEveryRange("range", in: 0 ..< layout.count) { range in + withEvery("isContiguous", in: [false, true]) { isContiguous in + withEvery("c", in: 0 ..< layout.capacity - layout.count + range.count) { c in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + let addition = (0 ..< c).map { -100 - $0 } + expected.replaceSubrange(range, with: addition) + + let trackedAddition = MinimalCollection( + addition.map { tracker.instance(for: $0) }, + isContiguous: isContiguous) + var a = tracker.rigidArray(layout: layout) + a.replaceSubrange(range, copying: trackedAddition) + + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count - range.count + c) + } + } + } + } + } + } + func test_replaceSubrange_Span() { + withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in + withEveryRange("range", in: 0 ..< layout.count) { range in + withEvery("c", in: 0 ..< layout.capacity - layout.count + range.count) { c in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + let addition = (0 ..< c).map { -100 - $0 } + expected.replaceSubrange(range, with: addition) + + var a = tracker.rigidArray(layout: layout) + let trackedAddition = RigidArray(copying: addition.map { tracker.instance(for: $0) }) + a.replaceSubrange(range, copying: trackedAddition.span) + + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count - range.count + c) + } + } + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + func test_replaceSubrange_Container() { + withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in + withEveryRange("range", in: 0 ..< layout.count) { range in + withEvery("c", in: 0 ..< layout.capacity - layout.count + range.count) { c in + withEvery("spanCount", in: 1 ... Swift.max(1, layout.capacity - layout.count)) { spanCount in + withLifetimeTracking { tracker in + var expected = Array(0 ..< layout.count) + let addition = (0 ..< c).map { -100 - $0 } + expected.replaceSubrange(range, with: addition) + + var a = tracker.rigidArray(layout: layout) + let trackedAddition = StaccatoContainer( + contents: RigidArray(copying: addition.map { tracker.instance(for: $0) }), + spanCounts: [spanCount]) + a.replaceSubrange(range, copying: trackedAddition) + + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.count - range.count + c) + } + } + } + } + } + } +#endif +} +#endif diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift new file mode 100644 index 00000000..b88327d7 --- /dev/null +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift @@ -0,0 +1,217 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2025 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 +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import ContainersPreview +#endif + +#if compiler(>=6.2) +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 5.0, *) +public func expectContainerContents< + Element: Equatable, + C2: Collection, +>( + _ left: borrowing Span, + equalTo right: C2, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #file, + line: UInt = #line +) { + var i = 0 + var it = right.makeIterator() + while i < left.count { + let a = left[i] + guard let b = it.next() else { + _expectFailure( + "\(left.testDescription) is longer than expected", + message, trapping: trapping, file: file, line: line) + return + } + guard a == b else { + _expectFailure( + "'\(a)' at index \(i) is not equal to '\(b)'", + message, trapping: trapping, file: file, line: line) + return + } + i += 1 + } + guard it.next() == nil else { + _expectFailure( + "\(left.testDescription) is shorter than expected", + message, trapping: trapping, file: file, line: line) + return + } +} + +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 5.0, *) +public func expectContainerContents< + E1: ~Copyable, + C2: Collection, +>( + _ left: borrowing Span, + equivalentTo right: C2, + by areEquivalent: (borrowing E1, C2.Element) -> Bool, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #file, + line: UInt = #line +) { + var i = 0 + var it = right.makeIterator() + while i < left.count { + guard let b = it.next() else { + _expectFailure( + "\(left.testDescription) is longer than expected", + message, trapping: trapping, file: file, line: line) + return + } + guard areEquivalent(left[i], b) else { + _expectFailure( + "Element at index \(i) is not equal to '\(b)'", + message, trapping: trapping, file: file, line: line) + return + } + i += 1 + } + guard it.next() == nil else { + _expectFailure( + "\(left.testDescription) is shorter than expected", + message, trapping: trapping, file: file, line: line) + return + } +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 6.2, *) +public func expectContainersWithEquivalentElements< + C1: Container & ~Copyable & ~Escapable, + C2: Container & ~Copyable & ~Escapable +>( + _ left: borrowing C1, + _ right: borrowing C2, + by areEquivalent: (borrowing C1.Element, borrowing C2.Element) -> Bool, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #file, + line: UInt = #line +) { + if left.elementsEqual(right, by: areEquivalent) { return } + _expectFailure( + "Containers do not have equivalent elements", + message, trapping: trapping, file: file, line: line) +} + +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 6.2, *) +public func expectContainersWithEqualElements< + Element: Equatable, + C1: Container & ~Copyable & ~Escapable, + C2: Container & ~Copyable & ~Escapable, +>( + _ left: borrowing C1, + _ right: borrowing C2, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #file, + line: UInt = #line +) { + if left.elementsEqual(right) { return } + _expectFailure( + "Containers do not have equal elements", + message, trapping: trapping, file: file, line: line) +} + +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 6.2, *) +public func expectContainerContents< + Element: Equatable, + C1: Container & ~Copyable & ~Escapable, + C2: Collection, +>( + _ left: borrowing C1, + equalTo right: C2, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #file, + line: UInt = #line +) { + var i = left.startIndex + var it = right.makeIterator() + while i < left.endIndex { + let a = left[i] + guard let b = it.next() else { + _expectFailure( + "Container is longer than expected", + message, trapping: trapping, file: file, line: line) + return + } + guard a == b else { + _expectFailure( + "'\(a)' at index \(i) is not equal to '\(b)'", + message, trapping: trapping, file: file, line: line) + return + } + left.formIndex(after: &i) + } + guard it.next() == nil else { + _expectFailure( + "Container is shorter than expected", + message, trapping: trapping, file: file, line: line) + return + } +} + +/// Check if `left` and `right` contain equal elements in the same order. +@available(SwiftStdlib 6.2, *) +public func expectContainerContents< + C1: Container & ~Copyable & ~Escapable, + C2: Collection, +>( + _ left: borrowing C1, + equivalentTo right: C2, + by areEquivalent: (borrowing C1.Element, C2.Element) -> Bool, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #file, + line: UInt = #line +) { + var i = left.startIndex + var it = right.makeIterator() + while i < left.endIndex { + guard let b = it.next() else { + _expectFailure( + "Container is longer than expected", + message, trapping: trapping, file: file, line: line) + return + } + guard areEquivalent(left[i], b) else { + _expectFailure( + "Element at index \(i) is not equal to '\(b)'", + message, trapping: trapping, file: file, line: line) + return + } + left.formIndex(after: &i) + } + guard it.next() == nil else { + _expectFailure( + "Container is shorter than expected", + message, trapping: trapping, file: file, line: line) + return + } +} +#endif +#endif diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index a1777e22..3d6780e7 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -7,10 +7,16 @@ objects = { /* Begin PBXBuildFile section */ + 7D48BCD22E51524200D7F6F7 /* DynamicArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCC22E51524200D7F6F7 /* DynamicArray.swift */; }; 7D48BCD32E51524200D7F6F7 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCC82E51524200D7F6F7 /* Box.swift */; }; + 7D48BCD52E51524200D7F6F7 /* RigidArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCC42E51524200D7F6F7 /* RigidArray.swift */; }; 7D48BCDC2E51554900D7F6F7 /* ClassBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */; }; 7D48BCE02E51558700D7F6F7 /* LifetimeTrackedStruct.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDE2E51558700D7F6F7 /* LifetimeTrackedStruct.swift */; }; + 7D48BCE92E5158A100D7F6F7 /* DynamicArrayTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCE22E5158A100D7F6F7 /* DynamicArrayTests.swift */; }; + 7D48BCEA2E5158A100D7F6F7 /* ArrayLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCE12E5158A100D7F6F7 /* ArrayLayout.swift */; }; + 7D48BCEB2E5158A100D7F6F7 /* RigidArrayTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCE32E5158A100D7F6F7 /* RigidArrayTests.swift */; }; 7D48BCEE2E5158A100D7F6F7 /* BoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCE62E5158A100D7F6F7 /* BoxTests.swift */; }; + 7D48BCF02E51597200D7F6F7 /* Assertions+Containers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCEF2E51597200D7F6F7 /* Assertions+Containers.swift */; }; 7D48BCFE2E5182CE00D7F6F7 /* UnsafeRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCFD2E5182CE00D7F6F7 /* UnsafeRawBufferPointer+Extras.swift */; }; 7D48BCFF2E5182CE00D7F6F7 /* UnsafeMutableRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCFC2E5182CE00D7F6F7 /* UnsafeMutableRawBufferPointer+Extras.swift */; }; 7D48BD002E5182CE00D7F6F7 /* LifetimeOverride.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCFA2E5182CE00D7F6F7 /* LifetimeOverride.swift */; }; @@ -432,10 +438,18 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 7D48BCC12E51524200D7F6F7 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 7D48BCC22E51524200D7F6F7 /* DynamicArray.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DynamicArray.swift; sourceTree = ""; }; + 7D48BCC42E51524200D7F6F7 /* RigidArray.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidArray.swift; sourceTree = ""; }; 7D48BCC82E51524200D7F6F7 /* Box.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Box.swift; sourceTree = ""; }; + 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClassBox.swift; sourceTree = ""; }; 7D48BCDE2E51558700D7F6F7 /* LifetimeTrackedStruct.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LifetimeTrackedStruct.swift; sourceTree = ""; }; + 7D48BCE12E5158A100D7F6F7 /* ArrayLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArrayLayout.swift; sourceTree = ""; }; + 7D48BCE22E5158A100D7F6F7 /* DynamicArrayTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DynamicArrayTests.swift; sourceTree = ""; }; + 7D48BCE32E5158A100D7F6F7 /* RigidArrayTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidArrayTests.swift; sourceTree = ""; }; 7D48BCE62E5158A100D7F6F7 /* BoxTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BoxTests.swift; sourceTree = ""; }; + 7D48BCEF2E51597200D7F6F7 /* Assertions+Containers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Assertions+Containers.swift"; sourceTree = ""; }; 7D48BCF52E51651900D7F6F7 /* Package@swift-6.0.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = "Package@swift-6.0.swift"; path = "../Package@swift-6.0.swift"; sourceTree = SOURCE_ROOT; }; 7D48BCF62E5172CF00D7F6F7 /* LifetimeOverride.swift.gyb */ = {isa = PBXFileReference; lastKnownFileType = text; path = LifetimeOverride.swift.gyb; sourceTree = ""; }; 7D48BCF82E5172CF00D7F6F7 /* UnsafeMutableRawBufferPointer+Extras.swift.gyb */ = {isa = PBXFileReference; lastKnownFileType = text; path = "UnsafeMutableRawBufferPointer+Extras.swift.gyb"; sourceTree = ""; }; @@ -904,14 +918,35 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 7D48BCC62E51524200D7F6F7 /* ArrayModule */ = { + isa = PBXGroup; + children = ( + 7D48BCC12E51524200D7F6F7 /* CMakeLists.txt */, + 7D48BCC22E51524200D7F6F7 /* DynamicArray.swift */, + 7D48BCC42E51524200D7F6F7 /* RigidArray.swift */, + ); + path = ArrayModule; + sourceTree = ""; + }; 7D48BCCE2E51524200D7F6F7 /* ContainersPreview */ = { isa = PBXGroup; children = ( 7D48BCC82E51524200D7F6F7 /* Box.swift */, + 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */, ); path = ContainersPreview; sourceTree = ""; }; + 7D48BCE42E5158A100D7F6F7 /* ArrayTests */ = { + isa = PBXGroup; + children = ( + 7D48BCE12E5158A100D7F6F7 /* ArrayLayout.swift */, + 7D48BCE22E5158A100D7F6F7 /* DynamicArrayTests.swift */, + 7D48BCE32E5158A100D7F6F7 /* RigidArrayTests.swift */, + ); + path = ArrayTests; + sourceTree = ""; + }; 7D48BCE82E5158A100D7F6F7 /* ContainersTests */ = { isa = PBXGroup; children = ( @@ -953,6 +988,7 @@ children = ( 7DE91F2229CA70F3004483EB /* InternalCollectionsUtilities */, 7D48BCCE2E51524200D7F6F7 /* ContainersPreview */, + 7D48BCC62E51524200D7F6F7 /* ArrayModule */, 7DE91F3929CA70F3004483EB /* BitCollections */, 7DE91F7929CA70F3004483EB /* Collections */, 7DE91EB629CA70F3004483EB /* DequeModule */, @@ -1541,6 +1577,7 @@ isa = PBXGroup; children = ( 7DEBDB1F29CCE43600ADC226 /* _CollectionsTestSupport */, + 7D48BCE42E5158A100D7F6F7 /* ArrayTests */, 7DE921DA29CA8575004483EB /* BitCollectionsTests */, 7DE921CB29CA8575004483EB /* CollectionsTestSupportTests */, 7D48BCE82E5158A100D7F6F7 /* ContainersTests */, @@ -1737,10 +1774,11 @@ 7DEBDB2029CCE43600ADC226 /* AssertionContexts */ = { isa = PBXGroup; children = ( + 7DEBDB2329CCE43600ADC226 /* Assertions.swift */, + 7D48BCEF2E51597200D7F6F7 /* Assertions+Containers.swift */, + 7DEBDB2429CCE43600ADC226 /* CollectionTestCase.swift */, 7DEBDB2129CCE43600ADC226 /* Combinatorics.swift */, 7DEBDB2229CCE43600ADC226 /* TestContext.swift */, - 7DEBDB2329CCE43600ADC226 /* Assertions.swift */, - 7DEBDB2429CCE43600ADC226 /* CollectionTestCase.swift */, ); path = AssertionContexts; sourceTree = ""; @@ -1748,20 +1786,20 @@ 7DEBDB2529CCE43600ADC226 /* Utilities */ = { isa = PBXGroup; children = ( - 7DEBDB2629CCE43600ADC226 /* RandomStableSample.swift */, + 7DEBDB2C29CCE43600ADC226 /* AllOnesRandomNumberGenerator.swift */, 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */, + 7DEBDB2A29CCE43600ADC226 /* DictionaryAPIChecker.swift */, + 7DEBDB3129CCE43600ADC226 /* HashableBox.swift */, 7DEBDB2829CCE43600ADC226 /* IndexRangeCollection.swift */, 7DEBDB2929CCE43600ADC226 /* Integer Square Root.swift */, - 7DEBDB2A29CCE43600ADC226 /* DictionaryAPIChecker.swift */, - 7DEBDB2B29CCE43600ADC226 /* StringConvertibleValue.swift */, - 7DEBDB2C29CCE43600ADC226 /* AllOnesRandomNumberGenerator.swift */, 7DEBDB2729CCE43600ADC226 /* LifetimeTracked.swift */, 7D48BCDE2E51558700D7F6F7 /* LifetimeTrackedStruct.swift */, 7DEBDB2E29CCE43600ADC226 /* LifetimeTracker.swift */, + 7DEBDB2629CCE43600ADC226 /* RandomStableSample.swift */, 7DEBDB2F29CCE43600ADC226 /* RepeatableRandomNumberGenerator.swift */, - 7DEBDB3029CCE43600ADC226 /* SortedCollectionAPIChecker.swift */, - 7DEBDB3129CCE43600ADC226 /* HashableBox.swift */, 7DEBDB3229CCE43600ADC226 /* SetAPIChecker.swift */, + 7DEBDB3029CCE43600ADC226 /* SortedCollectionAPIChecker.swift */, + 7DEBDB2B29CCE43600ADC226 /* StringConvertibleValue.swift */, ); path = Utilities; sourceTree = ""; @@ -1769,12 +1807,12 @@ 7DEBDB3329CCE43600ADC226 /* ConformanceCheckers */ = { isa = PBXGroup; children = ( + 7DEBDB3929CCE43600ADC226 /* CheckBidirectionalCollection.swift */, 7DEBDB3429CCE43600ADC226 /* CheckCollection.swift */, - 7DEBDB3529CCE43600ADC226 /* CheckHashable.swift */, 7DEBDB3629CCE43600ADC226 /* CheckComparable.swift */, 7DEBDB3729CCE43600ADC226 /* CheckEquatable.swift */, + 7DEBDB3529CCE43600ADC226 /* CheckHashable.swift */, 7DEBDB3829CCE43600ADC226 /* CheckSequence.swift */, - 7DEBDB3929CCE43600ADC226 /* CheckBidirectionalCollection.swift */, ); path = ConformanceCheckers; sourceTree = ""; @@ -1783,19 +1821,19 @@ isa = PBXGroup; children = ( 7DEBDB3B29CCE43600ADC226 /* _CollectionState.swift */, - 7DEBDB3C29CCE43600ADC226 /* MinimalRandomAccessCollection.swift */, - 7DEBDB3D29CCE43600ADC226 /* MinimalMutableRandomAccessCollection.swift */, - 7DEBDB3E29CCE43600ADC226 /* MinimalSequence.swift */, - 7DEBDB3F29CCE43600ADC226 /* MinimalMutableRangeReplaceableRandomAccessCollection.swift */, - 7DEBDB4029CCE43600ADC226 /* MinimalBidirectionalCollection.swift */, - 7DEBDB4129CCE43600ADC226 /* MinimalIndex.swift */, - 7DEBDB4229CCE43600ADC226 /* ResettableValue.swift */, - 7DEBDB4329CCE43600ADC226 /* MinimalRangeReplaceableRandomAccessCollection.swift */, - 7DEBDB4429CCE43600ADC226 /* MinimalEncoder.swift */, - 7DEBDB4529CCE43600ADC226 /* MinimalIterator.swift */, 7DEBDB4629CCE43600ADC226 /* _MinimalCollectionCore.swift */, - 7DEBDB4729CCE43600ADC226 /* MinimalDecoder.swift */, + 7DEBDB4029CCE43600ADC226 /* MinimalBidirectionalCollection.swift */, 7DEBDB4829CCE43600ADC226 /* MinimalCollection.swift */, + 7DEBDB4729CCE43600ADC226 /* MinimalDecoder.swift */, + 7DEBDB4429CCE43600ADC226 /* MinimalEncoder.swift */, + 7DEBDB4129CCE43600ADC226 /* MinimalIndex.swift */, + 7DEBDB4529CCE43600ADC226 /* MinimalIterator.swift */, + 7DEBDB3D29CCE43600ADC226 /* MinimalMutableRandomAccessCollection.swift */, + 7DEBDB3F29CCE43600ADC226 /* MinimalMutableRangeReplaceableRandomAccessCollection.swift */, + 7DEBDB3C29CCE43600ADC226 /* MinimalRandomAccessCollection.swift */, + 7DEBDB4329CCE43600ADC226 /* MinimalRangeReplaceableRandomAccessCollection.swift */, + 7DEBDB3E29CCE43600ADC226 /* MinimalSequence.swift */, + 7DEBDB4229CCE43600ADC226 /* ResettableValue.swift */, ); path = MinimalTypes; sourceTree = ""; @@ -1992,7 +2030,9 @@ 7DE9212A29CA70F4004483EB /* TreeSet+Extras.swift in Sources */, 7DE9209A29CA70F4004483EB /* Rope+Append.swift in Sources */, 7DE9203F29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isDisjoint.swift in Sources */, + 7D48BCD22E51524200D7F6F7 /* DynamicArray.swift in Sources */, 7D48BCD32E51524200D7F6F7 /* Box.swift in Sources */, + 7D48BCD52E51524200D7F6F7 /* RigidArray.swift in Sources */, 7DE9208629CA70F4004483EB /* BigString+LosslessStringConvertible.swift in Sources */, 7DE9204329CA70F3004483EB /* _HashTable+Bucket.swift in Sources */, 7DE9216A29CA70F4004483EB /* TreeDictionary.swift in Sources */, @@ -2251,6 +2291,7 @@ files = ( 7DEBDB7F29CCE44A00ADC226 /* CheckBidirectionalCollection.swift in Sources */, 7DE9221829CA8576004483EB /* HashTableTests.swift in Sources */, + 7D48BCF02E51597200D7F6F7 /* Assertions+Containers.swift in Sources */, 7DE9220C29CA8576004483EB /* Availability.swift in Sources */, 7DE9220029CA8576004483EB /* TreeDictionary Smoke Tests.swift in Sources */, 7DEBDB9029CCE44A00ADC226 /* TestContext.swift in Sources */, @@ -2316,6 +2357,9 @@ 7DEBDB8F29CCE44A00ADC226 /* CheckEquatable.swift in Sources */, 7DEBDB7729CCE44A00ADC226 /* HashableBox.swift in Sources */, 7DE9220E29CA8576004483EB /* SampleStrings.swift in Sources */, + 7D48BCE92E5158A100D7F6F7 /* DynamicArrayTests.swift in Sources */, + 7D48BCEA2E5158A100D7F6F7 /* ArrayLayout.swift in Sources */, + 7D48BCEB2E5158A100D7F6F7 /* RigidArrayTests.swift in Sources */, 7D48BCEE2E5158A100D7F6F7 /* BoxTests.swift in Sources */, 7DEBDB9129CCE44A00ADC226 /* CollectionTestCase.swift in Sources */, 7DEBDB1829CBF69F00ADC226 /* _UnsafeBitSet+_Word.swift in Sources */,