From fea1d24e7be3284646858ef7bc9950f685adaa61 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 30 Apr 2025 19:41:15 -0700 Subject: [PATCH] Flesh out DynamicArray Also: - Tweak RigidArray. - Define some default implementations for Container requirements. - Beef up ContiguousContainer. - Add support for testing contiguous access on minimal collections. --- Sources/Future/Arrays/DynamicArray.swift | 915 +++++++++++++++++- Sources/Future/Arrays/RigidArray.swift | 899 +++++++++++++---- Sources/Future/Containers/Container.swift | 149 +++ .../Containers/ContiguousContainer.swift | 43 +- .../Containers/RandomAccessContainer.swift | 13 + ...afeBufferPointer+ContiguousContainer.swift | 31 + ...bleBufferPointer+ContiguousContainer.swift | 32 + ...r.swift => Span+ContiguousContainer.swift} | 8 + .../Span/UnsafeBufferPointer+Additions.swift | 64 +- Tests/DequeTests/RigidDequeTests.swift | 10 +- .../FutureTests/ArrayTests/ArrayLayout.swift | 96 ++ .../ArrayTests/DynamicArrayTests.swift | 804 +++++++++++++++ .../{ => ArrayTests}/RigidArrayTests.swift | 217 ++--- .../FutureTests/ContiguousStorageTests.swift | 11 + Tests/FutureTests/DynamicArrayTests.swift | 212 ---- .../FutureTests/RepeatingContainerTests.swift | 10 +- .../MinimalBidirectionalCollection.swift | 16 +- .../MinimalTypes/MinimalCollection.swift | 16 +- ...MinimalMutableRandomAccessCollection.swift | 16 +- ...ngeReplaceableRandomAccessCollection.swift | 16 +- .../MinimalRandomAccessCollection.swift | 16 +- ...ngeReplaceableRandomAccessCollection.swift | 16 +- .../MinimalTypes/MinimalSequence.swift | 12 +- .../MinimalTypes/_MinimalCollectionCore.swift | 12 +- 24 files changed, 2987 insertions(+), 647 deletions(-) create mode 100644 Sources/Future/Containers/UnsafeBufferPointer+ContiguousContainer.swift create mode 100644 Sources/Future/Containers/UnsafeMutableBufferPointer+ContiguousContainer.swift rename Sources/Future/Span/{Span+Container.swift => Span+ContiguousContainer.swift} (94%) create mode 100644 Tests/FutureTests/ArrayTests/ArrayLayout.swift create mode 100644 Tests/FutureTests/ArrayTests/DynamicArrayTests.swift rename Tests/FutureTests/{ => ArrayTests}/RigidArrayTests.swift (82%) delete mode 100644 Tests/FutureTests/DynamicArrayTests.swift diff --git a/Sources/Future/Arrays/DynamicArray.swift b/Sources/Future/Arrays/DynamicArray.swift index 2c3b03a7..e7e3000a 100644 --- a/Sources/Future/Arrays/DynamicArray.swift +++ b/Sources/Future/Arrays/DynamicArray.swift @@ -20,29 +20,100 @@ public struct DynamicArray: ~Copyable { public init() { _storage = .init(capacity: 0) } - - @inlinable - public init(minimumCapacity: Int) { - _storage = .init(capacity: minimumCapacity) - } - - @inlinable - public init(count: Int, initializedWith generator: (Int) -> Element) { - _storage = .init(count: count, initializedWith: generator) - } } extension DynamicArray: Sendable where Element: Sendable & ~Copyable {} +//MARK: - Initializers + extension DynamicArray where Element: ~Copyable { @inlinable - public var capacity: Int { _storage.capacity } + public init(consuming storage: consuming RigidArray) { + self._storage = storage + } + + @inlinable + public init(capacity: Int) { + _storage = .init(capacity: capacity) + } + + // FIXME: Remove in favor of an OutputSpan-based initializer + @inlinable + public init(count: Int, initializedWith generator: (Int) -> Element) { + self.init(capacity: count, count: count, initializedWith: generator) + } + + // FIXME: Remove in favor of an OutputSpan-based initializer + @inlinable + public init( + capacity: Int, count: Int, initializedWith generator: (Int) -> Element + ) { + _storage = .init( + capacity: capacity, count: count, initializedWith: generator) + } } +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) + } + + @available(SwiftCompatibilitySpan 5.0, *) + @_alwaysEmitIntoClient + @inline(__always) + public init & ~Copyable & ~Escapable>( + capacity: Int? = nil, + copying contents: borrowing C + ) { + self.init(consuming: RigidArray(capacity: capacity, copying: contents)) + } + + @available(SwiftCompatibilitySpan 5.0, *) + @_alwaysEmitIntoClient + @inline(__always) + public init & Sequence>( + capacity: Int? = nil, + copying contents: C + ) { + self.init(consuming: RigidArray(capacity: capacity, 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 { capacity - count } +} + +//MARK: - Span creation + extension DynamicArray where Element: ~Copyable { @available(SwiftCompatibilitySpan 5.0, *) public var span: Span { @lifetime(borrow self) + @inlinable get { _storage.span } @@ -60,56 +131,61 @@ extension DynamicArray where Element: ~Copyable { //MARK: RandomAccessContainer conformance -@available(SwiftCompatibilitySpan 5.0, *) -extension DynamicArray: RandomAccessContainer where Element: ~Copyable { - @lifetime(borrow self) - public func nextSpan(after index: inout Int) -> Span { - _storage.nextSpan(after: &index) - } - - @lifetime(borrow self) - public func previousSpan(before index: inout Int) -> Span { - _storage.previousSpan(before: &index) - } -} - 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 - public var startIndex: Int { 0 } + @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 + @inline(__always) @lifetime(borrow self) public func borrowElement(at index: Int) -> Borrow { _storage.borrowElement(at: index) } } +@available(SwiftCompatibilitySpan 5.0, *) +extension DynamicArray: RandomAccessContainer where Element: ~Copyable { + @inlinable + @lifetime(borrow self) + public func nextSpan(after index: inout Int) -> Span { + _storage.nextSpan(after: &index) + } + + @inlinable + @lifetime(borrow self) + public func previousSpan(before index: inout Int) -> Span { + _storage.previousSpan(before: &index) + } +} + // MARK: - MutableContainer conformance -extension DynamicArray: MutableContainer where Element: ~Copyable { +extension DynamicArray where Element: ~Copyable { @inlinable @lifetime(&self) public mutating func mutateElement(at index: Int) -> Inout { _storage.mutateElement(at: index) } - @available(SwiftCompatibilitySpan 5.0, *) - @lifetime(&self) - public mutating func nextMutableSpan(after index: inout Int) -> MutableSpan { - _storage.nextMutableSpan(after: &index) - } - @inlinable @lifetime(&self) public mutating func swapAt(_ i: Int, _ j: Int) { @@ -117,52 +193,795 @@ extension DynamicArray: MutableContainer where Element: ~Copyable { } } -// MARK: - Range replacement operations - -extension DynamicArray where Element: ~Copyable { - @inlinable - @discardableResult - public mutating func remove(at index: Int) -> Element { - _storage.remove(at: index) +extension DynamicArray: MutableContainer where Element: ~Copyable { + @available(SwiftCompatibilitySpan 5.0, *) + @lifetime(&self) + public mutating func nextMutableSpan(after index: inout Int) -> MutableSpan { + _storage.nextMutableSpan(after: &index) } } +//MARK: Unsafe access + extension DynamicArray where Element: ~Copyable { + // FIXME: Replace this with an OutputSpan-based mutator @inlinable + public mutating func withUnsafeMutableBufferPointer( + _ body: (UnsafeMutableBufferPointer, inout Int) throws(E) -> R + ) throws(E) -> R { + unsafe try _storage.withUnsafeMutableBufferPointer(body) + } +} + +//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 - internal static func _grow(_ capacity: Int) -> Int { - 2 * capacity + @_transparent + public mutating func _ensureFreeCapacity(_ freeCapacity: Int) { + guard _storage.freeCapacity < freeCapacity else { return } + _ensureFreeCapacitySlow(freeCapacity) } @inlinable - public mutating func _ensureFreeCapacity(_ minimumCapacity: Int) { - guard _storage.freeCapacity < minimumCapacity else { return } - reserveCapacity(max(count + minimumCapacity, Self._grow(capacity))) + internal mutating func _ensureFreeCapacitySlow(_ freeCapacity: Int) { + let newCapacity = Swift.max( + count + freeCapacity, + _growDynamicArrayCapacity(capacity)) + reallocate(capacity: newCapacity) + } +} + +//MARK: - Removal operations + +extension DynamicArray 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 + @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 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(`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(`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(`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 all the elements that satisfy the given predicate. + /// + /// Use this method to remove every element in a container that meets + /// particular criteria. The order of the remaining elements is preserved. + /// + /// - Parameter shouldBeRemoved: A closure that takes an element of the + /// sequence as its argument and returns a Boolean value indicating + /// whether the element should be removed from the array. + /// + /// - Complexity: O(`count`) + @available(SwiftCompatibilitySpan 5.0, *) + @_alwaysEmitIntoClient + public mutating func removeAll( + where shouldBeRemoved: (borrowing Element) throws(E) -> Bool + ) throws(E) { + // FIXME: Remove this in favor of a standard algorithm. + let suffixStart = try _halfStablePartition(isSuffixElement: shouldBeRemoved) + removeSubrange(suffixStart...) + } +} + +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: - Insertion 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 extend 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 { + /// 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(SwiftCompatibilitySpan 5.0, *) + @_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) + } + } + + @available(SwiftCompatibilitySpan 5.0, *) + public mutating func _appendContainer< + C: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing C + ) { + var i = newElements.startIndex + while true { + let span = newElements.nextSpan(after: &i) + if span.isEmpty { break } + self.append(copying: span) + } + } + + /// Copies the elements of a container 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 container whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`), when amortized over many invocations + /// over the same array. + @available(SwiftCompatibilitySpan 5.0, *) + @_alwaysEmitIntoClient + public mutating func append< + C: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing C + ) { + _appendContainer(copying: newElements) + } + + /// Copies the elements of a container 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 container whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`), when amortized over many invocations + /// over the same array. + @available(SwiftCompatibilitySpan 5.0, *) + @_alwaysEmitIntoClient + public mutating func append< + C: Container & Sequence + >( + copying newElements: borrowing C + ) { + _appendContainer(copying: newElements) + } +} + +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(`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 { + /// 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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. @inlinable - public mutating func append(contentsOf items: some Sequence) { - for item in items { - append(item) - } + 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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @available(SwiftCompatibilitySpan 5.0, *) + @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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @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) + } + + @available(SwiftCompatibilitySpan 5.0, *) + @inlinable + internal mutating func _insertContainer< + C: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing C, at index: Int + ) { + // FIXME: Avoiding moving the subsequent elements twice. + let newCount = newElements.count + _ensureFreeCapacity(newCount) + _storage._insertContainer( + at: index, copying: newElements, newCount: newCount) + } + + /// Copies the elements of a container 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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @available(SwiftCompatibilitySpan 5.0, *) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing C, at index: Int + ) { + _insertContainer(copying: newElements, at: index) + } + + /// Copies the elements of a container 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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @available(SwiftCompatibilitySpan 5.0, *) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & Collection + >( + copying newElements: borrowing C, at index: Int + ) { + _insertContainer(copying: newElements, at: index) + } +} + +//MARK: - Range replacement + +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(SwiftCompatibilitySpan 5.0, *) + @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) + } + + @available(SwiftCompatibilitySpan 5.0, *) + @inlinable + public mutating func _replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copyingContainer newElements: borrowing C + ) { + // FIXME: Avoiding moving the subsequent elements twice. + let c = newElements.count + _ensureFreeCapacity(c) + _storage._replaceSubrange( + subrange, copyingContainer: newElements, newCount: c) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// 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 container 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(SwiftCompatibilitySpan 5.0, *) + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copying newElements: borrowing C + ) { + _replaceSubrange(subrange, copyingContainer: newElements) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// 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 container 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(SwiftCompatibilitySpan 5.0, *) + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & Collection + >( + _ subrange: Range, + copying newElements: borrowing C + ) { + _replaceSubrange(subrange, copyingContainer: newElements) } } diff --git a/Sources/Future/Arrays/RigidArray.swift b/Sources/Future/Arrays/RigidArray.swift index 7a505fc2..bb7dd9d2 100644 --- a/Sources/Future/Arrays/RigidArray.swift +++ b/Sources/Future/Arrays/RigidArray.swift @@ -45,14 +45,28 @@ extension RigidArray: @unchecked Sendable where Element: Sendable & ~Copyable {} //MARK: - Initializers extension RigidArray where Element: ~Copyable { + // FIXME: Remove in favor of an OutputSpan-based initializer @inlinable - public init(count: Int, initializedWith generator: (Int) -> Element) { - unsafe _storage = .allocate(capacity: count) + public init( + capacity: Int, + count: Int, + initializedWith generator: (Int) -> Element + ) { + precondition( + count >= 0 && count <= capacity, + "RigidArray capacity overflow") + unsafe _storage = .allocate(capacity: capacity) for i in 0 ..< count { unsafe _storage.initializeElement(at: i, to: generator(i)) } _count = count } + + // FIXME: Remove in favor of an OutputSpan-based initializer + @inlinable + public init(count: Int, initializedWith generator: (Int) -> Element) { + self.init(capacity: count, count: count, initializedWith: generator) + } } extension RigidArray /*where Element: Copyable*/ { @@ -73,9 +87,33 @@ extension RigidArray /*where Element: Copyable*/ { extension RigidArray /*where Element: Copyable*/ { @_alwaysEmitIntoClient @inline(__always) - public init(capacity: Int? = nil, copying contents: some Collection) { + public init( + capacity: Int, + copying contents: some Sequence + ) { + self.init(capacity: capacity) + self.append(copying: contents) + } + + @available(SwiftCompatibilitySpan 5.0, *) + @_alwaysEmitIntoClient + @inline(__always) + public init & Sequence>( + capacity: Int, + copying contents: C + ) { + 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(contentsOf: contents) + self.append(copying: contents) } @available(SwiftCompatibilitySpan 5.0, *) @@ -162,7 +200,9 @@ extension RigidArray where Element: ~Copyable { @available(SwiftCompatibilitySpan 5.0, *) @inlinable @lifetime(&self) - internal mutating func _mutableSpan(in range: Range) -> MutableSpan { + internal mutating func _mutableSpan( + in range: Range + ) -> MutableSpan { let result = unsafe MutableSpan(_unsafeElements: _items.extracting(range)) return unsafe _overrideLifetime(result, mutating: &self) } @@ -184,7 +224,41 @@ extension RigidArray where Element: ~Copyable { } } -//MARK: - RandomAccessContainer conformance +//MARK: - RandomAccessContainer and MutableContainer conformance + +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)) } + + @inlinable + @lifetime(borrow self) + public func borrowElement(at index: Int) -> Borrow { + precondition(index >= 0 && index < _count, "Index out of bounds") + return unsafe Borrow( + unsafeAddress: _storage.baseAddress.unsafelyUnwrapped.advanced(by: index), + borrowing: self + ) + } +} @available(SwiftCompatibilitySpan 5.0, *) extension RigidArray: RandomAccessContainer where Element: ~Copyable { @@ -201,51 +275,6 @@ extension RigidArray: RandomAccessContainer where Element: ~Copyable { } } -extension RigidArray where Element: ~Copyable { - public typealias Index = Int - - @inlinable - public var isEmpty: Bool { count == 0 } - - @inlinable - public var count: Int { _count } - - @inlinable - public var startIndex: Int { 0 } - - @inlinable - public var endIndex: Int { count } - - @inlinable - public var indices: Range { unsafe Range(uncheckedBounds: (0, count)) } - - @inlinable - @lifetime(borrow self) - public func borrowElement(at index: Int) -> Borrow { - precondition(index >= 0 && index < _count, "Index out of bounds") - return unsafe Borrow( - unsafeAddress: _storage.baseAddress.unsafelyUnwrapped.advanced(by: index), - borrowing: self - ) - } - - @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) - } -} - -//MARK: - MutableContainer conformance - -@available(SwiftCompatibilitySpan 5.0, *) -extension RigidArray: MutableContainer where Element: ~Copyable { - @lifetime(&self) - public mutating func nextMutableSpan(after index: inout Int) -> MutableSpan { - _mutableSpan(in: _contiguousSubrange(following: &index)) - } -} - extension RigidArray where Element: ~Copyable { @inlinable @lifetime(&self) @@ -256,6 +285,24 @@ extension RigidArray where Element: ~Copyable { mutating: &self ) } + + @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) + } +} + +@available(SwiftCompatibilitySpan 5.0, *) +extension RigidArray: MutableContainer where Element: ~Copyable { + @lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Int + ) -> MutableSpan { + _mutableSpan(in: _contiguousSubrange(following: &index)) + } } //MARK: Unsafe access @@ -275,10 +322,11 @@ extension RigidArray where Element: ~Copyable { extension RigidArray where Element: ~Copyable { @inlinable - public mutating func setCapacity(_ newCapacity: Int) { + 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 newStorage: UnsafeMutableBufferPointer = .allocate( + capacity: newCapacity) let i = unsafe newStorage.moveInitialize(fromContentsOf: self._items) assert(i == count) unsafe _storage.deallocate() @@ -288,7 +336,7 @@ extension RigidArray where Element: ~Copyable { @inlinable public mutating func reserveCapacity(_ n: Int) { guard capacity < n else { return } - setCapacity(n) + reallocate(capacity: n) } } @@ -320,8 +368,10 @@ extension RigidArray where Element: ~Copyable { 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 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) } @@ -333,11 +383,14 @@ extension RigidArray where Element: ~Copyable { 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 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))) + return unsafe _storage.extracting( + Range(uncheckedBounds: (index, index + count))) } } @@ -371,17 +424,23 @@ extension RigidArray where Element: ~Copyable { /// Removes 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. + /// 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. + /// `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() + 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 } @@ -407,8 +466,8 @@ extension RigidArray where Element: ~Copyable { /// Removes the specified subrange of elements from the array. /// - /// All the elements following the specified subrange are moved to close the resulting - /// gap. + /// 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. @@ -424,6 +483,18 @@ extension RigidArray where Element: ~Copyable { _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 { @@ -442,41 +513,34 @@ extension RigidArray where Element: ~Copyable { public mutating func removeAll( where shouldBeRemoved: (borrowing Element) throws(E) -> Bool ) throws(E) { + // FIXME: Remove this in favor of a standard algorithm. let suffixStart = try _halfStablePartition(isSuffixElement: shouldBeRemoved) removeSubrange(suffixStart...) } +} - /// Removes and returns the last element of the array. +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`. + /// - 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() } - - /// 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) { - removeSubrange(bounds.relative(to: indices)) - } } //MARK: - Insertion 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. + /// 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. /// @@ -490,48 +554,156 @@ extension RigidArray where Element: ~Copyable { } 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(contentsOf items: some Sequence) { - var (it, c) = unsafe items._copyContents(initializing: _freeSpace) - precondition(it.next() == nil, "RigidArray capacity overflow") - _count += c + 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 } - // FIXME: We need to nail the naming of this: we'll have consuming variants, too, and we need to interoperate with Collection's methods. + /// 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(SwiftCompatibilitySpan 5.0, *) @_alwaysEmitIntoClient public mutating func append(copying items: Span) { - precondition(items.count <= freeCapacity, "RigidArray capacity overflow") unsafe items.withUnsafeBufferPointer { source in - let c = unsafe source._copyContents(initializing: _freeSpace).1 - _count &+= c + unsafe self.append(copying: source) } } - // FIXME: We need to nail the naming of this: we'll have consuming variants, too, and we need to interoperate with Collection's methods. + @_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") + } + + @available(SwiftCompatibilitySpan 5.0, *) + @inlinable + internal mutating func _appendContainer< + C: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing C + ) { + let (copied, end) = unsafe _freeSpace._initializePrefix( + copying: newElements) + precondition(end == newElements.endIndex, "RigidArray capacity overflow") + _count += copied + } + + /// Copies the elements of a container to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// container, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A container whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`) @available(SwiftCompatibilitySpan 5.0, *) @_alwaysEmitIntoClient + @inline(__always) public mutating func append & ~Copyable & ~Escapable>( - copying items: borrowing C + copying newElements: borrowing C ) { - let (copied, end) = unsafe _freeSpace._initializePrefix(copying: items) - precondition(end == items.endIndex, "RigidArray capacity overflow") - _count += copied + _appendContainer(copying: newElements) + } + + /// Copies the elements of a container to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// container, 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`. + @available(SwiftCompatibilitySpan 5.0, *) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append< + C: Container & Sequence + >(copying newElements: C) { + _appendContainer(copying: newElements) } } 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. + /// 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 - /// collection. + /// 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. + /// 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. @@ -554,126 +726,292 @@ extension RigidArray where Element: ~Copyable { } extension RigidArray { + /// 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 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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. @inlinable - public mutating func insert(contentsOf items: some Collection, at index: Int) { - precondition(index >= 0 && index <= _count, "Index out of bounds") - let c = items.count - precondition(c <= freeCapacity, "RigidArray capacity overflow") - let gap = unsafe _openGap(at: index, count: c) - var (it, copied) = unsafe items._copyContents(initializing: gap) - precondition(it.next() == nil && copied == c, "Broken Collection: count doesn't match contents") - _count += c - } - - @available(SwiftCompatibilitySpan 5.0, *) - @inlinable - internal mutating func _insert(copying items: UnsafeBufferPointer, at index: Int) { - guard items.count > 0 else { return } - precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - let gap = unsafe _openGap(at: index, count: items.count) + 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: items.baseAddress.unsafelyUnwrapped, count: items.count) - _count += items.count + from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count) + _count += newElements.count } - // FIXME: We need to nail the naming of this: we'll have consuming variants, too, and we need to interoperate with Collection's methods. + /// 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 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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. @available(SwiftCompatibilitySpan 5.0, *) @inlinable - public mutating func insert(copying items: Span, at index: Int) { - precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - unsafe items.withUnsafeBufferPointer { unsafe self._insert(copying: $0, at: index) } + public mutating func insert( + copying newElements: Span, at index: Int + ) { + precondition( + newElements.count <= freeCapacity, + "RigidArray capacity overflow") + unsafe newElements.withUnsafeBufferPointer { + unsafe self.insert(copying: $0, at: index) + } } - // FIXME: We need to nail the naming of this: we'll have consuming variants, too, and we need to interoperate with Collection's methods. - @available(SwiftCompatibilitySpan 5.0, *) - @_alwaysEmitIntoClient - public mutating func insert & ~Copyable & ~Escapable>( - copying items: borrowing C, at index: Int + @inlinable + internal mutating func _insertCollection( + at index: Int, + copying items: some Collection, + newCount: Int ) { precondition(index >= 0 && index <= _count, "Index out of bounds") - let c = items.count - precondition(c <= freeCapacity, "RigidArray capacity overflow") - let target = unsafe _openGap(at: index, count: c) + 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 + } + + @available(SwiftCompatibilitySpan 5.0, *) + @inlinable + internal mutating func _insertContainer< + C: Container & ~Copyable & ~Escapable + >( + at index: Int, + copying items: borrowing C, + newCount: Int + ) { + precondition(index >= 0 && index <= _count, "Index out of bounds") + precondition(newCount <= freeCapacity, "RigidArray capacity overflow") + let target = unsafe _openGap(at: index, count: newCount) let (copied, end) = unsafe target._initializePrefix(copying: items) precondition( - copied == c && end == items.endIndex, + copied == newCount && end == items.endIndex, "Broken Container: count doesn't match contents") - _count += c + _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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @inlinable + @inline(__always) + public mutating func insert( + copying newElements: some Collection, at index: Int + ) { + _insertCollection( + at: index, copying: newElements, newCount: newElements.count) + } + + /// Copies the elements of a container 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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @available(SwiftCompatibilitySpan 5.0, *) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing C, at index: Int + ) { + _insertContainer( + at: index, copying: newElements, newCount: newElements.count) + } + + /// Copies the elements of a container 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(*n* + *m*), where *n* is count of this array and + /// *m* is the count of `newElements`. + @available(SwiftCompatibilitySpan 5.0, *) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & Collection + >( + copying newElements: borrowing C, at index: Int + ) { + _insertContainer( + at: index, copying: newElements, newCount: newElements.count) } } //MARK: - Range replacement -extension RigidArray { - /// Perform a range replacement up to populating the newly opened gap. This deinitializes removed content, rearranges trailing - /// elements to be at their final size, and sets the container's new count. +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. + /// - Returns: A buffer pointer addressing the newly opened gap, to be + /// initialized by the caller. @inlinable 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") + 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) + _ = unsafe _openGap( + at: subrange.upperBound, count: newCount - subrange.count) } else if newCount < subrange.count { - _closeGap(at: subrange.lowerBound + newCount, count: subrange.count - newCount) + _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) } +} - /// 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(contentsOf: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 - public mutating func replaceSubrange( - _ subrange: Range, - with newElements: __owned some Collection - ) { - let c = newElements.count - let gap = unsafe _gapForReplacement(of: subrange, withNewCount: c) - var (it, copied) = unsafe newElements._copyContents(initializing: gap) - precondition(it.next() == nil && copied == c, "Broken Collection: count doesn't match contents") - } - +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. + /// 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(contentsOf:at:)` method instead is preferred in this case. + /// 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 @@ -690,24 +1028,67 @@ extension RigidArray { @inlinable public mutating func replaceSubrange( _ subrange: Range, - with newElements: UnsafeBufferPointer + copying newElements: UnsafeBufferPointer ) { - let gap = unsafe _gapForReplacement(of: subrange, withNewCount: newElements.count) - unsafe gap.initializeAll(fromContentsOf: newElements) + 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 span. + /// 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. + /// 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(contentsOf:at:)` method instead is preferred in this case. + /// the `insert(copying:at:)` method instead is preferred in this case. /// - /// Likewise, if you pass a zero-length collection as the `newElements` + /// 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 + 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. @@ -726,20 +1107,46 @@ extension RigidArray { copying newElements: Span ) { unsafe newElements.withUnsafeBufferPointer { buffer in - unsafe self.replaceSubrange(subrange, with: buffer) + unsafe self.replaceSubrange(subrange, copying: buffer) } } - /// Replaces the specified subrange of elements by copying the elements of the given container. + @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. + /// 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(contentsOf:at:)` method instead is preferred in this case. + /// 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 @@ -753,17 +1160,109 @@ extension RigidArray { /// /// - 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 + ) { + _replaceSubrange( + subrange, copyingCollection: newElements, newCount: newElements.count) + } + @available(SwiftCompatibilitySpan 5.0, *) @inlinable - public mutating func replaceSubrange & ~Copyable & ~Escapable>( + public mutating func _replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copyingContainer newElements: borrowing C, + newCount: Int + ) { + let gap = unsafe _gapForReplacement(of: subrange, withNewCount: newCount) + let (copied, end) = unsafe gap._initializePrefix(copying: newElements) + precondition( + copied == newCount && end == newElements.endIndex, + "Broken Container: count doesn't match contents") + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// 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 container 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(SwiftCompatibilitySpan 5.0, *) + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( _ subrange: Range, copying newElements: borrowing C ) { - let c = newElements.count - let gap = unsafe _gapForReplacement(of: subrange, withNewCount: c) - let (copied, end) = unsafe gap._initializePrefix(copying: newElements) - precondition( - copied == c && end == newElements.endIndex, - "Broken Container: count doesn't match contents") + _replaceSubrange( + subrange, copyingContainer: newElements, newCount: newElements.count) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given container. + /// + /// 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 container 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(SwiftCompatibilitySpan 5.0, *) + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & Collection + >( + _ subrange: Range, + copying newElements: C + ) { + _replaceSubrange( + subrange, copyingContainer: newElements, newCount: newElements.count) } } diff --git a/Sources/Future/Containers/Container.swift b/Sources/Future/Containers/Container.swift index 7af024a2..f8b997fa 100644 --- a/Sources/Future/Containers/Container.swift +++ b/Sources/Future/Containers/Container.swift @@ -85,6 +85,123 @@ public protocol Container: ~Copyable, ~Escapable { @available(SwiftCompatibilitySpan 5.0, *) extension Container where Self: ~Copyable & ~Escapable { + @inlinable + public func _defaultIndex(_ i: Index, advancedBy distance: Int) -> Index { + precondition( + distance >= 0, + "Only BidirectionalContainers can be advanced by a negative amount") + + var i = index(alignedDown: i) + var distance = distance + + // FIXME: This implementation can be wasteful for contiguous containers, + // as iterating over spans will overshoot the target immediately. + // Reintroducing `nextSpan(after:maximumCount:)` would help avoid + // having to use a second loop to refine the result, but it would + // complicate conformances. + + // Skip forward until we find the span that contains our target. + while distance > 0 { + var j = i + let span = self.nextSpan(after: &j) + precondition( + !span.isEmpty, + "Can't advance index beyond the end of the container") + guard span.count <= distance else { break } + i = j + distance &-= span.count + } + // Step through to find the precise target. + while distance > 0 { + self.formIndex(after: &i) + distance &-= 1 + } + return i + } + + @inlinable + public func _defaultDistance(from start: Index, to end: Index) -> Int { + var start = index(alignedDown: start) + let end = index(alignedDown: end) + if start > end { + return -_defaultDistance(from: end, to: start) + } + var count = 0 + while start != end { + count = count + 1 + formIndex(after: &start) + } + return count + } + + @inlinable + public func _defaultFormIndex( + _ i: inout Index, + advancedBy distance: inout Int, + limitedBy limit: Index + ) { + precondition( + distance >= 0, + "Only BidirectionalContainers can be advanced by a negative amount") + + i = index(alignedDown: i) + let limit = index(alignedDown: limit) + + // Skip forward until we find the span that contains our target. + while distance > 0 { + var j = i + let span = self.nextSpan(after: &j) + precondition( + !span.isEmpty, + "Can't advance index beyond the end of the container") + guard span.count <= distance, j < limit else { + break + } + i = j + distance &-= span.count + } + // Step through to find the precise target. + while distance != 0 { + if i == limit { + return + } + formIndex(after: &i) + distance &-= 1 + } + } +} + +@available(SwiftCompatibilitySpan 5.0, *) +extension Container where Self: ~Copyable & ~Escapable { + @inlinable + public var isEmpty: Bool { + return startIndex == endIndex + } + + @inlinable + public func formIndex(after i: inout Index) { + i = self.index(after: i) + } + + @inlinable + public func distance(from start: Index, to end: Index) -> Int { + _defaultDistance(from: start, to: end) + } + + @inlinable + public func index(_ index: Index, offsetBy n: Int) -> Index { + _defaultIndex(index, advancedBy: n) + } + + @inlinable + public func formIndex( + _ i: inout Index, + offsetBy distance: inout Int, + limitedBy limit: Index + ) { + _defaultFormIndex(&i, advancedBy: &distance, limitedBy: limit) + } + @inlinable public func index(alignedDown index: Index) -> Index { index } @@ -98,8 +215,40 @@ extension Container where Self: ~Copyable & ~Escapable { public func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index?? { nil } } +@available(SwiftCompatibilitySpan 5.0, *) +extension Container where Self: Sequence { + @inlinable + public var underestimatedCount: Int { count } +} + @available(SwiftCompatibilitySpan 5.0, *) extension Container where Self: Collection { + // Resolve ambiguities between default implementations between Collection + // and Container. + + @inlinable + public var underestimatedCount: Int { count } + + @inlinable + public var isEmpty: Bool { + return startIndex == endIndex + } + + @inlinable + public func formIndex(after i: inout Index) { + i = self.index(after: i) + } + + @inlinable + public func distance(from start: Index, to end: Index) -> Int { + _defaultDistance(from: start, to: end) + } + + @inlinable + public func index(_ index: Index, offsetBy n: Int) -> Index { + _defaultIndex(index, advancedBy: n) + } + @inlinable public func _customIndexOfEquatableElement(_ element: borrowing Element) -> Index?? { nil } diff --git a/Sources/Future/Containers/ContiguousContainer.swift b/Sources/Future/Containers/ContiguousContainer.swift index 853e7462..7f966a16 100644 --- a/Sources/Future/Containers/ContiguousContainer.swift +++ b/Sources/Future/Containers/ContiguousContainer.swift @@ -10,18 +10,38 @@ // //===----------------------------------------------------------------------===// -@available(SwiftCompatibilitySpan 5.0, *) -public protocol ContiguousContainer: /*RandomAccessContainer*/ ~Copyable, ~Escapable { - associatedtype Element: ~Copyable/* & ~Escapable*/ - - var span: Span { @lifetime(copy self) get } +@available(SwiftStdlib 6.2, *) +public protocol ContiguousContainer + : RandomAccessContainer, ~Copyable, ~Escapable +{ + var span: Span { @lifetime(borrow self) get } } -@available(SwiftCompatibilitySpan 5.0, *) -extension Span: ContiguousContainer where Element: ~Copyable { - public var span: Self { - @lifetime(copy self) - get { self } +@available(SwiftStdlib 6.2, *) +extension ContiguousContainer +where Self: ~Copyable & ~Escapable, Index == Int { + @inlinable + @lifetime(borrow self) + public func borrowElement(at index: Index) -> Borrow { + span.borrowElement(at: index - startIndex) + } + + @inlinable + @lifetime(borrow self) + public func nextSpan(after index: inout Index) -> Span { + var i = index - startIndex + let result = span.nextSpan(after: &i) + index = i + startIndex + return result + } + + @inlinable + @lifetime(borrow self) + public func previousSpan(before index: inout Index) -> Span { + var i = index - startIndex + let result = span.previousSpan(before: &i) + index = i + startIndex + return result } } @@ -33,6 +53,3 @@ extension ContiguousArray: ContiguousContainer {} @available(SwiftStdlib 6.2, *) extension CollectionOfOne: ContiguousContainer {} - -@available(SwiftStdlib 6.2, *) -extension String.UTF8View: ContiguousContainer {} diff --git a/Sources/Future/Containers/RandomAccessContainer.swift b/Sources/Future/Containers/RandomAccessContainer.swift index f2bfe921..7caf2094 100644 --- a/Sources/Future/Containers/RandomAccessContainer.swift +++ b/Sources/Future/Containers/RandomAccessContainer.swift @@ -66,6 +66,19 @@ where Self: ~Copyable & ~Escapable, Index: Strideable, Index.Stride == Int // Note: Range checks are deferred until element access. index.advance(by: &distance, limitedBy: limit) } + + + @lifetime(borrow self) + @inlinable + public func nextSpan( + after index: inout Index, maximumCount: Int + ) -> Span { + precondition(maximumCount >= 0, "Maximum count must be non-negative") + let span = self.nextSpan(after: &index) + if span.count <= maximumCount { return span } + index = index.advanced(by: maximumCount - span.count) + return span._extracting(first: maximumCount) + } } // Disambiguate parallel extensions on RandomAccessContainer and RandomAccessCollection diff --git a/Sources/Future/Containers/UnsafeBufferPointer+ContiguousContainer.swift b/Sources/Future/Containers/UnsafeBufferPointer+ContiguousContainer.swift new file mode 100644 index 00000000..a6206e9b --- /dev/null +++ b/Sources/Future/Containers/UnsafeBufferPointer+ContiguousContainer.swift @@ -0,0 +1,31 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +@available(SwiftStdlib 6.2, *) +extension UnsafeBufferPointer: @unsafe ContiguousContainer +where Element: ~Copyable +{ + public var span: Span { + @inlinable + @lifetime(borrow self) + get { + unsafe Span(_unsafeElements: self) + } + } + + @inlinable + @lifetime(borrow self) + public func borrowElement(at index: Int) -> Borrow { + precondition(index >= 0 && index < count, "Index out of bounds") + let ptr = unsafe baseAddress.unsafelyUnwrapped + index + return unsafe Borrow(unsafeAddress: ptr, borrowing: self) + } +} diff --git a/Sources/Future/Containers/UnsafeMutableBufferPointer+ContiguousContainer.swift b/Sources/Future/Containers/UnsafeMutableBufferPointer+ContiguousContainer.swift new file mode 100644 index 00000000..50a1bcab --- /dev/null +++ b/Sources/Future/Containers/UnsafeMutableBufferPointer+ContiguousContainer.swift @@ -0,0 +1,32 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +@available(SwiftStdlib 6.2, *) +extension UnsafeMutableBufferPointer: @unsafe ContiguousContainer +where Element: ~Copyable +{ + /// The contents of `self` must not be mutated while the returned span exists. + public var span: Span { + @inlinable + @lifetime(borrow self) + get { + unsafe Span(_unsafeElements: self) + } + } + + @inlinable + @lifetime(borrow self) + public func borrowElement(at index: Int) -> Borrow { + precondition(index >= 0 && index < count, "Index out of bounds") + let ptr = unsafe baseAddress.unsafelyUnwrapped + index + return unsafe Borrow(unsafeAddress: ptr, borrowing: self) + } +} diff --git a/Sources/Future/Span/Span+Container.swift b/Sources/Future/Span/Span+ContiguousContainer.swift similarity index 94% rename from Sources/Future/Span/Span+Container.swift rename to Sources/Future/Span/Span+ContiguousContainer.swift index 5f032241..6578e62e 100644 --- a/Sources/Future/Span/Span+Container.swift +++ b/Sources/Future/Span/Span+ContiguousContainer.swift @@ -39,6 +39,14 @@ extension Span: RandomAccessContainer where Element: ~Copyable { } } +@available(SwiftStdlib 6.2, *) +extension Span: ContiguousContainer where Element: ~Copyable { + public var span: Self { + @lifetime(copy self) + get { self } + } +} + @available(SwiftStdlib 6.2, *) extension Span where Element: ~Copyable { @usableFromInline diff --git a/Sources/Future/Span/UnsafeBufferPointer+Additions.swift b/Sources/Future/Span/UnsafeBufferPointer+Additions.swift index 3a4c7271..efb123b0 100644 --- a/Sources/Future/Span/UnsafeBufferPointer+Additions.swift +++ b/Sources/Future/Span/UnsafeBufferPointer+Additions.swift @@ -49,37 +49,35 @@ extension UnsafeMutableRawBufferPointer { extension UnsafeMutableBufferPointer { - /// 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. + /// 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 `buffer` must be fully initialized. + /// entirely uninitialized, while `source` must be fully initialized. /// - /// The count of `buffer` must not be greater than `self.count`. + /// The `source` buffer must fit entirely in `self`. + /// + /// - Returns: The index after the last item that was initialized in this buffer. @inlinable - internal mutating func _initializeAndDropPrefix(copying buffer: UnsafeBufferPointer) { - if buffer.isEmpty { return } - precondition(buffer.count <= self.count) + internal func _initializePrefix(copying source: UnsafeBufferPointer) -> Int { + if source.isEmpty { return 0 } + precondition(source.count <= self.count) unsafe self.baseAddress.unsafelyUnwrapped.initialize( - from: buffer.baseAddress.unsafelyUnwrapped, count: buffer.count) - unsafe self = self.extracting(buffer.count...) + from: source.baseAddress.unsafelyUnwrapped, count: source.count) + return source.count } - /// 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. + /// 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 count of `span` must not be greater than `self.count`. + /// The `source` span must fit entirely in `self`. + /// + /// - Returns: The index after the last item that was initialized in this buffer. @available(SwiftCompatibilitySpan 5.0, *) @inlinable - internal mutating func _initializeAndDropPrefix(copying span: Span) { - unsafe span.withUnsafeBufferPointer { buffer in - unsafe self._initializeAndDropPrefix(copying: buffer) - } + internal func _initializePrefix(copying source: Span) -> Int { + unsafe source.withUnsafeBufferPointer { unsafe self._initializePrefix(copying: $0) } } /// Initialize all slots in this buffer by copying data from `items`, which must fit entirely @@ -114,4 +112,34 @@ extension UnsafeMutableBufferPointer { } return (self.count - target.count, i) } + + /// 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 = unsafe _initializePrefix(copying: source) + unsafe self = self.extracting(i...) + } + + /// 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(SwiftCompatibilitySpan 5.0, *) + @inlinable + internal mutating func _initializeAndDropPrefix(copying span: Span) { + unsafe span.withUnsafeBufferPointer { buffer in + unsafe self._initializeAndDropPrefix(copying: buffer) + } + } } diff --git a/Tests/DequeTests/RigidDequeTests.swift b/Tests/DequeTests/RigidDequeTests.swift index d0057ee6..15534d2f 100644 --- a/Tests/DequeTests/RigidDequeTests.swift +++ b/Tests/DequeTests/RigidDequeTests.swift @@ -1,9 +1,13 @@ +//===----------------------------------------------------------------------===// // -// RepeatingContainerTests.swift -// swift-collections +// This source file is part of the Swift Collections open source project // -// Created by Karoy Lorentey on 2025-04-21. +// 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 diff --git a/Tests/FutureTests/ArrayTests/ArrayLayout.swift b/Tests/FutureTests/ArrayTests/ArrayLayout.swift new file mode 100644 index 00000000..9a8563ac --- /dev/null +++ b/Tests/FutureTests/ArrayTests/ArrayLayout.swift @@ -0,0 +1,96 @@ +//===----------------------------------------------------------------------===// +// +// 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 _CollectionsTestSupport +import Future + +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 = #file, + 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 + } + } +} + +extension RigidArray where Element: ~Copyable { + init(layout: ArrayLayout, using generator: (Int) -> Element) { + self.init( + capacity: layout.capacity, + count: layout.count, + initializedWith: generator) + } +} + +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) + } +} diff --git a/Tests/FutureTests/ArrayTests/DynamicArrayTests.swift b/Tests/FutureTests/ArrayTests/DynamicArrayTests.swift new file mode 100644 index 00000000..e45f14c6 --- /dev/null +++ b/Tests/FutureTests/ArrayTests/DynamicArrayTests.swift @@ -0,0 +1,804 @@ +//===----------------------------------------------------------------------===// +// +// 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 +import _CollectionsTestSupport +import Future +import Synchronization + +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.nextSpan(after: &i) + expectEqual(i, layout.count) + expectTrue(first.isIdentical(to: whole)) + let second = a.nextSpan(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.previousSpan(before: &i) + expectEqual(i, 0) + expectTrue(first.isIdentical(to: whole)) + let second = a.previousSpan(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_withUnsafeMutableBufferPointer() { + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in + withLifetimeTracking { tracker in + var a = tracker.dynamicArray(layout: layout) + unsafe a.withUnsafeMutableBufferPointer { buffer, count in + expectEqual(buffer.count, layout.capacity) + expectEqual(count, layout.count) + unsafe buffer.extracting(0 ..< count).deinitialize() + expectEqual(tracker.instances, 0) + count = 0 + } + expectEqual(a.count, 0) + + unsafe a.withUnsafeMutableBufferPointer { buffer, count in + expectEqual(buffer.count, layout.capacity) + expectEqual(count, 0) + for i in 0 ..< buffer.count { + unsafe buffer.initializeElement(at: i, to: tracker.instance(for: -i)) + count += 1 + } + expectEqual(tracker.instances, layout.capacity) + } + expectEqual(a.count, layout.capacity) + + struct TestError: Error {} + + expectThrows({ + unsafe try a.withUnsafeMutableBufferPointer { buffer, count in + expectEqual(tracker.instances, layout.capacity) + while count > 0 { + if count == layout.count { break } + unsafe buffer.deinitializeElement(at: count - 1) + count -= 1 + } + throw TestError() + } + }) { 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.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) + + + array.append( + copying: RigidArray(count: 300) { tracker.instance(for: 100 + $0) }) + 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) + } + } + } + } + } + } +} diff --git a/Tests/FutureTests/RigidArrayTests.swift b/Tests/FutureTests/ArrayTests/RigidArrayTests.swift similarity index 82% rename from Tests/FutureTests/RigidArrayTests.swift rename to Tests/FutureTests/ArrayTests/RigidArrayTests.swift index 60d1b3b3..171f6305 100644 --- a/Tests/FutureTests/RigidArrayTests.swift +++ b/Tests/FutureTests/ArrayTests/RigidArrayTests.swift @@ -1,85 +1,18 @@ +//===----------------------------------------------------------------------===// // -// RepeatingContainerTests.swift -// swift-collections +// This source file is part of the Swift Collections open source project // -// Created by Karoy Lorentey on 2025-04-21. +// 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 import _CollectionsTestSupport import Future -struct ArrayLayout { - var capacity: Int - var count: Int - - init(capacity: Int, count: Int) { - precondition(count >= 0 && count <= capacity) - self.capacity = capacity - self.count = count - } -} - -extension RigidArray where Element: ~Copyable { - init(layout: ArrayLayout, using generator: (Int) -> Element) { - self.init(capacity: layout.capacity) - for i in 0 ..< layout.count { - self.append(generator(i)) - } - } -} - -extension LifetimeTracker { - func rigidArray(layout: ArrayLayout) -> RigidArray> { - rigidArray(layout: layout, using: { $0 }) - } - - func rigidArray( - layout: ArrayLayout, - using generator: (Int) -> Element - ) -> RigidArray> { - RigidArray(layout: layout, using: { self.instance(for: generator($0)) }) - } -} - -func withSomeArrayLayouts( - _ label: String, - ofCapacities capacities: some Sequence, - file: StaticString = #file, - 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 - } - } -} - @available(SwiftStdlib 6.0, *) class RigidArrayTests: CollectionTestCase { func test_validate_Container() { @@ -145,16 +78,18 @@ class RigidArrayTests: CollectionTestCase { } func test_init_copying_Collection() { - withEvery("c", in: [0, 10, 100]) { c in + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in - let a = RigidArray(copying: (0 ..< c).map { tracker.instance(for: $0) }) - expectEqual(tracker.instances, 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 { + 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) } } @@ -162,7 +97,7 @@ class RigidArrayTests: CollectionTestCase { } func test_init_copying_Container() { - withEvery("c", in: [0, 10, 100]) { c in + withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withEvery("spanCounts", in: [ [1], [3, 5, 7], @@ -170,14 +105,15 @@ class RigidArrayTests: CollectionTestCase { ] as [[Int]]) { spanCounts in withLifetimeTracking { tracker in let additions = StaccatoContainer( - contents: RigidArray(copying: (0 ..< c).map { tracker.instance(for: $0) }), + contents: RigidArray( + copying: (0 ..< layout.count).map { tracker.instance(for: $0) }), spanCounts: spanCounts) - let array = RigidArray(copying: additions) - expectEqual(tracker.instances, c) - expectEqual(array.capacity, c) - expectEqual(array.count, c) - for i in 0 ..< c { + 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) } } @@ -268,7 +204,6 @@ class RigidArrayTests: CollectionTestCase { } } - func test_index_properties() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in let a = RigidArray(layout: layout, using: { $0 }) @@ -366,7 +301,7 @@ class RigidArrayTests: CollectionTestCase { } } - func test_setCapacity() { + func test_reallocate() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withEvery( "newCapacity", @@ -374,11 +309,14 @@ class RigidArrayTests: CollectionTestCase { ) { newCapacity in withLifetimeTracking { tracker in var a = tracker.rigidArray(layout: layout) - a.setCapacity(newCapacity) + 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 }) + expectContainerContents( + a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) } } } @@ -389,16 +327,20 @@ class RigidArrayTests: CollectionTestCase { withEvery( "newCapacity", in: [ - 0, layout.count - 1, layout.count, layout.count + 1, layout.capacity, layout.capacity + 1 + 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 }) + expectContainerContents( + a, equivalentTo: 0 ..< layout.count, by: { $0.payload == $1 }) } } } @@ -454,7 +396,8 @@ class RigidArrayTests: CollectionTestCase { withLifetimeTracking { tracker in var a = tracker.rigidArray(layout: layout) withEvery("i", in: 0 ..< layout.count) { i in - a.removeLast() + let old = a.removeLast() + expectEqual(old.payload, layout.count - 1 - i) expectEqual(a.count, layout.count - 1 - i) expectEqual(a.capacity, layout.capacity) } @@ -474,7 +417,8 @@ class RigidArrayTests: CollectionTestCase { expectEqual(tracker.instances, layout.count) a.removeLast(k) expectEqual(tracker.instances, layout.count - k) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) } } } @@ -488,7 +432,8 @@ class RigidArrayTests: CollectionTestCase { expected.remove(at: i) var a = tracker.rigidArray(layout: layout) - a.remove(at: i) + let old = a.remove(at: i) + expectEqual(old.payload, i) expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) } } @@ -518,7 +463,8 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) a.removeAll(where: { $0.payload.isMultiple(of: 2) }) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) } } } @@ -533,7 +479,8 @@ class RigidArrayTests: CollectionTestCase { let item = a.popLast() expectEquivalent(item, expectedItem, by: { $0?.payload == $1 }) - expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectContainerContents( + a, equivalentTo: expected, by: { $0.payload == $1 }) } } } @@ -553,16 +500,18 @@ class RigidArrayTests: CollectionTestCase { } } - func test_append_contentsOf() { + func test_append_copying_MinimalSequence() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in - withLifetimeTracking { tracker in - var a = tracker.rigidArray(layout: layout) - a.append(contentsOf: MinimalSequence( - elements: (layout.count ..< layout.capacity).map { tracker.instance(for: $0) }, - underestimatedCount: .half, - isContiguous: false)) - expectTrue(a.isFull) - expectEqual(tracker.instances, layout.capacity) + 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) + } } } } @@ -621,20 +570,25 @@ class RigidArrayTests: CollectionTestCase { } } - func test_insert_contentsOf() { + func test_insert_copying_Collection() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withEvery("i", in: 0 ... layout.count) { i in - withLifetimeTracking { tracker in - let addition = (layout.count ..< layout.capacity) + 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) + var expected = Array(0 ..< layout.count) + expected.insert(contentsOf: addition, at: i) - var a = tracker.rigidArray(layout: layout) - a.insert(contentsOf: addition.map { tracker.instance(for: $0) }, 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) + expectContainerContents(a, equivalentTo: expected, by: { $0.payload == $1 }) + expectEqual(tracker.instances, layout.capacity) + } } } } @@ -691,24 +645,27 @@ class RigidArrayTests: CollectionTestCase { func test_replaceSubrange_Collection() { 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) + 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) - var a = tracker.rigidArray(layout: layout) - let trackedAddition = addition.map { tracker.instance(for: $0) } - a.replaceSubrange(range, with: trackedAddition) + 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) + 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 diff --git a/Tests/FutureTests/ContiguousStorageTests.swift b/Tests/FutureTests/ContiguousStorageTests.swift index a4cbdce0..1862794f 100644 --- a/Tests/FutureTests/ContiguousStorageTests.swift +++ b/Tests/FutureTests/ContiguousStorageTests.swift @@ -1,3 +1,14 @@ +//===----------------------------------------------------------------------===// +// +// 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 import Future diff --git a/Tests/FutureTests/DynamicArrayTests.swift b/Tests/FutureTests/DynamicArrayTests.swift deleted file mode 100644 index e066a592..00000000 --- a/Tests/FutureTests/DynamicArrayTests.swift +++ /dev/null @@ -1,212 +0,0 @@ -import XCTest -import _CollectionsTestSupport -import Future -import Synchronization - -class DynamicArrayTests: CollectionTestCase { - func test_validate_Container() { - let c = 100 - - withLifetimeTracking { tracker in - let expected = (0 ..< c).map { tracker.instance(for: $0) } - let items = DynamicArray(count: c, initializedWith: { expected[$0] }) - 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: 42)) - expectFalse(array.isEmpty) - expectEqual(array.count, 1) - expectEqual(array[0].payload, 42) - expectEqual(tracker.instances, 1) - - array.append(tracker.structInstance(for: 23)) - expectFalse(array.isEmpty) - expectEqual(array.count, 2) - expectEqual(array[0].payload, 42) - expectEqual(array[1].payload, 23) - expectEqual(tracker.instances, 2) - - let old = array.remove(at: 0) - expectEqual(old.payload, 42) - expectFalse(array.isEmpty) - expectEqual(array.count, 1) - expectEqual(array[0].payload, 23) - expectEqual(tracker.instances, 2) - _ = consume old - expectEqual(tracker.instances, 1) - - let old2 = array.remove(at: 0) - expectEqual(old2.payload, 23) - expectEqual(array.count, 0) - expectTrue(array.isEmpty) - expectEqual(tracker.instances, 1) - _ = consume old2 - expectEqual(tracker.instances, 0) - } - } - - func test_read_access() { - withLifetimeTracking { tracker in - typealias Value = LifetimeTrackedStruct - - let c = 100 - let array = DynamicArray(count: c) { tracker.structInstance(for: $0) } - - for i in 0 ..< c { - expectEqual(array.borrowElement(at: i)[].payload, i) - expectEqual(array[i].payload, i) - } - } - } - - func test_update_access() { - withLifetimeTracking { tracker in - typealias Value = LifetimeTrackedStruct - - let c = 100 - var array = DynamicArray(count: c) { tracker.structInstance(for: $0) } - - for i in 0 ..< c { - // FIXME: 'exclusive' or something instead of mutating subscript - var me = array.mutateElement(at: i) - me[].payload += 100 - array[i].payload += 100 - } - - for i in 0 ..< c { - expectEqual(array[i].payload, 200 + i) - } - - expectEqual(tracker.instances, c) - _ = consume array - expectEqual(tracker.instances, 0) - } - } - - func test_append() { - withLifetimeTracking { tracker in - typealias Value = LifetimeTrackedStruct - - var array = DynamicArray() - let c = 100 - for i in 0 ..< c { - array.append(tracker.structInstance(for: 100 + i)) - } - expectEqual(tracker.instances, c) - expectEqual(array.count, c) - - for i in 0 ..< c { - expectEqual(array.borrowElement(at: i)[].payload, 100 + i) - expectEqual(array[i].payload, 100 + i) - } - - _ = consume array - expectEqual(tracker.instances, 0) - } - } - - func test_insert() { - withLifetimeTracking { tracker in - typealias Value = LifetimeTrackedStruct - - var array = DynamicArray() - let c = 100 - for i in 0 ..< c { - array.insert(tracker.structInstance(for: 100 + i), at: 0) - } - expectEqual(tracker.instances, c) - expectEqual(array.count, c) - - for i in 0 ..< c { - expectEqual(array.borrowElement(at: i)[].payload, c + 99 - i) - expectEqual(array[i].payload, c + 99 - i) - } - - _ = consume array - expectEqual(tracker.instances, 0) - } - } - - func test_remove() { - withLifetimeTracking { tracker in - typealias Value = LifetimeTrackedStruct - - let c = 100 - var array = DynamicArray(count: c) { tracker.structInstance(for: 100 + $0) } - expectEqual(tracker.instances, c) - expectEqual(array.count, c) - - for i in 0 ..< c { - array.remove(at: 0) - expectEqual(array.count, c - 1 - i) - expectEqual(tracker.instances, c - 1 - i) - } - - expectTrue(array.isEmpty) - expectEqual(tracker.instances, 0) - } - } - - @available(SwiftCompatibilitySpan 5.0, *) - func test_iterate_full() { - withLifetimeTracking { tracker in - typealias Value = LifetimeTrackedStruct - - let c = 100 - let array = DynamicArray(count: c) { tracker.structInstance(for: 100 + $0) } - - var index = 0 - do { - let span = array.nextSpan(after: &index) - expectEqual(span.count, c) - for i in 0 ..< span.count { - expectEqual(span[i].payload, 100 + i) - } - } - do { - let span2 = array.nextSpan(after: &index) - expectEqual(span2.count, 0) - } - } - } - - @available(SwiftCompatibilitySpan 5.0, *) - func test_iterate_stepped() { - withLifetimeTracking { tracker in - typealias Value = LifetimeTrackedStruct - - let c = 100 - let array = DynamicArray(count: c) { tracker.structInstance(for: $0) } - - withEvery("stride", in: 1 ... c) { stride in - var index = 0 - var i = 0 - while true { - expectEqual(index, i) - let span = array.nextSpan(after: &index, maximumCount: stride) - expectEqual(index, i + span.count) - if span.isEmpty { break } - expectEqual(span.count, i + stride <= c ? stride : c % stride) - for j in 0 ..< span.count { - expectEqual(span[j].payload, i) - i += 1 - } - } - expectEqual(i, c) - expectEqual(array.nextSpan(after: &index, maximumCount: Int.max).count, 0) - expectEqual(index, i) - } - } - } -} diff --git a/Tests/FutureTests/RepeatingContainerTests.swift b/Tests/FutureTests/RepeatingContainerTests.swift index 4e0ec00d..da7eb606 100644 --- a/Tests/FutureTests/RepeatingContainerTests.swift +++ b/Tests/FutureTests/RepeatingContainerTests.swift @@ -1,9 +1,13 @@ +//===----------------------------------------------------------------------===// // -// RepeatingContainerTests.swift -// swift-collections +// This source file is part of the Swift Collections open source project // -// Created by Karoy Lorentey on 2025-04-21. +// 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 import _CollectionsTestSupport diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift index 02b3dbba..688a4479 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalBidirectionalCollection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// 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 @@ -29,9 +29,14 @@ public struct MinimalBidirectionalCollection { public init( _ elements: S, context: TestContext = TestContext.current, + isContiguous: Bool = false, underestimatedCount: UnderestimatedCountBehavior = .value(0) ) where S.Element == Element { - self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount) + self._core = _MinimalCollectionCore( + context: context, + elements: elements, + isContiguous: isContiguous, + underestimatedCount: underestimatedCount) } var _context: TestContext { @@ -51,6 +56,13 @@ extension MinimalBidirectionalCollection: Sequence { timesUnderestimatedCountCalled.increment() return _core.underestimatedCount } + + public func withContiguousStorageIfAvailable( + _ body: (UnsafeBufferPointer) throws -> R + ) rethrows -> R? { + guard _core.isContiguous else { return nil } + return unsafe try _core.elements.withUnsafeBufferPointer(body) + } } extension MinimalBidirectionalCollection: BidirectionalCollection { diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift index 50d0d986..009cbc3c 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalCollection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// 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 @@ -28,9 +28,14 @@ public struct MinimalCollection { public init( _ elements: S, context: TestContext = TestContext.current, + isContiguous: Bool = false, underestimatedCount: UnderestimatedCountBehavior = .value(0) ) where S.Element == Element { - self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount) + self._core = _MinimalCollectionCore( + context: context, + elements: elements, + isContiguous: isContiguous, + underestimatedCount: underestimatedCount) } var _context: TestContext { @@ -50,6 +55,13 @@ extension MinimalCollection: Sequence { timesUnderestimatedCountCalled.increment() return _core.underestimatedCount } + + public func withContiguousStorageIfAvailable( + _ body: (UnsafeBufferPointer) throws -> R + ) rethrows -> R? { + guard _core.isContiguous else { return nil } + return unsafe try _core.elements.withUnsafeBufferPointer(body) + } } extension MinimalCollection: Collection { diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift index 24998e2b..2b8d8c02 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRandomAccessCollection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// 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 @@ -30,9 +30,14 @@ public struct MinimalMutableRandomAccessCollection { public init( _ elements: S, context: TestContext = TestContext.current, + isContiguous: Bool = false, underestimatedCount: UnderestimatedCountBehavior = .value(0) ) where S.Element == Element { - self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount) + self._core = _MinimalCollectionCore( + context: context, + elements: elements, + isContiguous: isContiguous, + underestimatedCount: underestimatedCount) } var _context: TestContext { @@ -52,6 +57,13 @@ extension MinimalMutableRandomAccessCollection: Sequence { timesUnderestimatedCountCalled.increment() return _core.underestimatedCount } + + public func withContiguousStorageIfAvailable( + _ body: (UnsafeBufferPointer) throws -> R + ) rethrows -> R? { + guard _core.isContiguous else { return nil } + return unsafe try _core.elements.withUnsafeBufferPointer(body) + } } extension MinimalMutableRandomAccessCollection: RandomAccessCollection { diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift index b3eedec2..31e7809d 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalMutableRangeReplaceableRandomAccessCollection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// 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 @@ -30,9 +30,14 @@ public struct MinimalMutableRangeReplaceableRandomAccessCollection { public init( _ elements: S, context: TestContext = TestContext.current, + isContiguous: Bool = false, underestimatedCount: UnderestimatedCountBehavior = .value(0) ) where S.Element == Element { - self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount) + self._core = _MinimalCollectionCore( + context: context, + elements: elements, + isContiguous: isContiguous, + underestimatedCount: underestimatedCount) } var _context: TestContext { @@ -52,6 +57,13 @@ extension MinimalMutableRangeReplaceableRandomAccessCollection: Sequence { timesUnderestimatedCountCalled.increment() return _core.underestimatedCount } + + public func withContiguousStorageIfAvailable( + _ body: (UnsafeBufferPointer) throws -> R + ) rethrows -> R? { + guard _core.isContiguous else { return nil } + return unsafe try _core.elements.withUnsafeBufferPointer(body) + } } extension MinimalMutableRangeReplaceableRandomAccessCollection: RandomAccessCollection { diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift index bf666b8f..d0405a68 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalRandomAccessCollection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// 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 @@ -26,9 +26,14 @@ public struct MinimalRandomAccessCollection { public init( _ elements: S, context: TestContext = TestContext.current, + isContiguous: Bool = false, underestimatedCount: UnderestimatedCountBehavior = .value(0) ) where S.Element == Element { - self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount) + self._core = _MinimalCollectionCore( + context: context, + elements: elements, + isContiguous: isContiguous, + underestimatedCount: underestimatedCount) } var _context: TestContext { @@ -48,6 +53,13 @@ extension MinimalRandomAccessCollection: Sequence { timesUnderestimatedCountCalled.increment() return _core.underestimatedCount } + + public func withContiguousStorageIfAvailable( + _ body: (UnsafeBufferPointer) throws -> R + ) rethrows -> R? { + guard _core.isContiguous else { return nil } + return unsafe try _core.elements.withUnsafeBufferPointer(body) + } } extension MinimalRandomAccessCollection: RandomAccessCollection { diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift index 4a119be3..262d56c2 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalRangeReplaceableRandomAccessCollection.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// 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 @@ -30,9 +30,14 @@ public struct MinimalRangeReplaceableRandomAccessCollection { public init( _ elements: S, context: TestContext = TestContext.current, + isContiguous: Bool = false, underestimatedCount: UnderestimatedCountBehavior = .value(0) ) where S.Element == Element { - self._core = _MinimalCollectionCore(context: context, elements: elements, underestimatedCount: underestimatedCount) + self._core = _MinimalCollectionCore( + context: context, + elements: elements, + isContiguous: isContiguous, + underestimatedCount: underestimatedCount) } var _context: TestContext { @@ -52,6 +57,13 @@ extension MinimalRangeReplaceableRandomAccessCollection: Sequence { timesUnderestimatedCountCalled.increment() return _core.underestimatedCount } + + public func withContiguousStorageIfAvailable( + _ body: (UnsafeBufferPointer) throws -> R + ) rethrows -> R? { + guard _core.isContiguous else { return nil } + return unsafe try _core.elements.withUnsafeBufferPointer(body) + } } extension MinimalRangeReplaceableRandomAccessCollection: RandomAccessCollection { diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift index 66f6924b..c3b9e10e 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/MinimalSequence.swift @@ -44,17 +44,17 @@ public enum UnderestimatedCountBehavior { /// narrow way possible. /// /// This sequence is consumed when its iterator is advanced. -public struct MinimalSequence: Sequence, CustomDebugStringConvertible { +public struct MinimalSequence: Sequence, CustomDebugStringConvertible { public let timesMakeIteratorCalled = ResettableValue(0) - internal let _sharedState: _MinimalIteratorSharedState + internal let _sharedState: _MinimalIteratorSharedState internal let _isContiguous: Bool public init( elements: S, underestimatedCount: UnderestimatedCountBehavior = .value(0), isContiguous: Bool = false - ) where S.Element == T { + ) where S.Element == Element { let data = Array(elements) self._sharedState = _MinimalIteratorSharedState(data) self._isContiguous = isContiguous @@ -73,7 +73,7 @@ public struct MinimalSequence: Sequence, CustomDebugStringConvertible { } } - public func makeIterator() -> MinimalIterator { + public func makeIterator() -> MinimalIterator { timesMakeIteratorCalled.value += 1 return MinimalIterator(_sharedState) } @@ -87,10 +87,10 @@ public struct MinimalSequence: Sequence, CustomDebugStringConvertible { } public func withContiguousStorageIfAvailable( - _ body: (UnsafeBufferPointer) throws -> R + _ body: (UnsafeBufferPointer) throws -> R ) rethrows -> R? { guard _isContiguous else { return nil } - return try _sharedState.data[_sharedState.i...] + return unsafe try _sharedState.data[_sharedState.i...] .withContiguousStorageIfAvailable(body) } } diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift b/Tests/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift index 6e6d8666..4d348ac7 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/_MinimalCollectionCore.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift.org open source project // -// Copyright (c) 2014 - 2024 Apple Inc. and the Swift project authors +// 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 @@ -13,23 +13,31 @@ struct _MinimalCollectionCore { var state: _CollectionState var elements: [Element] + let isContiguous: Bool var underestimatedCount: Int public init( context: TestContext, elements: S, + isContiguous: Bool, underestimatedCount: UnderestimatedCountBehavior? = nil ) where S.Element == Element { - self.init(context: context, elements: Array(elements), underestimatedCount: underestimatedCount) + self.init( + context: context, + elements: Array(elements), + isContiguous: isContiguous, + underestimatedCount: underestimatedCount) } public init( context: TestContext, elements: [Element], + isContiguous: Bool, underestimatedCount: UnderestimatedCountBehavior? = nil ) { self.state = _CollectionState(context: context, parent: nil, count: elements.count) self.elements = elements + self.isContiguous = isContiguous self.underestimatedCount = underestimatedCount?.value(forCount: elements.count) ?? elements.count }