From 174efda735d691aa6e591b8c4c06020149a8aeb2 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 26 Sep 2025 17:18:50 -0700 Subject: [PATCH] RigidArray/UniqueArray: Final API cleanup pass - Set availability to match Span availability - Split implementation into multiple source files - Add OutputSpan-based primitives that can be the bases of all append/insertion/replaceSubrange variants - Add the ability to consume a subrange of items using an InputSpan - Add bulk copying operations generic over the new Container protocol --- Sources/BasicContainers/CMakeLists.txt | 14 +- .../BasicContainers/RigidArray+Append.swift | 312 ++++++ .../RigidArray+Experimental.swift | 378 +------ .../RigidArray+Initializers.swift | 108 ++ .../RigidArray+Insertions.swift | 415 ++++++++ .../BasicContainers/RigidArray+Removals.swift | 187 ++++ .../RigidArray+Replacements.swift | 464 +++++++++ Sources/BasicContainers/RigidArray.swift | 970 +----------------- .../BasicContainers/UniqueArray+Append.swift | 265 +++++ .../UniqueArray+Experimental.swift | 279 +---- .../UniqueArray+Initializers.swift | 91 ++ .../UniqueArray+Insertions.swift | 339 ++++++ .../UniqueArray+Removals.swift | 149 +++ .../UniqueArray+Replacements.swift | 399 +++++++ Sources/BasicContainers/UniqueArray.swift | 840 +-------------- ...nsafeMutableBufferPointer+Extras.swift.gyb | 41 +- .../UnsafeMutableBufferPointer+Extras.swift | 82 +- .../RigidArrayTests.swift | 14 +- .../UniqueArrayTests.swift | 12 +- 19 files changed, 2869 insertions(+), 2490 deletions(-) create mode 100644 Sources/BasicContainers/RigidArray+Append.swift create mode 100644 Sources/BasicContainers/RigidArray+Initializers.swift create mode 100644 Sources/BasicContainers/RigidArray+Insertions.swift create mode 100644 Sources/BasicContainers/RigidArray+Removals.swift create mode 100644 Sources/BasicContainers/RigidArray+Replacements.swift create mode 100644 Sources/BasicContainers/UniqueArray+Append.swift create mode 100644 Sources/BasicContainers/UniqueArray+Initializers.swift create mode 100644 Sources/BasicContainers/UniqueArray+Insertions.swift create mode 100644 Sources/BasicContainers/UniqueArray+Removals.swift create mode 100644 Sources/BasicContainers/UniqueArray+Replacements.swift diff --git a/Sources/BasicContainers/CMakeLists.txt b/Sources/BasicContainers/CMakeLists.txt index d37397ef..94586ef4 100644 --- a/Sources/BasicContainers/CMakeLists.txt +++ b/Sources/BasicContainers/CMakeLists.txt @@ -23,8 +23,18 @@ else() endif() target_sources(${module_name} PRIVATE - "UniqueArray.swift" - "UniqueArray+Experimental.swift" "RigidArray.swift" + "RigidArray+Append.swift" "RigidArray+Experimental.swift" + "RigidArray+Initializers.swift" + "RigidArray+Insertions.swift" + "RigidArray+Removals.swift" + "RigidArray+Replacements.swift" + "UniqueArray.swift" + "UniqueArray+Append.swift" + "UniqueArray+Experimental.swift" + "UniqueArray+Initializers.swift" + "UniqueArray+Insertions.swift" + "UniqueArray+Removals.swift" + "UniqueArray+Replacements.swift" ) diff --git a/Sources/BasicContainers/RigidArray+Append.swift b/Sources/BasicContainers/RigidArray+Append.swift new file mode 100644 index 00000000..ded035f4 --- /dev/null +++ b/Sources/BasicContainers/RigidArray+Append.swift @@ -0,0 +1,312 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Adds an element to the end of the array. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this triggers a runtime error. + /// + /// - Parameter item: The element to append to the collection. + /// + /// - Complexity: O(1) + @inlinable + public mutating func append(_ item: consuming Element) { + precondition(!isFull, "RigidArray capacity overflow") + unsafe _storage.initializeElement(at: _count, to: item) + _count &+= 1 + } + + /// Adds an element to the end of the array, if possible. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this returns the given item without appending it; otherwise it + /// returns nil. + /// + /// - Parameter item: The element to append to the collection. + /// - Returns: `item` if the array is full; otherwise nil. + /// + /// - Complexity: O(1) + @inlinable + public mutating func pushLast(_ item: consuming Element) -> Element? { + // FIXME: Remove this in favor of a standard algorithm. + if isFull { return item } + append(item) + return nil + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + @_alwaysEmitIntoClient + public mutating func append( + count: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Result + ) throws(E) -> Result { + // FIXME: This is extremely similar to `edit()`, except it provides a narrower span. + precondition(freeCapacity >= count, "RigidArray capacity overflow") + let buffer = _freeSpace._extracting(first: count) + var span = OutputSpan(buffer: buffer, initializedCount: 0) + defer { + _count &+= span.finalize(for: buffer) + span = OutputSpan() + } + return try body(&span) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Moves the elements of a buffer to the end of this array, leaving the + /// buffer uninitialized. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + moving items: UnsafeMutableBufferPointer + ) { + precondition(items.count <= freeCapacity, "RigidArray capacity overflow") + guard items.count > 0 else { return } + let c = unsafe _freeSpace._moveInitializePrefix(from: items) + assert(c == items.count) + _count &+= items.count + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout InputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.append(moving: source) + count = 0 + } + } +#endif + + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout OutputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.append(moving: source) + count = 0 + } + } + + /// Appends the elements of a given array to the end of this array by moving + /// them between the containers. On return, the input array becomes empty, but + /// it is not destroyed, and it preserves its original storage capacity. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this triggers a runtime error. + /// + /// - Parameters + /// - items: An array whose items to move to the end of this array. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout RigidArray + ) { + // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers + unsafe items._unsafeEdit { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.append(moving: source) + count = 0 + } + } +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Appends the elements of a given container to the end of this array by + /// consuming the source container. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this triggers a runtime error. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + consuming items: consuming RigidArray + ) { + // FIXME: Remove this in favor of a generic algorithm over consumable containers + var items = items + self.append(moving: &items) + } +} +#endif + +@available(SwiftStdlib 5.0, *) +extension RigidArray { + /// Copies the elements of a buffer to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A fully initialized buffer whose contents to copy into + /// the array. + /// + /// - Complexity: O(`newElements.count`) + @_alwaysEmitIntoClient + public mutating func append( + copying newElements: UnsafeBufferPointer + ) { + precondition( + newElements.count <= freeCapacity, + "RigidArray capacity overflow") + guard newElements.count > 0 else { return } + unsafe _freeSpace.baseAddress.unsafelyUnwrapped.initialize( + from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count) + _count &+= newElements.count + } + + /// Copies the elements of a buffer to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A fully initialized buffer whose contents to copy into + /// the array. + /// + /// - Complexity: O(`newElements.count`) + @_alwaysEmitIntoClient + public mutating func append( + copying items: UnsafeMutableBufferPointer + ) { + unsafe self.append(copying: UnsafeBufferPointer(items)) + } + + /// Copies the elements of a span to the end of this array. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// span, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A span whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`) + @_alwaysEmitIntoClient + public mutating func append(copying items: Span) { + unsafe items.withUnsafeBufferPointer { source in + unsafe self.append(copying: source) + } + } + + @_alwaysEmitIntoClient + @inline(__always) + internal mutating func _append>( + prefixOf items: S + ) -> S.Iterator { + let (it, c) = unsafe items._copyContents(initializing: _freeSpace) + _count += c + return it + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _append< + Source: Container & ~Copyable & ~Escapable + >( + copyingContainer newElements: borrowing Source + ) { + let target = _freeSpace + _count += newElements._copyContents(intoPrefixOf: target) + } +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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 + /// source iterable, then this triggers a runtime error. + /// + /// - Parameters + /// - newElements: A container whose contents to copy into the array. + /// + /// - Complexity: O(`newElements.count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append< + Source: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing Source + ) { + _append(copyingContainer: newElements) + } +#endif + + /// 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") + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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 + /// source iterable, 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 + @inline(__always) + public mutating func append< + Source: Container & Sequence + >(copying newElements: Source) { + _append(copyingContainer: newElements) + } +#endif +} +#endif diff --git a/Sources/BasicContainers/RigidArray+Experimental.swift b/Sources/BasicContainers/RigidArray+Experimental.swift index 8bcf6482..214e0b44 100644 --- a/Sources/BasicContainers/RigidArray+Experimental.swift +++ b/Sources/BasicContainers/RigidArray+Experimental.swift @@ -14,48 +14,10 @@ import InternalCollectionsUtilities import ContainersPreview #endif -#if compiler(>=6.2) -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -extension RigidArray /*where Element: Copyable*/ { -#if FIXME - @_alwaysEmitIntoClient - @inline(__always) - public init & Sequence>( - capacity: Int, - copying contents: C - ) { - self.init(capacity: capacity) - self.append(copying: contents) - } -#endif - -#if FIXME - @_alwaysEmitIntoClient - @inline(__always) - public init & ~Copyable & ~Escapable>( - capacity: Int? = nil, - copying contents: borrowing C - ) { - self.init(capacity: capacity ?? contents.count) - self.append(copying: contents) - } -#endif - -#if FIXME - @_alwaysEmitIntoClient - @inline(__always) - public init & Collection>( - capacity: Int? = nil, - copying contents: C - ) { - self.init(capacity: capacity ?? contents.count) - self.append(copying: contents) - } -#endif -} - -#if FIXME +#if false // FIXME +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(borrow self) @@ -69,18 +31,14 @@ extension RigidArray where Element: ~Copyable { } #endif -#if FIXME -extension RigidArray: RandomAccessContainer where Element: ~Copyable { -} -#endif - -#if FIXME +#if false // FIXME +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable @_lifetime(&self) - public mutating func mutateElement(at index: Int) -> Inout { + public mutating func mutateElement(at index: Int) -> Mut { precondition(index >= 0 && index < _count) - return unsafe Inout( + return unsafe Mut( unsafeAddress: _storage.baseAddress.unsafelyUnwrapped.advanced(by: index), mutating: &self ) @@ -88,13 +46,9 @@ extension RigidArray where Element: ~Copyable { } #endif -#if FIXME -extension RigidArray: MutableContainer where Element: ~Copyable { -} -#endif - +#if false // FIXME +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @inlinable public mutating func reallocate( capacity: Int, @@ -118,8 +72,10 @@ extension RigidArray where Element: ~Copyable { return try body(&source, &target) } } +#endif -#if FIXME +#if false // FIXME +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { /// Removes all the elements that satisfy the given predicate. /// @@ -131,7 +87,6 @@ extension RigidArray where Element: ~Copyable { /// whether the element should be removed from the array. /// /// - Complexity: O(`count`) - @available(SwiftStdlib 6.2, *) @_alwaysEmitIntoClient public mutating func removeAll( where shouldBeRemoved: (borrowing Element) throws(E) -> Bool @@ -143,313 +98,4 @@ extension RigidArray where Element: ~Copyable { } #endif -extension RigidArray where Element: ~Copyable { - @_lifetime(&self) - public mutating func popLast(_ count: Int) -> InputSpan { - let c = Swift.min(count, self.count) - self._count &-= c - let span = InputSpan( - buffer: self._storage._extracting(last: c), - initializedCount: c) - return _overrideLifetime(span, mutating: &self) - } -} - -extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func append( - moving items: inout InputSpan - ) { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) - unsafe self.append(moving: source) - count = 0 - } - } - - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func append( - moving items: inout OutputSpan - ) { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) - unsafe self.append(moving: source) - count = 0 - } - } -} - -extension RigidArray { -#if FIXME - @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 - } -#endif - -#if FIXME - /// 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`) - @_alwaysEmitIntoClient - @inline(__always) - public mutating func append & ~Copyable & ~Escapable>( - copying newElements: borrowing C - ) { - _appendContainer(copying: newElements) - } -#endif - -#if FIXME - /// 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`. - @_alwaysEmitIntoClient - @inline(__always) - public mutating func append< - C: Container & Sequence - >(copying newElements: C) { - _appendContainer(copying: newElements) - } -#endif -} - -extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: inout InputSpan, - at index: Int - ) { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) - unsafe self.append(moving: source) - count = 0 - } - } - - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: inout OutputSpan, - at index: Int - ) { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) - unsafe self.append(moving: source) - count = 0 - } - } -} - -extension RigidArray { -#if FIXME - @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 == newCount && end == items.endIndex, - "Broken Container: count doesn't match contents") - _count += newCount - } -#endif - -#if FIXME - /// 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`. - @_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) - } -#endif - -#if FIXME - /// 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`. - @_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) - } -#endif -} - -extension RigidArray { -#if FIXME - @inlinable - 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") - } -#endif - -#if FIXME - /// 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(`self.count` + `newElements.count`) - @inlinable - @inline(__always) - public mutating func replaceSubrange< - C: Container & ~Copyable & ~Escapable - >( - _ subrange: Range, - copying newElements: borrowing C - ) { - _replaceSubrange( - subrange, copyingContainer: newElements, newCount: newElements.count) - } -#endif - -#if FIXME - /// 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`. - @inlinable - @inline(__always) - public mutating func replaceSubrange< - C: Container & Collection - >( - _ subrange: Range, - copying newElements: C - ) { - _replaceSubrange( - subrange, copyingContainer: newElements, newCount: newElements.count) - } -#endif -} - -#endif #endif diff --git a/Sources/BasicContainers/RigidArray+Initializers.swift b/Sources/BasicContainers/RigidArray+Initializers.swift new file mode 100644 index 00000000..dd395144 --- /dev/null +++ b/Sources/BasicContainers/RigidArray+Initializers.swift @@ -0,0 +1,108 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + @inlinable + public init( + capacity: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + self.init(capacity: capacity) + try edit(body) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray /*where Element: Copyable*/ { + /// Creates a new array containing the specified number of a single, + /// repeated value. + /// + /// - Parameters: + /// - repeatedValue: The element to repeat. + /// - count: The number of times to repeat the value passed in the + /// `repeating` parameter. `count` must be zero or greater. + public init(repeating repeatedValue: Element, count: Int) { + self.init(capacity: count) + unsafe _freeSpace.initialize(repeating: repeatedValue) + _count = count + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray /*where Element: Copyable*/ { + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int, + copying contents: some Sequence + ) { + self.init(capacity: capacity) + self.append(copying: contents) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + @inline(__always) + public init & Sequence>( + capacity: Int, + copying contents: Source + ) { + self.init(capacity: capacity) + self.append(copying: contents) + } +#endif + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + @inline(__always) + public init & ~Copyable & ~Escapable>( + capacity: Int? = nil, + copying contents: borrowing Source + ) { + self.init(capacity: capacity ?? contents.count) + self.append(copying: contents) + } +#endif + + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int? = nil, + copying contents: some Collection + ) { + self.init(capacity: capacity ?? contents.count) + self.append(copying: contents) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + @inline(__always) + public init & Collection>( + capacity: Int? = nil, + copying contents: Source + ) { + self.init(capacity: capacity ?? contents.count) + self.append(copying: contents) + } +#endif +} + +// FIXME: Add init(moving:), init(consuming:) + +#endif diff --git a/Sources/BasicContainers/RigidArray+Insertions.swift b/Sources/BasicContainers/RigidArray+Insertions.swift new file mode 100644 index 00000000..c1f076c4 --- /dev/null +++ b/Sources/BasicContainers/RigidArray+Insertions.swift @@ -0,0 +1,415 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Inserts a new element into the array at the specified position. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this triggers a runtime error. + /// + /// The new element is inserted before the element currently at the specified + /// index. If you pass the array's `endIndex` as the `index` parameter, then + /// the new element is appended to the container. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// - Parameter item: The new element to insert into the array. + /// - Parameter i: The position at which to insert the new element. + /// `index` must be a valid index in the array. + /// + /// - Complexity: O(`count`) + @inlinable + public mutating func insert(_ item: consuming Element, at index: Int) { + precondition(index >= 0 && index <= count, "Index out of bounds") + precondition(!isFull, "RigidArray capacity overflow") + if index < count { + let source = unsafe _storage.extracting(index ..< count) + let target = unsafe _storage.extracting(index + 1 ..< count + 1) + let last = unsafe target.moveInitialize(fromContentsOf: source) + assert(last == target.endIndex) + } + unsafe _storage.initializeElement(at: index, to: item) + _count += 1 + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + @inlinable + public mutating func insert( + count: Int, + at index: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + // FIXME: This does not allow `body` to throw, to prevent having to move the tail twice. Is that okay? + precondition(index >= 0 && index <= self.count, "Index out of bounds") + precondition(count <= freeCapacity, "RigidArray capacity overflow") + let target = unsafe _openGap(at: index, count: count) + var span = OutputSpan(buffer: target, initializedCount: 0) + defer { + let c = span.finalize(for: target) + precondition(c == count, "Inserted fewer items than promised") + _count &+= c + span = OutputSpan() + } + return body(&span) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Moves the elements of a fully initialized buffer into this array, + /// starting at the specified position, and leaving the buffer + /// uninitialized. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this triggers a runtime error. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: UnsafeMutableBufferPointer, + at index: Int + ) { + insert(count: items.count, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.moveInitializeAll(fromContentsOf: items) + count = items.count + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout InputSpan, + at index: Int + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.insert(moving: source, at: index) + count = 0 + } + } +#endif + + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout OutputSpan, + at index: Int + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.insert(moving: source, at: index) + count = 0 + } + } + + /// Inserts the elements of a given array into the given position in this + /// array by moving them between the containers. On return, the input array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this triggers a runtime error. + /// + /// - Parameters + /// - items: An array whose contents to move into `self`. + /// + /// - Complexity: O(`count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout RigidArray, + at index: Int + ) { + insert(count: items.count, at: index) { target in + target.withUnsafeMutableBufferPointer { dst, dstCount in + items.edit { source in + source.withUnsafeMutableBufferPointer { src, srcCount in + dst.moveInitializeAll(fromContentsOf: src) + dstCount = src.count + srcCount = 0 + } + } + } + } + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Inserts the elements of a given array into the given position in this + /// array by consuming the source container. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this triggers a runtime error. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + consuming items: consuming RigidArray, + at index: Int + ) { + var items = items + self.insert(moving: &items, at: index) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray { + /// Copies the elements of a fully initialized buffer pointer into this + /// array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeBufferPointer, at index: Int + ) { + guard newElements.count > 0 else { return } + self.insert(count: newElements.count, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + buffer.initializeAll(fromContentsOf: newElements) + count = newElements.count + } + } + } + + /// Copies the elements of a fully initialized buffer pointer into this + /// array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeMutableBufferPointer, + at index: Int + ) { + unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) + } + + /// Copies the elements of a span into this array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: Span, at index: Int + ) { + unsafe newElements.withUnsafeBufferPointer { + unsafe self.insert(copying: $0, at: index) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _insertContainer< + C: Container & ~Copyable & ~Escapable + >( + at index: Int, + copying items: borrowing C, + newCount: Int + ) { + insert(count: newCount, at: index) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + let copied = items._copyContents(intoPrefixOf: buffer) + precondition( + copied == newCount, + "Broken Container: count doesn't match contents") + count = newCount + } + } + } +#endif + + @inlinable + internal mutating func _insertCollection( + at index: Int, + copying items: some Collection, + newCount: Int + ) { + precondition(index >= 0 && index <= _count, "Index out of bounds") + precondition(newCount <= freeCapacity, "RigidArray capacity overflow") + let gap = unsafe _openGap(at: index, count: newCount) + + let done: Void? = items.withContiguousStorageIfAvailable { buffer in + let i = unsafe gap._initializePrefix(copying: buffer) + precondition( + i == newCount, + "Broken Collection: count doesn't match contents") + _count += newCount + } + if done != nil { return } + + var (it, copied) = unsafe items._copyContents(initializing: gap) + precondition( + it.next() == nil && copied == newCount, + "Broken Collection: count doesn't match contents") + _count += newCount + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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`. + @_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) + } +#endif + + /// Copies the elements of a collection into this array at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved + /// to make room for the new item. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`count` + `newElements.count`) + @inlinable + @inline(__always) + public mutating func insert( + copying newElements: some Collection, at index: Int + ) { + _insertCollection( + at: index, copying: newElements, newCount: newElements.count) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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`. + @_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) + } +#endif +} + +#endif diff --git a/Sources/BasicContainers/RigidArray+Removals.swift b/Sources/BasicContainers/RigidArray+Removals.swift new file mode 100644 index 00000000..888009d0 --- /dev/null +++ b/Sources/BasicContainers/RigidArray+Removals.swift @@ -0,0 +1,187 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Removes all elements from the array, preserving its allocated capacity. + /// + /// - Complexity: O(*n*), where *n* is the original count of the array. + @inlinable + public mutating func removeAll() { + unsafe _items.deinitialize() + _count = 0 + } + + /// Removes and returns the last element of the array. + /// + /// The array must not be empty. + /// + /// - Returns: The last element of the original array. + /// + /// - Complexity: O(1) + @inlinable + @discardableResult + public mutating func removeLast() -> Element { + precondition(!isEmpty, "Cannot remove last element from an empty array") + let old = unsafe _storage.moveElement(from: _count - 1) + _count -= 1 + return old + } + + /// Removes and discards the specified number of elements from the end of the + /// array. + /// + /// Attempting to remove more elements than exist in the array + /// triggers a runtime error. + /// + /// - Parameter k: The number of elements to remove from the array. + /// `k` must be greater than or equal to zero and must not exceed + /// the count of the array. + /// + /// - Complexity: O(`k`) + @inlinable + public mutating func removeLast(_ k: Int) { + if k == 0 { return } + precondition( + k >= 0 && k <= _count, + "Count of elements to remove is out of bounds") + unsafe _storage.extracting( + Range(uncheckedBounds: (_count - k, _count)) + ).deinitialize() + _count &-= k + } + + /// Removes and returns the element at the specified position. + /// + /// All the elements following the specified position are moved to close the + /// gap. + /// + /// - Parameter i: The position of the element to remove. `index` must be + /// a valid index of the array that is not equal to the end index. + /// - Returns: The removed element. + /// + /// - Complexity: O(`count`) + @inlinable + @discardableResult + public mutating func remove(at index: Int) -> Element { + precondition(index >= 0 && index < _count, "Index out of bounds") + let old = unsafe _storage.moveElement(from: index) + _closeGap(at: index, count: 1) + _count -= 1 + return old + } + + /// Removes the specified subrange of elements from the array. + /// + /// All the elements following the specified subrange are moved to close the + /// resulting gap. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds + /// of the range must be valid indices of the array. + /// + /// - Complexity: O(`count`) + @inlinable + public mutating func removeSubrange(_ bounds: Range) { + precondition( + bounds.lowerBound >= 0 && bounds.upperBound <= _count, + "Subrange out of bounds") + guard !bounds.isEmpty else { return } + unsafe _storage.extracting(bounds).deinitialize() + _closeGap(at: bounds.lowerBound, count: bounds.count) + _count -= bounds.count + } + + /// Removes the specified subrange of elements from the array. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds of the + /// range must be valid indices of the array. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + public mutating func removeSubrange(_ bounds: some RangeExpression) { + // FIXME: Remove this in favor of a standard algorithm. + removeSubrange(bounds.relative(to: indices)) + } +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + @_lifetime(&self) + @_alwaysEmitIntoClient + public mutating func consumeAll() -> InputSpan { + let span = InputSpan(buffer: _items, initializedCount: self.count) + self._count = 0 + return _overrideLifetime(span, mutating: &self) + } + + @_lifetime(&self) + @_alwaysEmitIntoClient + public mutating func consumeLast(_ count: Int) -> InputSpan { + precondition(count >= 0, "Cannot consume a negative number of items") + let c = Swift.min(count, self.count) + self._count &-= c + let span = InputSpan( + buffer: self._storage._extracting(first: c), + initializedCount: c) + return _overrideLifetime(span, mutating: &self) + } + + @_alwaysEmitIntoClient + public mutating func consumeSubrange( + _ bounds: Range, + consumingWith body: (inout InputSpan) throws(E) -> Result + ) throws(E) -> Result { + precondition( + bounds.lowerBound >= 0 && bounds.upperBound <= _count, + "Subrange out of bounds") + guard !bounds.isEmpty else { + var span = InputSpan() + return try body(&span) + } + let buffer = unsafe _storage.extracting(bounds) + var span = InputSpan(buffer: buffer, initializedCount: buffer.count) + defer { + let remainder = span.finalize(for: buffer) + buffer._extracting(last: remainder).deinitialize() + _closeGap(at: bounds.lowerBound, count: bounds.count) + _count -= bounds.count + span = InputSpan() + } + return try body(&span) + } +} +#endif + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Removes and returns the last element of the array, if there is one. + /// + /// - Returns: The last element of the array if the array is not empty; + /// otherwise, `nil`. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + public mutating func popLast() -> Element? { + // FIXME: Remove this in favor of a standard algorithm. + if isEmpty { return nil } + return removeLast() + } +} + +#endif diff --git a/Sources/BasicContainers/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray+Replacements.swift new file mode 100644 index 00000000..f1541949 --- /dev/null +++ b/Sources/BasicContainers/RigidArray+Replacements.swift @@ -0,0 +1,464 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + newCount: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + // FIXME: Should we allow throwing (and a partially filled output span)? + // FIXME: Should we have a version of this with two closures, to allow custom-consuming the old items? + // replaceSubrange(5..<10, newCount: 3, consumingWith: {...}, initializingWith: {...}) + let target = _gapForReplacement(of: subrange, withNewCount: newCount) + var span = OutputSpan(buffer: target, initializedCount: 0) + defer { + let c = span.finalize(for: target) + precondition(c == newCount, "Inserted fewer items than promised") + span = OutputSpan() + } + return body(&span) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// fully initialized buffer into their place. On return, the buffer is left + /// in an uninitialized state. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: UnsafeMutableBufferPointer, + ) { + replaceSubrange(subrange, newCount: newElements.count) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + count = unsafe buffer._moveInitializePrefix(from: newElements) + } + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout InputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(last: count) + unsafe self.replaceSubrange(subrange, moving: source) + count = 0 + } + } +#endif + + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout OutputSpan + ) { + items.withUnsafeMutableBufferPointer { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.replaceSubrange(subrange, moving: source) + count = 0 + } + } + + /// Replaces the specified range of elements by moving the elements of a + /// another array into their place. On return, the source array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: inout RigidArray, + ) { + unsafe newElements._unsafeEdit { buffer, count in + let source = buffer._extracting(first: count) + unsafe self.replaceSubrange(subrange, moving: source) + count = 0 + } + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// given array into their place, consuming it in the process. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + consuming newElements: consuming RigidArray, + ) { + replaceSubrange(subrange, moving: &newElements) + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidArray { + /// Replaces the specified subrange of elements by copying the elements of + /// the given buffer pointer, which must be fully initialized. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeBufferPointer + ) { + replaceSubrange(subrange, newCount: newElements.count) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + count = unsafe buffer._initializePrefix(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 the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: UnsafeMutableBufferPointer + ) { + unsafe self.replaceSubrange( + subrange, + copying: UnsafeBufferPointer(newElements)) + } + + /// Replaces the specified subrange of elements by copying the elements of + /// the given span. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length span as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: Span + ) { + unsafe newElements.withUnsafeBufferPointer { buffer in + unsafe self.replaceSubrange(subrange, copying: buffer) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @inlinable + internal mutating func _replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copyingContainer newElements: borrowing C, + newCount: Int + ) { + self.replaceSubrange(subrange, newCount: newCount) { target in + target.withUnsafeMutableBufferPointer { buffer, count in + count = newElements._copyContents(intoPrefixOf: buffer) + precondition( + count == newCount, + "Broken Container: count doesn't match contents") + } + } + } +#endif + + @inlinable + internal mutating func _replaceSubrange( + _ subrange: Range, + copyingCollection newElements: __owned some Collection, + newCount: Int + ) { + self.replaceSubrange(subrange, newCount: newCount) { target in + target.withUnsafeMutableBufferPointer { dst, dstCount in + let done: Void? = newElements.withContiguousStorageIfAvailable { src in + let i = unsafe dst._initializePrefix(copying: src) + precondition( + i == newCount, + "Broken Collection: count doesn't match contents") + dstCount = i + } + if done != nil { return } + + var (it, copied) = unsafe newElements._copyContents(initializing: dst) + dstCount = copied + precondition( + it.next() == nil && copied == newCount, + "Broken Collection: count doesn't match contents") + } + } + + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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(`self.count` + `newElements.count`) + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copying newElements: borrowing C + ) { + _replaceSubrange( + subrange, copyingContainer: newElements, newCount: newElements.count) + } +#endif + + /// Replaces the specified subrange of elements by copying the elements of + /// the given collection. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the capacity of the array isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length collection as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + @inline(__always) + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: __owned some Collection + ) { + _replaceSubrange( + subrange, copyingCollection: newElements, newCount: newElements.count) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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`. + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & Collection + >( + _ subrange: Range, + copying newElements: C + ) { + _replaceSubrange( + subrange, copyingContainer: newElements, newCount: newElements.count) + } +#endif +} + +#endif diff --git a/Sources/BasicContainers/RigidArray.swift b/Sources/BasicContainers/RigidArray.swift index b084474a..c3c1b749 100644 --- a/Sources/BasicContainers/RigidArray.swift +++ b/Sources/BasicContainers/RigidArray.swift @@ -11,6 +11,7 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities +import ContainersPreview #endif #if compiler(<6.2) @@ -41,7 +42,7 @@ public struct RigidArray: ~Copyable { /// A fixed capacity, heap allocated, noncopyable array of potentially /// noncopyable elements. /// -/// `RigidArray` instances are created with a certain maximum capacity. Elements +/// `RigidArray` instances are created with a specific maximum capacity. Elements /// can be added to the array up to that capacity, but no more: trying to add an /// item to a full array results in a runtime trap. /// @@ -73,7 +74,9 @@ public struct RigidArray: ~Copyable { /// spikes due to a reallocation getting triggered at an inopportune moment. /// /// For use cases outside of these narrow domains, we generally recommmend -/// the use of ``UniqueArray`` rather than `RigidArray`. +/// the use of ``UniqueArray`` rather than `RigidArray`. (For copyable elements, +/// the standard `Array` is an even more convenient choice.) +@available(SwiftStdlib 5.0, *) @safe @frozen public struct RigidArray: ~Copyable { @@ -107,63 +110,14 @@ public struct RigidArray: ~Copyable { _count = 0 } } + +@available(SwiftStdlib 5.0, *) extension RigidArray: @unchecked Sendable where Element: Sendable & ~Copyable {} -//MARK: - Initializers - -extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) - @inlinable - public init( - capacity: Int, - initializedWith body: (inout OutputSpan) throws(E) -> Void - ) throws(E) { - self.init(capacity: capacity) - try edit(body) - } -} - -extension RigidArray /*where Element: Copyable*/ { - /// Creates a new array containing the specified number of a single, - /// repeated value. - /// - /// - Parameters: - /// - repeatedValue: The element to repeat. - /// - count: The number of times to repeat the value passed in the - /// `repeating` parameter. `count` must be zero or greater. - public init(repeating repeatedValue: Element, count: Int) { - self.init(capacity: count) - unsafe _freeSpace.initialize(repeating: repeatedValue) - _count = count - } -} - -extension RigidArray /*where Element: Copyable*/ { - @_alwaysEmitIntoClient - @inline(__always) - public init( - capacity: Int, - copying contents: some Sequence - ) { - self.init(capacity: capacity) - self.append(copying: contents) - } - - @_alwaysEmitIntoClient - @inline(__always) - public init( - capacity: Int? = nil, - copying contents: some Collection - ) { - self.init(capacity: capacity ?? contents.count) - self.append(copying: contents) - } -} - -// FIXME: init(moving:), init(consuming:) //MARK: - Basics +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable @_transparent @@ -180,6 +134,7 @@ extension RigidArray where Element: ~Copyable { public var isFull: Bool { freeCapacity == 0 } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable internal var _items: UnsafeMutableBufferPointer { @@ -194,8 +149,8 @@ extension RigidArray where Element: ~Copyable { //MARK: - Span creation +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) public var span: Span { @_lifetime(borrow self) @inlinable @@ -205,7 +160,6 @@ extension RigidArray where Element: ~Copyable { } } - @available(SwiftStdlib 5.0, *) public var mutableSpan: MutableSpan { @_lifetime(&self) @inlinable @@ -215,14 +169,12 @@ extension RigidArray where Element: ~Copyable { } } - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(borrow self) internal func _span(in range: Range) -> Span { span.extracting(range) } - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(&self) internal mutating func _mutableSpan( @@ -233,6 +185,7 @@ extension RigidArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { /// Arbitrarily edit the storage underlying this array by invoking a /// user-supplied closure with a mutable `OutputSpan` view over it. @@ -251,7 +204,6 @@ extension RigidArray where Element: ~Copyable { /// - Returns: This method returns the result of its function argument. /// - Complexity: Adds O(1) overhead to the complexity of the function /// argument. - @available(SwiftStdlib 5.0, *) @inlinable public mutating func edit( _ body: (inout OutputSpan) throws(E) -> R @@ -275,6 +227,7 @@ extension RigidArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable internal func _contiguousSubrange(following index: inout Int) -> Range { @@ -291,11 +244,10 @@ extension RigidArray where Element: ~Copyable { } } -//MARK: - Random-access & mutable container primitives +//MARK: - Container primitives +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { - public typealias Index = Int - @inlinable @inline(__always) public var isEmpty: Bool { count == 0 } @@ -303,6 +255,24 @@ extension RigidArray where Element: ~Copyable { @inlinable @inline(__always) public var count: Int { _count } +} + +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension RigidArray: Container where Element: ~Copyable { + public typealias BorrowIterator = Span + + @_alwaysEmitIntoClient + @inline(__always) + public func startBorrowIteration() -> Span { + self.span + } +} +#endif + +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { + public typealias Index = Int @inlinable @inline(__always) @@ -317,6 +287,7 @@ extension RigidArray where Element: ~Copyable { public var indices: Range { unsafe Range(uncheckedBounds: (0, count)) } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable @inline(__always) internal func _ptr(to index: Int) -> UnsafePointer { @@ -344,6 +315,7 @@ extension RigidArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable public mutating func swapAt(_ i: Int, _ j: Int) { @@ -354,15 +326,14 @@ extension RigidArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(borrow self) public func span(after index: inout Int) -> Span { _span(in: _contiguousSubrange(following: &index)) } - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(borrow self) public func span(before index: inout Int) -> Span { @@ -370,8 +341,8 @@ extension RigidArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @_lifetime(&self) public mutating func mutableSpan( after index: inout Int @@ -379,7 +350,6 @@ extension RigidArray where Element: ~Copyable { _mutableSpan(in: _contiguousSubrange(following: &index)) } - @available(SwiftStdlib 5.0, *) @_lifetime(&self) public mutating func mutableSpan( before index: inout Int @@ -390,6 +360,7 @@ extension RigidArray where Element: ~Copyable { //MARK: - Resizing +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable public mutating func reallocate(capacity newCapacity: Int) { @@ -412,6 +383,7 @@ extension RigidArray where Element: ~Copyable { //MARK: - Copying helpers +@available(SwiftStdlib 5.0, *) extension RigidArray { @inlinable public func copy() -> Self { @@ -432,6 +404,7 @@ extension RigidArray { //MARK: - Opening and closing gaps +@available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable internal mutating func _closeGap( @@ -463,583 +436,7 @@ extension RigidArray where Element: ~Copyable { return unsafe _storage.extracting( Range(uncheckedBounds: (index, index + count))) } -} - -//MARK: - Removal operations - -extension RigidArray where Element: ~Copyable { - /// Removes all elements from the array, preserving its allocated capacity. - /// - /// - Complexity: O(*n*), where *n* is the original count of the array. - @inlinable - public mutating func removeAll() { - unsafe _items.deinitialize() - _count = 0 - } - - /// Removes and returns the last element of the array. - /// - /// The array must not be empty. - /// - /// - Returns: The last element of the original array. - /// - /// - Complexity: O(1) - @inlinable - @discardableResult - public mutating func removeLast() -> Element { - precondition(!isEmpty, "Cannot remove last element from an empty array") - let old = unsafe _storage.moveElement(from: _count - 1) - _count -= 1 - return old - } - - /// Removes and discards the specified number of elements from the end of the - /// array. - /// - /// Attempting to remove more elements than exist in the array - /// triggers a runtime error. - /// - /// - Parameter k: The number of elements to remove from the array. - /// `k` must be greater than or equal to zero and must not exceed - /// the count of the array. - /// - /// - Complexity: O(`k`) - @inlinable - public mutating func removeLast(_ k: Int) { - if k == 0 { return } - precondition( - k >= 0 && k <= _count, - "Count of elements to remove is out of bounds") - unsafe _storage.extracting( - Range(uncheckedBounds: (_count - k, _count)) - ).deinitialize() - _count &-= k - } - - /// Removes and returns the element at the specified position. - /// - /// All the elements following the specified position are moved to close the - /// gap. - /// - /// - Parameter i: The position of the element to remove. `index` must be - /// a valid index of the array that is not equal to the end index. - /// - Returns: The removed element. - /// - /// - Complexity: O(`count`) - @inlinable - @discardableResult - public mutating func remove(at index: Int) -> Element { - precondition(index >= 0 && index < _count, "Index out of bounds") - let old = unsafe _storage.moveElement(from: index) - _closeGap(at: index, count: 1) - _count -= 1 - return old - } - - /// Removes the specified subrange of elements from the array. - /// - /// All the elements following the specified subrange are moved to close the - /// resulting gap. - /// - /// - Parameter bounds: The subrange of the array to remove. The bounds - /// of the range must be valid indices of the array. - /// - /// - Complexity: O(`count`) - @inlinable - public mutating func removeSubrange(_ bounds: Range) { - precondition( - bounds.lowerBound >= 0 && bounds.upperBound <= _count, - "Subrange out of bounds") - guard !bounds.isEmpty else { return } - unsafe _storage.extracting(bounds).deinitialize() - _closeGap(at: bounds.lowerBound, count: bounds.count) - _count -= bounds.count - } - - /// Removes the specified subrange of elements from the array. - /// - /// - Parameter bounds: The subrange of the array to remove. The bounds of the - /// range must be valid indices of the array. - /// - /// - Complexity: O(`count`) - @_alwaysEmitIntoClient - public mutating func removeSubrange(_ bounds: some RangeExpression) { - // FIXME: Remove this in favor of a standard algorithm. - removeSubrange(bounds.relative(to: indices)) - } -} - -extension RigidArray where Element: ~Copyable { - /// Removes and returns the last element of the array, if there is one. - /// - /// - Returns: The last element of the array if the array is not empty; - /// otherwise, `nil`. - /// - /// - Complexity: O(1) - @_alwaysEmitIntoClient - public mutating func popLast() -> Element? { - // FIXME: Remove this in favor of a standard algorithm. - if isEmpty { return nil } - return removeLast() - } -} - -//MARK: - Append operations - -extension RigidArray where Element: ~Copyable { - /// Adds an element to the end of the array. - /// - /// If the array does not have sufficient capacity to hold any more elements, - /// then this triggers a runtime error. - /// - /// - Parameter item: The element to append to the collection. - /// - /// - Complexity: O(1) - @inlinable - public mutating func append(_ item: consuming Element) { - precondition(!isFull, "RigidArray capacity overflow") - unsafe _storage.initializeElement(at: _count, to: item) - _count &+= 1 - } - - /// Adds an element to the end of the array, if possible. - /// - /// If the array does not have sufficient capacity to hold any more elements, - /// then this returns the given item without appending it; otherwise it - /// returns nil. - /// - /// - Parameter item: The element to append to the collection. - /// - Returns: `item` if the array is full; otherwise nil. - /// - /// - Complexity: O(1) - @inlinable - public mutating func pushLast(_ item: consuming Element) -> Element? { - // FIXME: Remove this in favor of a standard algorithm. - if isFull { return item } - append(item) - return nil - } -} - -extension RigidArray where Element: ~Copyable { - /// Moves the elements of a buffer to the end of this array, leaving the - /// buffer uninitialized. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// buffer, then this triggers a runtime error. - /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`items.count`) - @_alwaysEmitIntoClient - public mutating func append( - moving items: UnsafeMutableBufferPointer - ) { - precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - guard items.count > 0 else { return } - let c = unsafe _freeSpace._moveInitializePrefix(from: items) - assert(c == items.count) - _count &+= items.count - } - - /// Appends the elements of a given array to the end of this array by moving - /// them between the containers. On return, the input array becomes empty, but - /// it is not destroyed, and it preserves its original storage capacity. - /// - /// If the target array does not have sufficient capacity to hold all items - /// in the source array, then this triggers a runtime error. - /// - /// - Parameters - /// - items: An array whose items to move to the end of this array. - /// - /// - Complexity: O(`items.count`) - @_alwaysEmitIntoClient - public mutating func append( - moving items: inout RigidArray - ) { - // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers - unsafe items._unsafeEdit { buffer, count in - let source = buffer._extracting(first: count) - unsafe self.append(moving: source) - count = 0 - } - } -} - -extension RigidArray where Element: ~Copyable { - /// Appends the elements of a given container to the end of this array by - /// consuming the source container. - /// - /// If the target array does not have sufficient capacity to hold all items - /// in the source array, then this triggers a runtime error. - /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`items.count`) - @_alwaysEmitIntoClient - public mutating func append( - consuming items: consuming RigidArray - ) { - // FIXME: Remove this in favor of a generic algorithm over consumable containers - var items = items - self.append(moving: &items) - } -} - -extension RigidArray { - /// Copies the elements of a buffer to the end of this array. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// buffer, then this triggers a runtime error. - /// - /// - Parameters - /// - newElements: A fully initialized buffer whose contents to copy into - /// the array. - /// - /// - Complexity: O(`newElements.count`) - @_alwaysEmitIntoClient - public mutating func append( - copying newElements: UnsafeBufferPointer - ) { - precondition( - newElements.count <= freeCapacity, - "RigidArray capacity overflow") - guard newElements.count > 0 else { return } - unsafe _freeSpace.baseAddress.unsafelyUnwrapped.initialize( - from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count) - _count &+= newElements.count - } - - /// Copies the elements of a buffer to the end of this array. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// buffer, then this triggers a runtime error. - /// - /// - Parameters - /// - newElements: A fully initialized buffer whose contents to copy into - /// the array. - /// - /// - Complexity: O(`newElements.count`) - @_alwaysEmitIntoClient - public mutating func append( - copying items: UnsafeMutableBufferPointer - ) { - unsafe self.append(copying: UnsafeBufferPointer(items)) - } - - /// Copies the elements of a span to the end of this array. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// span, then this triggers a runtime error. - /// - /// - Parameters - /// - newElements: A span whose contents to copy into the array. - /// - /// - Complexity: O(`newElements.count`) - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func append(copying items: Span) { - unsafe items.withUnsafeBufferPointer { source in - unsafe self.append(copying: source) - } - } - - @_alwaysEmitIntoClient - @inline(__always) - internal mutating func _append>( - prefixOf items: S - ) -> S.Iterator { - let (it, c) = unsafe items._copyContents(initializing: _freeSpace) - _count += c - return it - } - - /// Copies the elements of a sequence to the end of this array. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// sequence, then this triggers a runtime error. - /// - /// - Parameters - /// - newElements: The new elements to copy into the array. - /// - /// - Complexity: O(*m*), where *m* is the length of `newElements`. - @_alwaysEmitIntoClient - public mutating func append(copying newElements: some Sequence) { - let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in - unsafe self.append(copying: buffer) - return - } - if done != nil { return } - - var it = self._append(prefixOf: newElements) - precondition(it.next() == nil, "RigidArray capacity overflow") - } -} - -//MARK: - Insert operations - - -extension RigidArray where Element: ~Copyable { - /// Inserts a new element into the array at the specified position. - /// - /// If the array does not have sufficient capacity to hold any more elements, - /// then this triggers a runtime error. - /// - /// The new element is inserted before the element currently at the specified - /// index. If you pass the array's `endIndex` as the `index` parameter, then - /// the new element is appended to the container. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// - Parameter item: The new element to insert into the array. - /// - Parameter i: The position at which to insert the new element. - /// `index` must be a valid index in the array. - /// - /// - Complexity: O(`count`) - @inlinable - public mutating func insert(_ item: consuming Element, at index: Int) { - precondition(index >= 0 && index <= count, "Index out of bounds") - precondition(!isFull, "RigidArray capacity overflow") - if index < count { - let source = unsafe _storage.extracting(index ..< count) - let target = unsafe _storage.extracting(index + 1 ..< count + 1) - let last = unsafe target.moveInitialize(fromContentsOf: source) - assert(last == target.endIndex) - } - unsafe _storage.initializeElement(at: index, to: item) - _count += 1 - } -} - -extension RigidArray where Element: ~Copyable { - /// Moves the elements of a fully initialized buffer into this array, - /// starting at the specified position, and leaving the buffer - /// uninitialized. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// buffer, then this triggers a runtime error. - /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: UnsafeMutableBufferPointer, - at index: Int - ) { - precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - guard items.count > 0 else { return } - let target = unsafe _openGap(at: index, count: items.count) - let c = unsafe target._moveInitializePrefix(from: items) - assert(c == items.count) - _count &+= items.count - } - - /// Inserts the elements of a given array into the given position in this - /// array by moving them between the containers. On return, the input array - /// becomes empty, but it is not destroyed, and it preserves its original - /// storage capacity. - /// - /// If the target array does not have sufficient capacity to hold all items - /// in the source array, then this triggers a runtime error. - /// - /// - Parameters - /// - items: An array whose contents to move into `self`. - /// - /// - Complexity: O(`count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: inout RigidArray, - at index: Int - ) { - precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - guard items.count > 0 else { return } - unsafe items._unsafeEdit { buffer, count in - let source = buffer._extracting(first: count) - unsafe self.insert(moving: source, at: index) - count = 0 - } - } -} - -extension RigidArray where Element: ~Copyable { - /// Inserts the elements of a given array into the given position in this - /// array by consuming the source container. - /// - /// If the target array does not have sufficient capacity to hold all items - /// in the source array, then this triggers a runtime error. - /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - consuming items: consuming RigidArray, - at index: Int - ) { - var items = items - self.insert(moving: &items, at: index) - } -} - -extension RigidArray { - /// Copies the elements of a fully initialized buffer pointer into this - /// array at the specified position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array’s `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// - Parameters - /// - newElements: The new elements to insert into the array. The buffer - /// must be fully initialized. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(`count` + `newElements.count`) - @inlinable - public mutating func insert( - copying newElements: UnsafeBufferPointer, at index: Int - ) { - guard newElements.count > 0 else { return } - precondition( - newElements.count <= freeCapacity, - "RigidArray capacity overflow") - let gap = unsafe _openGap(at: index, count: newElements.count) - unsafe gap.baseAddress.unsafelyUnwrapped.initialize( - from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count) - _count += newElements.count - } - - /// Copies the elements of a fully initialized buffer pointer into this - /// array at the specified position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array’s `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// - Parameters - /// - newElements: The new elements to insert into the array. The buffer - /// must be fully initialized. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(`count` + `newElements.count`) - @inlinable - public mutating func insert( - copying newElements: UnsafeMutableBufferPointer, - at index: Int - ) { - unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) - } - - /// Copies the elements of a span into this array at the specified position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array’s `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// - Parameters - /// - newElements: The new elements to insert into the array. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(`count` + `newElements.count`) - @available(SwiftStdlib 5.0, *) - @inlinable - public mutating func insert( - copying newElements: Span, at index: Int - ) { - unsafe newElements.withUnsafeBufferPointer { - unsafe self.insert(copying: $0, at: index) - } - } - - @inlinable - internal mutating func _insertCollection( - at index: Int, - copying items: some Collection, - newCount: Int - ) { - precondition(index >= 0 && index <= _count, "Index out of bounds") - precondition(newCount <= freeCapacity, "RigidArray capacity overflow") - let gap = unsafe _openGap(at: index, count: newCount) - - let done: Void? = items.withContiguousStorageIfAvailable { buffer in - let i = unsafe gap._initializePrefix(copying: buffer) - precondition( - i == newCount, - "Broken Collection: count doesn't match contents") - _count += newCount - } - if done != nil { return } - - var (it, copied) = unsafe items._copyContents(initializing: gap) - precondition( - it.next() == nil && copied == newCount, - "Broken Collection: count doesn't match contents") - _count += newCount - } - - /// Copies the elements of a collection into this array at the specified - /// position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array’s `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved - /// to make room for the new item. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// - Parameters - /// - newElements: The new elements to insert into the array. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(`count` + `newElements.count`) - @inlinable - @inline(__always) - public mutating func insert( - copying newElements: some Collection, at index: Int - ) { - _insertCollection( - at: index, copying: newElements, newCount: newElements.count) - } -} - -//MARK: - Range replacement - -extension RigidArray where Element: ~Copyable { + /// Perform a range replacement up to populating the newly opened gap. This /// deinitializes existing elements in the specified subrange, rearranges /// following elements to be at their final location, and sets the container's @@ -1052,7 +449,6 @@ extension RigidArray where Element: ~Copyable { 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") @@ -1074,290 +470,4 @@ extension RigidArray where Element: ~Copyable { } } -extension RigidArray where Element: ~Copyable { - /// Replaces the specified range of elements by moving the elements of a - /// fully initialized buffer into their place. On return, the buffer is left - /// in an uninitialized state. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - moving newElements: UnsafeMutableBufferPointer, - ) { - let gap = unsafe _gapForReplacement( - of: subrange, withNewCount: newElements.count) - let c = unsafe gap._moveInitializePrefix(from: newElements) - assert(c == newElements.count) - } - - /// Replaces the specified range of elements by moving the elements of a - /// another array into their place. On return, the source array - /// becomes empty, but it is not destroyed, and it preserves its original - /// storage capacity. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: An array whose contents to move into `self`. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - moving newElements: inout RigidArray, - ) { - unsafe newElements._unsafeEdit { buffer, count in - let source = buffer._extracting(first: count) - unsafe self.replaceSubrange(subrange, moving: source) - count = 0 - } - } -} - -extension RigidArray where Element: ~Copyable { - /// Replaces the specified range of elements by moving the elements of a - /// given array into their place, consuming it in the process. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: An array whose contents to move into `self`. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - consuming newElements: consuming RigidArray, - ) { - replaceSubrange(subrange, moving: &newElements) - } -} - -extension RigidArray { - /// Replaces the specified subrange of elements by copying the elements of - /// the given buffer pointer, which must be fully initialized. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: UnsafeBufferPointer - ) { - let gap = unsafe _gapForReplacement( - of: subrange, withNewCount: newElements.count) - let i = unsafe gap._initializePrefix(copying: newElements) - assert(i == gap.count) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given buffer pointer, which must be fully initialized. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: UnsafeMutableBufferPointer - ) { - unsafe self.replaceSubrange( - subrange, - copying: UnsafeBufferPointer(newElements)) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given span. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length span as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @available(SwiftStdlib 5.0, *) - @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: Span - ) { - unsafe newElements.withUnsafeBufferPointer { buffer in - unsafe self.replaceSubrange(subrange, copying: buffer) - } - } - - @inlinable - internal mutating func _replaceSubrange( - _ subrange: Range, - copyingCollection newElements: __owned some Collection, - newCount: Int - ) { - let gap = unsafe _gapForReplacement(of: subrange, withNewCount: newCount) - - let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in - let i = unsafe gap._initializePrefix(copying: buffer) - precondition( - i == newCount, - "Broken Collection: count doesn't match contents") - } - if done != nil { return } - - var (it, copied) = unsafe newElements._copyContents(initializing: gap) - precondition( - it.next() == nil && copied == newCount, - "Broken Collection: count doesn't match contents") - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given collection. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the capacity of the array isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length collection as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: __owned some Collection - ) { - _replaceSubrange( - subrange, copyingCollection: newElements, newCount: newElements.count) - } -} #endif diff --git a/Sources/BasicContainers/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray+Append.swift new file mode 100644 index 00000000..36d96574 --- /dev/null +++ b/Sources/BasicContainers/UniqueArray+Append.swift @@ -0,0 +1,265 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Adds an element to the end of the array. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this reallocates the array's storage to grow its capacity. + /// + /// - Parameter item: The element to append to the collection. + /// + /// - Complexity: O(1) when amortized over many invocations on the same array + @inlinable + public mutating func append(_ item: consuming Element) { + _ensureFreeCapacity(1) + _storage.append(item) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @_alwaysEmitIntoClient + public mutating func append( + count: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Result + ) throws(E) -> Result { + _ensureFreeCapacity(count) + return try _storage.append(count: count, initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Moves the elements of a buffer to the end of this array, leaving the + /// buffer uninitialized. + /// + /// If the array does not have sufficient capacity to hold all items in the + /// buffer, then this reallocates the array's storage to grow its capacity. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`items.count`) when amortized over many invocations on + /// the same array + @_alwaysEmitIntoClient + public mutating func append( + moving items: UnsafeMutableBufferPointer + ) { + _ensureFreeCapacity(items.count) + _storage.append(moving: items) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout InputSpan + ) { + _ensureFreeCapacity(items.count) + _storage.append(moving: &items) + } +#endif + + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout OutputSpan + ) { + _ensureFreeCapacity(items.count) + _storage.append(moving: &items) + } + + /// Appends the elements of a given array to the end of this array by moving + /// them between the containers. On return, the input array becomes empty, but + /// it is not destroyed, and it preserves its original storage capacity. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this automatically grows the target array's + /// capacity. + /// + /// - Parameters + /// - items: An array whose items to move to the end of this array. + /// + /// - Complexity: O(`items.count`) when amortized over many invocations on + /// the same array + @_alwaysEmitIntoClient + public mutating func append( + moving items: inout RigidArray + ) { + // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers + _ensureFreeCapacity(items.count) + _storage.append(moving: &items) + } +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Appends the elements of a given container to the end of this array by + /// consuming the source container. + /// + /// If the target array does not have sufficient capacity to hold all items + /// in the source array, then this triggers a runtime error. + /// + /// - Parameters + /// - items: An array whose items to move to the end of this array. + /// + /// - Complexity: O(`items.count`) + @_alwaysEmitIntoClient + public mutating func append( + consuming items: consuming RigidArray + ) { + // FIXME: Remove this in favor of a generic algorithm over consumable containers + var items = items + self.append(moving: &items) + } +} +#endif + +@available(SwiftStdlib 5.0, *) +extension UniqueArray { + /// 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. + @_alwaysEmitIntoClient + public mutating func append(copying newElements: Span) { + _ensureFreeCapacity(newElements.count) + _storage.append(copying: newElements) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append< + Source: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing Source + ) { + _ensureFreeCapacity(newElements.count) + _storage._append(copyingContainer: newElements) + } + +#endif + + /// 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) + } + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func append< + Source: Container & Sequence + >(copying newElements: Source) { + _ensureFreeCapacity(newElements.count) + _storage._append(copyingContainer: newElements) + } +#endif + +} + +#endif diff --git a/Sources/BasicContainers/UniqueArray+Experimental.swift b/Sources/BasicContainers/UniqueArray+Experimental.swift index 5c55b284..1b807602 100644 --- a/Sources/BasicContainers/UniqueArray+Experimental.swift +++ b/Sources/BasicContainers/UniqueArray+Experimental.swift @@ -15,12 +15,10 @@ import InternalCollectionsUtilities import ContainersPreview #endif -#if compiler(>=6.2) -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW -#if FIXME +#if false // TODO extension UniqueArray /*where Element: Copyable*/ { - @available(SwiftStdlib 6.2, *) @_alwaysEmitIntoClient @inline(__always) public init & ~Copyable & ~Escapable>( @@ -30,7 +28,6 @@ extension UniqueArray /*where Element: Copyable*/ { self.init(consuming: RigidArray(capacity: capacity, copying: contents)) } - @available(SwiftStdlib 6.2, *) @_alwaysEmitIntoClient @inline(__always) public init & Sequence>( @@ -42,7 +39,7 @@ extension UniqueArray /*where Element: Copyable*/ { } #endif -#if FIXME +#if false // TODO extension UniqueArray where Element: ~Copyable { @inlinable @inline(__always) @@ -53,22 +50,19 @@ extension UniqueArray where Element: ~Copyable { } #endif -#if FIXME -extension UniqueArray: RandomAccessContainer where Element: ~Copyable {} -#endif - -#if FIXME +#if false // TODO extension UniqueArray where Element: ~Copyable { @inlinable @_lifetime(&self) - public mutating func mutateElement(at index: Int) -> Inout { + public mutating func mutateElement(at index: Int) -> Mut { _storage.mutateElement(at: index) } } #endif +#if false // TODO +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @_alwaysEmitIntoClient @_transparent internal mutating func _edit( @@ -83,8 +77,10 @@ extension UniqueArray where Element: ~Copyable { return _storage.reallocate(capacity: newCapacity, with: reallocatingMutation) } } +#endif -#if FIXME +#if false // TODO +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { /// Removes all the elements that satisfy the given predicate. /// @@ -96,7 +92,6 @@ extension UniqueArray where Element: ~Copyable { /// whether the element should be removed from the array. /// /// - Complexity: O(`count`) - @available(SwiftStdlib 6.2, *) @_alwaysEmitIntoClient public mutating func removeAll( where shouldBeRemoved: (borrowing Element) throws(E) -> Bool @@ -108,258 +103,4 @@ extension UniqueArray where Element: ~Copyable { } #endif -extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func append( - moving items: inout InputSpan - ) { - _ensureFreeCapacity(items.count) - _storage.append(moving: &items) - } - - @available(SwiftStdlib 5.0, *) - @_alwaysEmitIntoClient - public mutating func append( - moving items: inout OutputSpan - ) { - _ensureFreeCapacity(items.count) - _storage.append(moving: &items) - } -} - -extension UniqueArray { -#if FIXME - public mutating func _appendContainer< - C: Container & ~Copyable & ~Escapable - >( - copying newElements: borrowing C - ) { - var i = newElements.startIndex - while true { - let span = newElements.span(after: &i) - if span.isEmpty { break } - self.append(copying: span) - } - } -#endif - -#if FIXME - /// 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(SwiftStdlib 6.2, *) - @_alwaysEmitIntoClient - public mutating func append< - C: Container & ~Copyable & ~Escapable - >( - copying newElements: borrowing C - ) { - _appendContainer(copying: newElements) - } -#endif - -#if FIXME - /// 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(SwiftStdlib 6.2, *) - @_alwaysEmitIntoClient - public mutating func append< - C: Container & Sequence - >( - copying newElements: borrowing C - ) { - _appendContainer(copying: newElements) - } -#endif -} - -#if FIXME -extension UniqueArray { - @available(SwiftStdlib 6.2, *) - @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(SwiftStdlib 6.2, *) - @_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(SwiftStdlib 6.2, *) - @_alwaysEmitIntoClient - @inline(__always) - public mutating func insert< - C: Container & Collection - >( - copying newElements: borrowing C, at index: Int - ) { - _insertContainer(copying: newElements, at: index) - } - -} -#endif - -#if FIXME -extension UniqueArray { - @available(SwiftStdlib 6.2, *) - @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(SwiftStdlib 6.2, *) - @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(SwiftStdlib 6.2, *) - @inlinable - @inline(__always) - public mutating func replaceSubrange< - C: Container & Collection - >( - _ subrange: Range, - copying newElements: borrowing C - ) { - _replaceSubrange(subrange, copyingContainer: newElements) - } -} -#endif - -#endif #endif diff --git a/Sources/BasicContainers/UniqueArray+Initializers.swift b/Sources/BasicContainers/UniqueArray+Initializers.swift new file mode 100644 index 00000000..5a2dfe3f --- /dev/null +++ b/Sources/BasicContainers/UniqueArray+Initializers.swift @@ -0,0 +1,91 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @inlinable + public init( + capacity: Int, + initializingWith body: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + self.init(capacity: capacity) + try edit(body) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray /*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)) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @inlinable + public init(consuming storage: consuming RigidArray) { + self._storage = storage + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray /*where Element: Copyable*/ { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + @inline(__always) + public init & ~Copyable & ~Escapable>( + capacity: Int? = nil, + copying contents: borrowing Source + ) { + self.init(capacity: capacity ?? 0) + self.append(copying: contents) + } +#endif + + @_alwaysEmitIntoClient + @inline(__always) + public init( + capacity: Int? = nil, + copying contents: some Sequence + ) { + self.init(capacity: capacity ?? 0) + self.append(copying: contents) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + @inline(__always) + public init & Sequence>( + capacity: Int? = nil, + copying contents: Source + ) { + self.init(capacity: capacity ?? 0) + self.append(copying: contents) + } +#endif + +} + +#endif diff --git a/Sources/BasicContainers/UniqueArray+Insertions.swift b/Sources/BasicContainers/UniqueArray+Insertions.swift new file mode 100644 index 00000000..62d4f20e --- /dev/null +++ b/Sources/BasicContainers/UniqueArray+Insertions.swift @@ -0,0 +1,339 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Inserts a new element into the array at the specified position. + /// + /// If the array does not have sufficient capacity to hold any more elements, + /// then this reallocates storage to extend its capacity. + /// + /// The new element is inserted before the element currently at the specified + /// index. If you pass the array's `endIndex` as the `index` parameter, then + /// the new element is appended to the container. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// - Parameter item: The new element to insert into the array. + /// - Parameter i: The position at which to insert the new element. + /// `index` must be a valid index in the array. + /// + /// - Complexity: O(`self.count`) + @inlinable + public mutating func insert(_ item: consuming Element, at index: Int) { + precondition(index >= 0 && index <= count) + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(1) + _storage.insert(item, at: index) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @inlinable + public mutating func insert( + count: Int, + at index: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + // FIXME: This does not allow `body` to throw, to prevent having to move the tail twice. Is that okay? + _ensureFreeCapacity(count) + return _storage.insert(count: count, at: index, initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Moves the elements of a fully initialized buffer into this array, + /// starting at the specified position, and leaving the buffer + /// uninitialized. + /// + /// If the array does not have sufficient capacity to hold all elements, + /// then this reallocates storage to extend its capacity. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: UnsafeMutableBufferPointer, + at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(items.count) + _storage.insert(moving: items, at: index) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout InputSpan, + at index: Int + ) { + _ensureFreeCapacity(items.count) + _storage.insert(moving: &items, at: index) + } +#endif + + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout OutputSpan, + at index: Int + ) { + _ensureFreeCapacity(items.count) + _storage.insert(moving: &items, at: index) + } + + /// Inserts the elements of a given array into the given position in this + /// array by moving them between the containers. On return, the input array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// If the array does not have sufficient capacity to hold all elements, + /// then this reallocates storage to extend its capacity. + /// + /// - Parameters + /// - items: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + moving items: inout RigidArray, + at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(items.count) + _storage.insert(moving: &items, at: index) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Inserts the elements of a given array into the given position in this + /// array by consuming the source container. + /// + /// If the array does not have sufficient capacity to hold all elements, + /// then this reallocates storage to extend its capacity. + /// + /// - Parameters + /// - items: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `items.count`) + @_alwaysEmitIntoClient + public mutating func insert( + consuming items: consuming RigidArray, + at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(items.count) + _storage.insert(consuming: items, at: index) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray { + /// Copyies the elements of a fully initialized buffer pointer into this + /// array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeBufferPointer, at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count) + unsafe _storage.insert(copying: newElements, at: index) + } + + /// Copyies the elements of a fully initialized buffer pointer into this + /// array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. The buffer + /// must be fully initialized. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: UnsafeMutableBufferPointer, + at index: Int + ) { + unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) + } + + /// Copies the elements of a span into this array at the specified position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new item. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: Span, at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count) + _storage.insert(copying: newElements, at: index) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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`. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & ~Copyable & ~Escapable + >( + copying newElements: borrowing C, at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + let c = newElements.count + _ensureFreeCapacity(c) + _storage._insertContainer(at: index, copying: newElements, newCount: c) + } +#endif + + /// Copies the elements of a collection into this array at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the array’s `endIndex` as the `index` + /// parameter, then the new elements are appended to the end of the array. + /// + /// All existing elements at or following the specified position are moved + /// to make room for the new item. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// - Parameters + /// - newElements: The new elements to insert into the array. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @inlinable + public mutating func insert( + copying newElements: some Collection, at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + let newCount = newElements.count + _ensureFreeCapacity(newCount) + _storage._insertCollection( + at: index, copying: newElements, newCount: newCount) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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`. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & Collection + >( + copying newElements: borrowing C, at index: Int + ) { + // FIXME: Avoid moving the subsequent elements twice. + let c = newElements.count + _ensureFreeCapacity(c) + _storage._insertContainer(at: index, copying: newElements, newCount: c) + } +#endif +} + +#endif diff --git a/Sources/BasicContainers/UniqueArray+Removals.swift b/Sources/BasicContainers/UniqueArray+Removals.swift new file mode 100644 index 00000000..e84e9a8f --- /dev/null +++ b/Sources/BasicContainers/UniqueArray+Removals.swift @@ -0,0 +1,149 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Removes all elements from the array, optionally preserving its + /// allocated capacity. + /// + /// - Complexity: O(*n*), where *n* is the original count of the array. + @inlinable + @inline(__always) + public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { + if keepCapacity { + _storage.removeAll() + } else { + _storage = RigidArray(capacity: 0) + } + } + + /// Removes and returns the last element of the array. + /// + /// The array must not be empty. + /// + /// - Returns: The last element of the original array. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + @discardableResult + public mutating func removeLast() -> Element { + _storage.removeLast() + } + + /// Removes and discards the specified number of elements from the end of the + /// array. + /// + /// Attempting to remove more elements than exist in the array triggers a + /// runtime error. + /// + /// - Parameter k: The number of elements to remove from the array. + /// `k` must be greater than or equal to zero and must not exceed + /// the count of the array. + /// + /// - Complexity: O(`k`) + @inlinable + public mutating func removeLast(_ k: Int) { + _storage.removeLast(k) + } + + /// Removes and returns the element at the specified position. + /// + /// All the elements following the specified position are moved to close the + /// gap. + /// + /// - Parameter i: The position of the element to remove. `index` must be + /// a valid index of the array that is not equal to the end index. + /// - Returns: The removed element. + /// + /// - Complexity: O(`self.count`) + @inlinable + @inline(__always) + @discardableResult + public mutating func remove(at index: Int) -> Element { + _storage.remove(at: index) + } + + /// Removes the specified subrange of elements from the array. + /// + /// All the elements following the specified subrange are moved to close the + /// resulting gap. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds + /// of the range must be valid indices of the array. + /// + /// - Complexity: O(`self.count`) + @inlinable + public mutating func removeSubrange(_ bounds: Range) { + _storage.removeSubrange(bounds) + } + + /// Removes the specified subrange of elements from the array. + /// + /// - Parameter bounds: The subrange of the array to remove. The bounds + /// of the range must be valid indices of the array. + /// + /// - Complexity: O(`self.count`) + @_alwaysEmitIntoClient + public mutating func removeSubrange(_ bounds: some RangeExpression) { + // FIXME: Remove this in favor of a standard algorithm. + removeSubrange(bounds.relative(to: indices)) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray 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() + } +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @_lifetime(&self) + @_alwaysEmitIntoClient + public mutating func consumeAll() -> InputSpan { + _storage.consumeAll() + } + + @_lifetime(&self) + @_alwaysEmitIntoClient + public mutating func consumeLast(_ count: Int) -> InputSpan { + _storage.consumeLast(count) + } + + @_alwaysEmitIntoClient + public mutating func consumeSubrange( + _ bounds: Range, + consumingWith body: (inout InputSpan) throws(E) -> Result + ) throws(E) -> Result { + try _storage.consumeSubrange(bounds, consumingWith: body) + } +} +#endif + +#endif diff --git a/Sources/BasicContainers/UniqueArray+Replacements.swift b/Sources/BasicContainers/UniqueArray+Replacements.swift new file mode 100644 index 00000000..e4f72815 --- /dev/null +++ b/Sources/BasicContainers/UniqueArray+Replacements.swift @@ -0,0 +1,399 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2024 - 2025 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import ContainersPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + newCount: Int, + initializingWith body: (inout OutputSpan) -> Result + ) -> Result { + // FIXME: Should we allow throwing (and a partially filled output span)? + // FIXME: Should we have a version of this with two closures, to allow custom-consuming the old items? + // replaceSubrange(5..<10, newCount: 3, consumingWith: {...}, initializingWith: {...}) + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newCount - subrange.count) + return _storage.replaceSubrange( + subrange, newCount: newCount, initializingWith: body) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// fully initialized buffer into their place. On return, the buffer is left + /// in an uninitialized state. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: A fully initialized buffer whose contents to move into + /// the array. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: UnsafeMutableBufferPointer, + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count - subrange.count) + _storage.replaceSubrange(subrange, moving: newElements) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout InputSpan + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(items.count - subrange.count) + _storage.replaceSubrange(subrange, moving: &items) + } +#endif + + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving items: inout OutputSpan + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(items.count - subrange.count) + _storage.replaceSubrange(subrange, moving: &items) + } + + /// Replaces the specified range of elements by moving the elements of a + /// another array into their place. On return, the source array + /// becomes empty, but it is not destroyed, and it preserves its original + /// storage capacity. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + moving newElements: inout RigidArray, + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count - subrange.count) + _storage.replaceSubrange(subrange, moving: &newElements) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + /// Replaces the specified range of elements by moving the elements of a + /// given array into their place, consuming it in the process. + /// + /// This method has the effect of removing the specified range of elements + /// from the array and inserting the new elements starting at the same + /// location. The number of new elements need not match the number of elements + /// being removed. + /// + /// If the array does not have sufficient capacity to hold enough elements, + /// then this reallocates the array's storage to extend its capacity. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling + /// the `insert(copying:at:)` method instead is preferred in this case. + /// + /// Likewise, if you pass a zero-length buffer as the `newElements` + /// parameter, this method removes the elements in the given subrange + /// without replacement. Calling the `removeSubrange(_:)` method instead is + /// preferred in this case. + /// + /// - Parameters + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newElements: An array whose contents to move into `self`. + /// + /// - Complexity: O(`self.count` + `newElements.count`) + @_alwaysEmitIntoClient + public mutating func replaceSubrange( + _ subrange: Range, + consuming newElements: consuming RigidArray, + ) { + replaceSubrange(subrange, moving: &newElements) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueArray { + /// 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: Avoid 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`. + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + copying newElements: Span + ) { + // FIXME: Avoid moving the subsequent elements twice. + _ensureFreeCapacity(newElements.count) + _storage.replaceSubrange(subrange, copying: newElements) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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`. + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, + copying newElements: borrowing C + ) { + // FIXME: Avoid moving the subsequent elements twice. + let c = newElements.count + _ensureFreeCapacity(c - subrange.count) + _storage._replaceSubrange( + subrange, copyingContainer: newElements, newCount: c) + } +#endif + + /// 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: Avoid moving the subsequent elements twice. + let c = newElements.count + _ensureFreeCapacity(c) + _storage._replaceSubrange( + subrange, copyingCollection: newElements, newCount: c) + } + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// 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`. + @inlinable + @inline(__always) + public mutating func replaceSubrange< + C: Container & Collection + >( + _ subrange: Range, + copying newElements: borrowing C + ) { + // FIXME: Avoid moving the subsequent elements twice. + let c = newElements.count + _ensureFreeCapacity(c - subrange.count) + _storage._replaceSubrange( + subrange, copyingContainer: newElements, newCount: c) + } +#endif +} +#endif diff --git a/Sources/BasicContainers/UniqueArray.swift b/Sources/BasicContainers/UniqueArray.swift index 891c9a13..7711122c 100644 --- a/Sources/BasicContainers/UniqueArray.swift +++ b/Sources/BasicContainers/UniqueArray.swift @@ -11,6 +11,7 @@ #if !COLLECTIONS_SINGLE_MODULE import InternalCollectionsUtilities +import ContainersPreview #endif #if compiler(<6.2) @@ -56,70 +57,29 @@ public struct UniqueArray: ~Copyable { /// resizing array types as a matter of policy. The type `RigidArray` provides /// a fixed-capacity array variant that caters specifically for these use cases, /// trading ease-of-use for more consistent/predictable execution. +@available(SwiftStdlib 5.0, *) @frozen public struct UniqueArray: ~Copyable { @usableFromInline internal var _storage: RigidArray + @inlinable + public init(capacity: Int) { + _storage = .init(capacity: capacity) + } + @inlinable public init() { _storage = .init(capacity: 0) } } + +@available(SwiftStdlib 5.0, *) extension UniqueArray: Sendable where Element: Sendable & ~Copyable {} -//MARK: - Initializers - -extension UniqueArray where Element: ~Copyable { - @inlinable - public init(capacity: Int) { - _storage = .init(capacity: capacity) - } -} - -extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) - @inlinable - public init( - capacity: Int, - initializedWith body: (inout OutputSpan) throws(E) -> Void - ) throws(E) { - self.init(capacity: capacity) - try edit(body) - } -} - -extension UniqueArray where Element: ~Copyable { - @inlinable - public init(consuming storage: consuming RigidArray) { - self._storage = storage - } -} - -extension UniqueArray /*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 UniqueArray /*where Element: Copyable*/ { - @_alwaysEmitIntoClient - @inline(__always) - public init(capacity: Int? = nil, copying contents: some Sequence) { - self.init(capacity: capacity ?? 0) - self.append(copying: contents) - } -} - //MARK: - Basics +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { @inlinable @inline(__always) @@ -134,8 +94,8 @@ extension UniqueArray where Element: ~Copyable { //MARK: - Span creation +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) public var span: Span { @_lifetime(borrow self) @inlinable @@ -154,6 +114,7 @@ extension UniqueArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { /// Arbitrarily edit the storage underlying this array by invoking a /// user-supplied closure with a mutable `OutputSpan` view over it. @@ -172,7 +133,6 @@ extension UniqueArray where Element: ~Copyable { /// - Returns: This method returns the result of its function argument. /// - Complexity: Adds O(1) overhead to the complexity of the function /// argument. - @available(SwiftStdlib 5.0, *) @inlinable @inline(__always) public mutating func edit( _ body: (inout OutputSpan) throws(E) -> R @@ -181,11 +141,10 @@ extension UniqueArray where Element: ~Copyable { } } -//MARK: - Random-access & mutable container primitives +//MARK: - Container primitives +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - public typealias Index = Int - @inlinable @inline(__always) public var isEmpty: Bool { _storage.isEmpty } @@ -193,6 +152,24 @@ extension UniqueArray where Element: ~Copyable { @inlinable @inline(__always) public var count: Int { _storage.count } +} + +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +@available(SwiftStdlib 5.0, *) +extension UniqueArray: Container where Element: ~Copyable { + public typealias BorrowIterator = RigidArray.BorrowIterator + + @_alwaysEmitIntoClient + @inline(__always) + public func startBorrowIteration() -> Span { + self._storage.startBorrowIteration() + } +} +#endif + +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { + public typealias Index = Int @inlinable @inline(__always) @@ -217,6 +194,7 @@ extension UniqueArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { @inlinable public mutating func swapAt(_ i: Int, _ j: Int) { @@ -224,15 +202,14 @@ extension UniqueArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(borrow self) public func span(after index: inout Int) -> Span { _storage.span(after: &index) } - @available(SwiftStdlib 5.0, *) @inlinable @_lifetime(borrow self) public func span(before index: inout Int) -> Span { @@ -240,8 +217,8 @@ extension UniqueArray where Element: ~Copyable { } } +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - @available(SwiftStdlib 5.0, *) @_lifetime(&self) public mutating func mutableSpan( after index: inout Int @@ -249,7 +226,6 @@ extension UniqueArray where Element: ~Copyable { _storage.mutableSpan(after: &index) } - @available(SwiftStdlib 5.0, *) @_lifetime(&self) public mutating func mutableSpan( before index: inout Int @@ -269,6 +245,7 @@ internal func _growDynamicArrayCapacity(_ capacity: Int) -> Int { return Int(bitPattern: c) } +@available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { @inlinable @inline(never) public mutating func reallocate(capacity: Int) { @@ -302,749 +279,4 @@ extension UniqueArray where Element: ~Copyable { } } -//MARK: - Removal operations - -extension UniqueArray where Element: ~Copyable { - /// Removes all elements from the array, optionally preserving its - /// allocated capacity. - /// - /// - Complexity: O(*n*), where *n* is the original count of the array. - @inlinable - @inline(__always) - public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - if keepCapacity { - _storage.removeAll() - } else { - _storage = RigidArray(capacity: 0) - } - } - - /// Removes and returns the last element of the array. - /// - /// The array must not be empty. - /// - /// - Returns: The last element of the original array. - /// - /// - Complexity: O(1) - @inlinable - @inline(__always) - @discardableResult - public mutating func removeLast() -> Element { - _storage.removeLast() - } - - /// Removes and discards the specified number of elements from the end of the - /// array. - /// - /// Attempting to remove more elements than exist in the array triggers a - /// runtime error. - /// - /// - Parameter k: The number of elements to remove from the array. - /// `k` must be greater than or equal to zero and must not exceed - /// the count of the array. - /// - /// - Complexity: O(`k`) - @inlinable - public mutating func removeLast(_ k: Int) { - _storage.removeLast(k) - } - - /// Removes and returns the element at the specified position. - /// - /// All the elements following the specified position are moved to close the - /// gap. - /// - /// - Parameter i: The position of the element to remove. `index` must be - /// a valid index of the array that is not equal to the end index. - /// - Returns: The removed element. - /// - /// - Complexity: O(`self.count`) - @inlinable - @inline(__always) - @discardableResult - public mutating func remove(at index: Int) -> Element { - _storage.remove(at: index) - } - - /// Removes the specified subrange of elements from the array. - /// - /// All the elements following the specified subrange are moved to close the - /// resulting gap. - /// - /// - Parameter bounds: The subrange of the array to remove. The bounds - /// of the range must be valid indices of the array. - /// - /// - Complexity: O(`self.count`) - @inlinable - public mutating func removeSubrange(_ bounds: Range) { - _storage.removeSubrange(bounds) - } - - /// Removes the specified subrange of elements from the array. - /// - /// - Parameter bounds: The subrange of the array to remove. The bounds - /// of the range must be valid indices of the array. - /// - /// - Complexity: O(`self.count`) - @_alwaysEmitIntoClient - public mutating func removeSubrange(_ bounds: some RangeExpression) { - // FIXME: Remove this in favor of a standard algorithm. - removeSubrange(bounds.relative(to: indices)) - } -} - -extension UniqueArray where Element: ~Copyable { - /// Removes and returns the last element of the array, if there is one. - /// - /// - Returns: The last element of the array if the array is not empty; - /// otherwise, `nil`. - /// - /// - Complexity: O(1) - @_alwaysEmitIntoClient - public mutating func popLast() -> Element? { - if isEmpty { return nil } - return removeLast() - } -} - -//MARK: - Append operations - -extension UniqueArray where Element: ~Copyable { - /// Adds an element to the end of the array. - /// - /// If the array does not have sufficient capacity to hold any more elements, - /// then this reallocates the array's storage to grow its capacity. - /// - /// - Parameter item: The element to append to the collection. - /// - /// - Complexity: O(1) when amortized over many invocations on the same array - @inlinable - public mutating func append(_ item: consuming Element) { - _ensureFreeCapacity(1) - _storage.append(item) - } -} - -extension UniqueArray where Element: ~Copyable { - /// Moves the elements of a buffer to the end of this array, leaving the - /// buffer uninitialized. - /// - /// If the array does not have sufficient capacity to hold all items in the - /// buffer, then this reallocates the array's storage to grow its capacity. - /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`items.count`) when amortized over many invocations on - /// the same array - @_alwaysEmitIntoClient - public mutating func append( - moving items: UnsafeMutableBufferPointer - ) { - _ensureFreeCapacity(items.count) - _storage.append(moving: items) - } - - /// Appends the elements of a given array to the end of this array by moving - /// them between the containers. On return, the input array becomes empty, but - /// it is not destroyed, and it preserves its original storage capacity. - /// - /// If the target array does not have sufficient capacity to hold all items - /// in the source array, then this automatically grows the target array's - /// capacity. - /// - /// - Parameters - /// - items: An array whose items to move to the end of this array. - /// - /// - Complexity: O(`items.count`) when amortized over many invocations on - /// the same array - @_alwaysEmitIntoClient - public mutating func append( - moving items: inout RigidArray - ) { - // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers - _ensureFreeCapacity(items.count) - _storage.append(moving: &items) - } -} - -extension UniqueArray where Element: ~Copyable { - /// Appends the elements of a given container to the end of this array by - /// consuming the source container. - /// - /// If the target array does not have sufficient capacity to hold all items - /// in the source array, then this triggers a runtime error. - /// - /// - Parameters - /// - items: An array whose items to move to the end of this array. - /// - /// - Complexity: O(`items.count`) - @_alwaysEmitIntoClient - public mutating func append( - consuming items: consuming RigidArray - ) { - // FIXME: Remove this in favor of a generic algorithm over consumable containers - var items = items - self.append(moving: &items) - } -} - -extension UniqueArray { - /// Copies the elements of a buffer to the end of this array. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: A fully initialized buffer whose contents to copy into - /// the array. - /// - /// - Complexity: O(`newElements.count`) when amortized over many - /// invocations on the same array. - @_alwaysEmitIntoClient - public mutating func append( - copying newElements: UnsafeBufferPointer - ) { - _ensureFreeCapacity(newElements.count) - unsafe _storage.append(copying: newElements) - } - - /// Copies the elements of a buffer to the end of this array. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: A fully initialized buffer whose contents to copy into - /// the array. - /// - /// - Complexity: O(`newElements.count`) when amortized over many - /// invocations on the same array. - @_alwaysEmitIntoClient - public mutating func append( - copying newElements: UnsafeMutableBufferPointer - ) { - unsafe self.append(copying: UnsafeBufferPointer(newElements)) - } - - /// Copies the elements of a span to the end of this array. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: A span whose contents to copy into the array. - /// - /// - Complexity: O(`newElements.count`) when amortized over many - /// invocations on the same array. - @available(SwiftStdlib 6.2, *) - @_alwaysEmitIntoClient - public mutating func append(copying newElements: Span) { - _ensureFreeCapacity(newElements.count) - _storage.append(copying: newElements) - } - - /// Copies the elements of a sequence to the end of this array. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. This - /// reallocation can happen multiple times. - /// - /// - Parameters - /// - newElements: The new elements to copy into the array. - /// - /// - Complexity: O(*m*), where *m* is the length of `newElements`, when - /// amortized over many invocations over the same array. - @_alwaysEmitIntoClient - public mutating func append(copying newElements: some Sequence) { - let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in - _ensureFreeCapacity(buffer.count) - unsafe _storage.append(copying: buffer) - return - } - if done != nil { return } - - _ensureFreeCapacity(newElements.underestimatedCount) - var it = _storage._append(prefixOf: newElements) - while let item = it.next() { - _ensureFreeCapacity(1) - _storage.append(item) - } - } -} - -//MARK: - Insert operations - -extension UniqueArray where Element: ~Copyable { - /// Inserts a new element into the array at the specified position. - /// - /// If the array does not have sufficient capacity to hold any more elements, - /// then this reallocates storage to extend its capacity. - /// - /// The new element is inserted before the element currently at the specified - /// index. If you pass the array's `endIndex` as the `index` parameter, then - /// the new element is appended to the container. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// - Parameter item: The new element to insert into the array. - /// - Parameter i: The position at which to insert the new element. - /// `index` must be a valid index in the array. - /// - /// - Complexity: O(`self.count`) - @inlinable - public mutating func insert(_ item: consuming Element, at index: Int) { - precondition(index >= 0 && index <= count) - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(1) - _storage.insert(item, at: index) - } -} - -extension UniqueArray where Element: ~Copyable { - /// Moves the elements of a fully initialized buffer into this array, - /// starting at the specified position, and leaving the buffer - /// uninitialized. - /// - /// If the array does not have sufficient capacity to hold all elements, - /// then this reallocates storage to extend its capacity. - /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`self.count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: UnsafeMutableBufferPointer, - at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(items.count) - _storage.insert(moving: items, at: index) - } - - /// Inserts the elements of a given array into the given position in this - /// array by moving them between the containers. On return, the input array - /// becomes empty, but it is not destroyed, and it preserves its original - /// storage capacity. - /// - /// If the array does not have sufficient capacity to hold all elements, - /// then this reallocates storage to extend its capacity. - /// - /// - Parameters - /// - items: An array whose contents to move into `self`. - /// - /// - Complexity: O(`self.count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - moving items: inout RigidArray, - at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(items.count) - _storage.insert(moving: &items, at: index) - } -} - -extension UniqueArray where Element: ~Copyable { - /// Inserts the elements of a given array into the given position in this - /// array by consuming the source container. - /// - /// If the array does not have sufficient capacity to hold all elements, - /// then this reallocates storage to extend its capacity. - /// - /// - Parameters - /// - items: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`self.count` + `items.count`) - @_alwaysEmitIntoClient - public mutating func insert( - consuming items: consuming RigidArray, - at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(items.count) - _storage.insert(consuming: items, at: index) - } -} - -extension UniqueArray { - /// Copyies the elements of a fully initialized buffer pointer into this - /// array at the specified position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array’s `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: The new elements to insert into the array. The buffer - /// must be fully initialized. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - public mutating func insert( - copying newElements: UnsafeBufferPointer, at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count) - unsafe _storage.insert(copying: newElements, at: index) - } - - /// Copyies the elements of a fully initialized buffer pointer into this - /// array at the specified position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array’s `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: The new elements to insert into the array. The buffer - /// must be fully initialized. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - public mutating func insert( - copying newElements: UnsafeMutableBufferPointer, - at index: Int - ) { - unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) - } - - /// Copies the elements of a span into this array at the specified position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array’s `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved to - /// make room for the new item. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: The new elements to insert into the array. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @available(SwiftStdlib 6.2, *) - @inlinable - public mutating func insert( - copying newElements: Span, at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count) - _storage.insert(copying: newElements, at: index) - } - - /// Copies the elements of a collection into this array at the specified - /// position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the array’s `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the array. - /// - /// All existing elements at or following the specified position are moved - /// to make room for the new item. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// - Parameters - /// - newElements: The new elements to insert into the array. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the array. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - public mutating func insert( - copying newElements: some Collection, at index: Int - ) { - // FIXME: Avoiding moving the subsequent elements twice. - let newCount = newElements.count - _ensureFreeCapacity(newCount) - _storage._insertCollection( - at: index, copying: newElements, newCount: newCount) - } -} - -//MARK: - Range replacement - -extension UniqueArray where Element: ~Copyable { - /// Replaces the specified range of elements by moving the elements of a - /// fully initialized buffer into their place. On return, the buffer is left - /// in an uninitialized state. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: A fully initialized buffer whose contents to move into - /// the array. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - moving newElements: UnsafeMutableBufferPointer, - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count - subrange.count) - _storage.replaceSubrange(subrange, moving: newElements) - } - - /// Replaces the specified range of elements by moving the elements of a - /// another array into their place. On return, the source array - /// becomes empty, but it is not destroyed, and it preserves its original - /// storage capacity. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: An array whose contents to move into `self`. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - moving newElements: inout RigidArray, - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count - subrange.count) - _storage.replaceSubrange(subrange, moving: &newElements) - } -} - -extension UniqueArray where Element: ~Copyable { - /// Replaces the specified range of elements by moving the elements of a - /// given array into their place, consuming it in the process. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same - /// location. The number of new elements need not match the number of elements - /// being removed. - /// - /// If the array does not have sufficient capacity to hold enough elements, - /// then this reallocates the array's storage to extend its capacity. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: An array whose contents to move into `self`. - /// - /// - Complexity: O(`self.count` + `newElements.count`) - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - consuming newElements: consuming RigidArray, - ) { - replaceSubrange(subrange, moving: &newElements) - } -} - -extension UniqueArray { - /// Replaces the specified subrange of elements by copying the elements of - /// the given buffer pointer, which must be fully initialized. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same location. - /// The number of new elements need not match the number of elements being - /// removed. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @inlinable - @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: UnsafeBufferPointer - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count) - unsafe _storage.replaceSubrange(subrange, copying: newElements) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given buffer pointer, which must be fully initialized. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same location. - /// The number of new elements need not match the number of elements being - /// removed. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length buffer as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @inlinable - @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: UnsafeMutableBufferPointer - ) { - unsafe self.replaceSubrange( - subrange, copying: UnsafeBufferPointer(newElements)) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given span. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same location. - /// The number of new elements need not match the number of elements being - /// removed. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length span as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @available(SwiftStdlib 6.2, *) - @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: Span - ) { - // FIXME: Avoiding moving the subsequent elements twice. - _ensureFreeCapacity(newElements.count) - _storage.replaceSubrange(subrange, copying: newElements) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given collection. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting the new elements starting at the same location. - /// The number of new elements need not match the number of elements being - /// removed. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(copying:at:)` method instead is preferred in this case. - /// - /// Likewise, if you pass a zero-length collection as the `newElements` - /// parameter, this method removes the elements in the given subrange - /// without replacement. Calling the `removeSubrange(_:)` method instead is - /// preferred in this case. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newElements: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this array and - /// *m* is the count of `newElements`. - @inlinable - @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, - copying newElements: __owned some Collection - ) { - // FIXME: Avoiding moving the subsequent elements twice. - let c = newElements.count - _ensureFreeCapacity(c) - _storage._replaceSubrange( - subrange, copyingCollection: newElements, newCount: c) - } -} #endif diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb index 29553931..2bed0319 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb +++ b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift.gyb @@ -123,48 +123,13 @@ extension UnsafeMutableBufferPointer { /// The `source` span must fit entirely in `self`. /// /// - Returns: The index after the last item that was initialized in this buffer. - @available(SwiftStdlib 6.2, *) + @available(SwiftStdlib 5.0, *) @inlinable ${modifier} func _initializePrefix(copying source: Span) -> Int { source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } } #endif -#if compiler(>=6.2) && FIXME - /// Initialize all slots in this buffer by copying data from `items`, which must fit entirely - /// in this buffer. - /// - /// If `items` contains more elements than can fit into this buffer, then this function - /// will return an index other than `items.endIndex`. In that case, `self` may not be fully - /// populated. - /// - /// If `Element` is not bitwise copyable, then this function must be called on an - /// entirely uninitialized buffer. - /// - /// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were - /// successfully initialized, and `end` is the index into `items` after the last copied item. - @available(SwiftStdlib 6.2, *) - @inlinable - ${modifier} func _initializePrefix< - C: Container & ~Copyable & ~Escapable - >( - copying items: borrowing C - ) -> (copied: Int, end: C.Index) { - var target = self - var i = items.startIndex - while true { - let start = i - let span = items.span(after: &i) - if span.isEmpty { break } - guard span.count <= target.count else { - return (self.count - target.count, start) - } - target._initializeAndDropPrefix(copying: span) - } - return (self.count - target.count, i) - } -#endif - /// Initialize slots at the start of this buffer by copying data from `buffer`, then /// shrink `self` to drop all initialized items from its front, leaving it addressing the /// uninitialized remainder. @@ -269,13 +234,17 @@ extension UnsafeMutableBufferPointer { let i = self.initialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer where Element: ~Copyable { @inlinable @inline(__always) ${modifier} func moveInitializeAll(fromContentsOf source: Self) { let i = self.moveInitialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer { @inlinable @inline(__always) ${modifier} func moveInitializeAll(fromContentsOf source: Slice) { let i = self.moveInitialize(fromContentsOf: source) diff --git a/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift index 568b9fed..7abcc67e 100644 --- a/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/autogenerated/UnsafeMutableBufferPointer+Extras.swift @@ -129,48 +129,13 @@ extension UnsafeMutableBufferPointer { /// The `source` span must fit entirely in `self`. /// /// - Returns: The index after the last item that was initialized in this buffer. - @available(SwiftStdlib 6.2, *) + @available(SwiftStdlib 5.0, *) @inlinable internal func _initializePrefix(copying source: Span) -> Int { source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } } #endif -#if compiler(>=6.2) && FIXME - /// Initialize all slots in this buffer by copying data from `items`, which must fit entirely - /// in this buffer. - /// - /// If `items` contains more elements than can fit into this buffer, then this function - /// will return an index other than `items.endIndex`. In that case, `self` may not be fully - /// populated. - /// - /// If `Element` is not bitwise copyable, then this function must be called on an - /// entirely uninitialized buffer. - /// - /// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were - /// successfully initialized, and `end` is the index into `items` after the last copied item. - @available(SwiftStdlib 6.2, *) - @inlinable - internal func _initializePrefix< - C: Container & ~Copyable & ~Escapable - >( - copying items: borrowing C - ) -> (copied: Int, end: C.Index) { - var target = self - var i = items.startIndex - while true { - let start = i - let span = items.span(after: &i) - if span.isEmpty { break } - guard span.count <= target.count else { - return (self.count - target.count, start) - } - target._initializeAndDropPrefix(copying: span) - } - return (self.count - target.count, i) - } -#endif - /// Initialize slots at the start of this buffer by copying data from `buffer`, then /// shrink `self` to drop all initialized items from its front, leaving it addressing the /// uninitialized remainder. @@ -275,13 +240,17 @@ extension UnsafeMutableBufferPointer { let i = self.initialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer where Element: ~Copyable { @inlinable @inline(__always) internal func moveInitializeAll(fromContentsOf source: Self) { let i = self.moveInitialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer { @inlinable @inline(__always) internal func moveInitializeAll(fromContentsOf source: Slice) { let i = self.moveInitialize(fromContentsOf: source) @@ -438,48 +407,13 @@ extension UnsafeMutableBufferPointer { /// The `source` span must fit entirely in `self`. /// /// - Returns: The index after the last item that was initialized in this buffer. - @available(SwiftStdlib 6.2, *) + @available(SwiftStdlib 5.0, *) @inlinable public func _initializePrefix(copying source: Span) -> Int { source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } } #endif -#if compiler(>=6.2) && FIXME - /// Initialize all slots in this buffer by copying data from `items`, which must fit entirely - /// in this buffer. - /// - /// If `items` contains more elements than can fit into this buffer, then this function - /// will return an index other than `items.endIndex`. In that case, `self` may not be fully - /// populated. - /// - /// If `Element` is not bitwise copyable, then this function must be called on an - /// entirely uninitialized buffer. - /// - /// - Returns: A pair of values `(count, end)`, where `count` is the number of items that were - /// successfully initialized, and `end` is the index into `items` after the last copied item. - @available(SwiftStdlib 6.2, *) - @inlinable - public func _initializePrefix< - C: Container & ~Copyable & ~Escapable - >( - copying items: borrowing C - ) -> (copied: Int, end: C.Index) { - var target = self - var i = items.startIndex - while true { - let start = i - let span = items.span(after: &i) - if span.isEmpty { break } - guard span.count <= target.count else { - return (self.count - target.count, start) - } - target._initializeAndDropPrefix(copying: span) - } - return (self.count - target.count, i) - } -#endif - /// Initialize slots at the start of this buffer by copying data from `buffer`, then /// shrink `self` to drop all initialized items from its front, leaving it addressing the /// uninitialized remainder. @@ -584,13 +518,17 @@ extension UnsafeMutableBufferPointer { let i = self.initialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer where Element: ~Copyable { @inlinable @inline(__always) public func moveInitializeAll(fromContentsOf source: Self) { let i = self.moveInitialize(fromContentsOf: source) assert(i == self.endIndex) } +} +extension UnsafeMutableBufferPointer { @inlinable @inline(__always) public func moveInitializeAll(fromContentsOf source: Slice) { let i = self.moveInitialize(fromContentsOf: source) diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index 9b86c1ad..935de351 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -303,7 +303,7 @@ class RigidArrayTests: CollectionTestCase { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // TODO func test_borrowElement() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -334,8 +334,8 @@ class RigidArrayTests: CollectionTestCase { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - func test_mutateElement() { +#if false // TODO + func test_mutateElement2() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in var a = tracker.rigidArray(layout: layout) @@ -555,7 +555,7 @@ class RigidArrayTests: CollectionTestCase { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // TODO func test_removeAll_where() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -735,8 +735,10 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) let rigidAddition = StaccatoContainer( - contents: RigidArray(count: addition.count) { - tracker.instance(for: addition[$0]) + contents: RigidArray(capacity: addition.count) { + for item in addition { + $0.append(tracker.instance(for: item)) + } }, spanCounts: [Swift.max(spanCount, 1)]) a.insert(copying: rigidAddition, at: i) diff --git a/Tests/BasicContainersTests/UniqueArrayTests.swift b/Tests/BasicContainersTests/UniqueArrayTests.swift index 4096997b..3eaf7488 100644 --- a/Tests/BasicContainersTests/UniqueArrayTests.swift +++ b/Tests/BasicContainersTests/UniqueArrayTests.swift @@ -323,7 +323,7 @@ class UniqueArrayTests: CollectionTestCase { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // TODO func test_borrowElement() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -337,7 +337,7 @@ class UniqueArrayTests: CollectionTestCase { } #endif -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // TODO func test_mutateElement() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -538,7 +538,7 @@ class UniqueArrayTests: CollectionTestCase { } } -#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW +#if false // TODO func test_removeAll_where() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -785,8 +785,10 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) let rigidAddition = StaccatoContainer( - contents: RigidArray(count: addition.count) { - tracker.instance(for: addition[$0]) + contents: RigidArray(capacity: addition.count) { + for item in addition { + $0.append(tracker.instance(for: item)) + } }, spanCounts: [spanCount]) a.insert(copying: rigidAddition, at: i)