diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift index 91501f24..8ed3b386 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift @@ -78,13 +78,14 @@ extension RigidArray where Element: ~Copyable { /// is allowed to initialize fewer than `newItemCount` items. /// The array is appended however many items the callback adds to /// the output span before it returns (or before it throws an error). - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`newItemCount`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { + ) throws(E) -> Range { precondition(newItemCount >= 0, "Cannot add a negative number of items") precondition(freeCapacity >= newItemCount, "RigidArray capacity overflow") let buffer = _freeSpace._extracting(first: newItemCount) @@ -93,7 +94,8 @@ extension RigidArray where Element: ~Copyable { _count &+= span.finalize(for: buffer) span = OutputSpan() } - return try initializer(&span) + try initializer(&span) + return Range(uncheckedBounds: (count, count &+ span.count)) } } @@ -103,11 +105,15 @@ extension RigidArray where Element: ~Copyable { @unsafe internal mutating func _appendUnchecked( moving items: UnsafeMutableBufferPointer - ) { - guard items.count > 0 else { return } + ) -> Range { + guard items.count > 0 else { + return Range(uncheckedBounds: (_count, _count)) + } let c = unsafe _freeSpace._moveInitializePrefix(from: items) assert(c == items.count) + let origCount = _count _count &+= items.count + return Range(uncheckedBounds: (origCount, _count)) } /// Moves the elements of a buffer to the end of this array, leaving the @@ -119,14 +125,15 @@ extension RigidArray where Element: ~Copyable { /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: UnsafeMutableBufferPointer - ) { + ) -> Range { precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - unsafe _appendUnchecked(moving: items) + return unsafe _appendUnchecked(moving: items) } #if UnstableContainersPreview @@ -138,17 +145,18 @@ extension RigidArray where Element: ~Copyable { /// /// - Parameters: /// - items: An input span whose contents need to be appended to this array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: inout InputSpan - ) { + ) -> Range { // FIXME: Remove this when `InputSpan` starts conforming to RangeReplaceableContainer items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.append(moving: source) count = 0 + return unsafe self.append(moving: source) } } #endif @@ -161,18 +169,19 @@ extension RigidArray where Element: ~Copyable { /// /// - Parameters: /// - items: An output span whose contents need to be appended to this array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: inout OutputSpan - ) { + ) -> Range { // FIXME: Remove this when `OutputSpan` starts conforming to RangeReplaceableContainer precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - items.withUnsafeMutableBufferPointer { buffer, count in + return items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe _appendUnchecked(moving: source) count = 0 + return unsafe _appendUnchecked(moving: source) } } @@ -185,12 +194,12 @@ extension RigidArray where Element: ~Copyable { /// /// - Parameters: /// - items: An array whose items to move to the end of this array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient public mutating func append( moving items: inout RigidArray - ) { + ) -> Range { // FIXME: Remove this; RangeReplaceableContainer provides a more general algorithm items.edit { span in self.append(moving: &span) @@ -204,11 +213,15 @@ extension RigidArray { @unsafe internal mutating func _appendUnchecked( copying newElements: UnsafeBufferPointer - ) { - guard newElements.count > 0 else { return } + ) -> Range { + guard newElements.count > 0 else { + return Range(uncheckedBounds: (_count, _count)) + } unsafe _freeSpace.baseAddress.unsafelyUnwrapped.initialize( from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count) + let origCount = _count _count &+= newElements.count + return Range(uncheckedBounds: (origCount, _count)) } /// Copies the elements of a buffer to the end of this array. @@ -219,16 +232,17 @@ extension RigidArray { /// - Parameters: /// - newElements: A fully initialized buffer whose contents to copy into /// the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`newElements.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( copying newElements: UnsafeBufferPointer - ) { + ) -> Range { precondition( newElements.count <= freeCapacity, "RigidArray capacity overflow") - unsafe _appendUnchecked(copying: newElements) + return unsafe _appendUnchecked(copying: newElements) } /// Copies the elements of a buffer to the end of this array. @@ -239,12 +253,13 @@ extension RigidArray { /// - Parameters: /// - items: A fully initialized buffer whose contents to copy into /// the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( copying items: UnsafeMutableBufferPointer - ) { + ) -> Range { unsafe self.append(copying: UnsafeBufferPointer(items)) } @@ -255,12 +270,13 @@ extension RigidArray { /// /// - Parameters: /// - items: A span whose contents to copy into the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient - public mutating func append(copying items: Span) { + @discardableResult + public mutating func append(copying items: Span) -> Range { precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - items.withUnsafeBufferPointer { source in + return items.withUnsafeBufferPointer { source in unsafe _appendUnchecked(copying: source) } } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift index 89c0d8b3..54ba8264 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift @@ -40,18 +40,20 @@ extension RigidArray where Element: ~Copyable { /// The function is not required to consume all items in the span; /// however, the span's remaining items will still be removed from /// the array. - /// + /// - Returns: A valid index addressing the position following the consumed + /// range. /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient - public mutating func consume( + @discardableResult + public mutating func consumeSubrange( _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void - ) { + ) -> Index { _checkValidBounds(subrange) guard !subrange.isEmpty else { var span = InputSpan() consumer(&span) - return + return subrange.lowerBound } let buffer = unsafe _storage.extracting(subrange) var span = InputSpan(buffer: buffer, initializedCount: buffer.count) @@ -61,6 +63,7 @@ extension RigidArray where Element: ~Copyable { _closeGap(at: subrange.lowerBound, count: subrange.count) _count -= subrange.count + return subrange.lowerBound } /// Remove the specified subrange of items from this deque, @@ -78,17 +81,19 @@ extension RigidArray where Element: ~Copyable { /// - Parameter consumer: A function taking an input span of the removed items, /// allowing them to be consumed straight out of the array's storage. /// The function is called at most once. - /// + /// - Returns: A valid index addressing the upper bound of the consumed + /// range in the resulting array. /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient @inline(__always) - public mutating func consume>( + @discardableResult + public mutating func consumeSubrange>( _ subrange: R, consumingWith consumer: (inout InputSpan) -> Void - ) { - consume(subrange.relative(to: indices), consumingWith: consumer) + ) -> Int { + consumeSubrange(subrange.relative(to: indices), consumingWith: consumer) } - + /// Remove all items currently in this array, passing an input /// span to a given callback function to consume them in place. /// @@ -105,7 +110,7 @@ extension RigidArray where Element: ~Copyable { public mutating func consumeAll( consumingWith consumer: (inout InputSpan) -> Void ) { - consume(indices, consumingWith: consumer) + self.consumeSubrange(self.indices, consumingWith: consumer) } /// Remove the specified number of items from the end of this array, @@ -132,7 +137,7 @@ extension RigidArray where Element: ~Copyable { precondition( n >= 0 && n <= _count, "Count of elements to consume is out of bounds") - self.consume(_count &- n ..< _count, consumingWith: consumer) + self.consumeSubrange(_count &- n ..< _count, consumingWith: consumer) } } #endif @@ -141,9 +146,11 @@ extension RigidArray where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @_alwaysEmitIntoClient - @inline(__always) + @inline(always) @_lifetime(&self) - public mutating func consume(_ subrange: Range) -> SubrangeConsumer { + public mutating func consumeSubrange( + _ subrange: Range + ) -> SubrangeConsumer { SubrangeConsumer(_base: &self, offsetRange: subrange) } } @@ -192,6 +199,8 @@ extension RigidArray where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidArray.SubrangeConsumer where Element: ~Copyable { + public typealias Index = Int + @inlinable public var count: Int { _remainder.count @@ -209,6 +218,11 @@ extension RigidArray.SubrangeConsumer where Element: ~Copyable { InputSpan(buffer: buffer, initializedCount: buffer.count), mutating: &self) } + + @inlinable + public consuming func finalize() -> Index { + _offsetRange.lowerBound + } } #endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift index 3719fbbe..79c3bb46 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift @@ -127,184 +127,6 @@ extension RigidArray where Element: ~Copyable { public mutating func reallocate(capacity newCapacity: Int) { setCapacity(newCapacity) } - - /// Replaces the specified range of elements by a given count of new items, - /// using a callback to directly initialize array storage by populating - /// an output span. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting room for 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, then - /// this method is equivalent to calling - /// `insert(count: newCount, at: subrange.lowerbound, initializingWith: body)`. - /// - /// Likewise, if you pass a zero for `newCount`, then this method - /// removes the elements in the given subrange without any replacement. - /// This case is more directly expressed by `removeSubrange(subrange)`. - /// - /// - Parameters: - /// - subrange: The subrange of the array to replace. The bounds of - /// the range must be valid indices in the array. - /// - newCount: the number of items to replace the old subrange. - /// - body: A callback that gets called exactly once to directly - /// populate newly reserved storage within the array. The function - /// is called with an empty output span of capacity `newCount`, - /// and it must fully populate it before returning. - /// - /// - Complexity: O(`self.count` + `newCount`) - @available(*, deprecated, renamed: "replace(removing:addingCount:initializingWith:)") - @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - newCount: Int, - initializingWith body: (inout OutputSpan) -> Result - ) -> Result { - var result: Result? = nil - self.replace(removing: subrange, addingCount: newCount) { target in - result = body(&target) - } - return result! - } - - /// 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(moving: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`) - @available(*, deprecated, renamed: "replace(removing:moving:)") - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - moving newElements: UnsafeMutableBufferPointer, - ) { - replace(removing: subrange, moving: newElements) - } - - /// Replaces the specified range of elements by moving the contents of an - /// output span into their place. On return, the span is left empty. - /// - /// 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(moving: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. - /// - items: An output span whose contents are to be moved into the array. - /// - /// - Complexity: O(`self.count` + `items.count`) - @available(*, deprecated, renamed: "replace(removing:moving:)") - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - moving items: inout OutputSpan - ) { - replace(removing: 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 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`) - @available(*, deprecated, renamed: "replace(removing:moving:)") - @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, - moving newElements: inout RigidArray, - ) { - self.replace(removing: subrange, moving: &newElements) - } - - - /// Perform a range replacement up to populating the newly opened gap. This - /// deinitializes existing elements in the specified subrange, rearranges - /// following elements to be at their final location, and sets the container's - /// new count. - /// - /// - Returns: A buffer pointer addressing the newly opened gap, to be - /// initialized by the caller. - @available(*, deprecated) // FIXME: Obsolete, remove this - @usableFromInline - @unsafe - internal mutating func _gapForReplacement( - of subrange: Range, newItemCount: Int - ) -> UnsafeMutableBufferPointer { - precondition( - subrange.lowerBound >= 0 && subrange.upperBound <= _count, - "Index range out of bounds") - precondition(newItemCount >= 0, "Cannot add a negative number of items") - precondition( - newItemCount - subrange.count <= freeCapacity, - "RigidArray capacity overflow") - unsafe _items.extracting(subrange).deinitialize() - return _resizeGap(in: subrange, to: newItemCount) - } } @available(SwiftStdlib 5.0, *) @@ -332,160 +154,91 @@ extension RigidArray { public func copy(capacity: Int) -> Self { clone(capacity: capacity) } - - /// 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`) - @available(*, deprecated, renamed: "replace(removing:copying:)") + + @available(*, deprecated, renamed: "replaceSubrange(_:addingCount:initializingWith:)") @inlinable - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + try replaceSubrange( + subrange, addingCount: newItemCount, initializingWith: initializer) + } + + @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + moving newElements: UnsafeMutableBufferPointer, + ) { + replaceSubrange(subrange, moving: newElements) + } + + @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + moving items: inout OutputSpan + ) { + replaceSubrange(subrange, moving: &items) + } + + @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + moving newElements: inout RigidArray, + ) { + replaceSubrange(subrange, moving: &newElements) + } + + @available(*, deprecated, renamed: "replaceSubrange(_:consuming:)") + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + consuming newElements: consuming RigidArray, + ) { + replaceSubrange(subrange, moving: &newElements) + } + + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") + @inlinable + public mutating func replace( + removing subrange: Range, copying newElements: UnsafeBufferPointer ) { - self.replace(removing: subrange, copying: newElements) + 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 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`) - @available(*, deprecated, renamed: "replace(removing:copying:)") + + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") @inlinable - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: UnsafeMutableBufferPointer ) { - self.replace(removing: subrange, copying: newElements) + replaceSubrange(subrange, copying: 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(*, deprecated, renamed: "replace(removing:copying:)") + + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") @inlinable - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: Span ) { - self.replace(removing: subrange, copying: newElements) + replaceSubrange(subrange, copying: newElements) } - - @available(*, unavailable) - @usableFromInline - internal mutating func _replaceSubrange( - _ subrange: Range, - copyingCollection newElements: __owned some Collection, - newCount: Int - ) { - self._replace( - removing: subrange, - copyingCollection: newElements, - newCount: newCount) - } - - /// 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`) - @available(*, deprecated, renamed: "replace(removing:copying:)") + + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") @inlinable @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: __owned some Collection ) { - self.replace(removing: subrange, copying: newElements) + replaceSubrange(subrange, copying: newElements) } + } #endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift index 8ccd0915..519cd165 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift @@ -160,8 +160,6 @@ extension RigidArray /*where Element: Copyable*/ { } #endif - // FIXME: Add a version that's generic over `Container`, with an optional capacity - /// Creates a new array with the specified capacity, holding a copy /// of the contents of a given collection. /// @@ -199,6 +197,4 @@ extension RigidArray /*where Element: Copyable*/ { } } -// FIXME: Add init(moving:), init(consuming:) - #endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift index ca004607..4ef074c9 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift @@ -35,10 +35,11 @@ extension RigidArray where Element: ~Copyable { /// - Parameter item: The new element to insert into the array. /// - Parameter index: The position at which to insert the new element. /// `index` must be a valid index in the array. - /// + /// - Returns: A valid index to the newly inserted item. /// - Complexity: O(`self.count`) @inlinable - public mutating func insert(_ item: consuming Element, at index: Int) { + @discardableResult + public mutating func insert(_ item: consuming Element, at index: Int) -> Int { _checkValidIndex(index) precondition(!isFull, "RigidArray capacity overflow") if index < count { @@ -49,6 +50,7 @@ extension RigidArray where Element: ~Copyable { } unsafe _storage.initializeElement(at: index, to: item) _count += 1 + return index } } @@ -91,16 +93,17 @@ extension RigidArray where Element: ~Copyable { /// - initializer: A callback that gets called at most once to directly /// populate newly reserved storage within the array. The function /// is always called with an empty output span. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity /// of the callback invocations. @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func insert( addingCount newItemCount: Int, at index: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { + ) throws(E) -> Range { _checkValidIndex(index) precondition(newItemCount >= 0, "Cannot add a negative number of items") precondition(newItemCount <= freeCapacity, "RigidArray capacity overflow") @@ -116,6 +119,7 @@ extension RigidArray where Element: ~Copyable { span = OutputSpan() } try initializer(&span) + return index ..< (index + span.count) } } @@ -136,13 +140,14 @@ extension RigidArray where Element: ~Copyable { /// the array. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: UnsafeMutableBufferPointer, at index: Int - ) { + ) -> Range { insert(addingCount: items.count, at: index) { target in target._append(moving: items) } @@ -163,18 +168,19 @@ extension RigidArray where Element: ~Copyable { /// the array. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: inout InputSpan, at index: Int - ) { + ) -> Range { // FIXME: Remove when InputSpan starts conforming to RangeReplaceableContainer items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.insert(moving: source, at: index) count = 0 + return unsafe self.insert(moving: source, at: index) } } #endif @@ -193,18 +199,19 @@ extension RigidArray where Element: ~Copyable { /// the array. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: inout OutputSpan, at index: Int - ) { + ) -> Range { // FIXME: Remove when OutputSpan starts conforming to RangeReplaceableContainer items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe self.insert(moving: source, at: index) count = 0 + return unsafe self.insert(moving: source, at: index) } } @@ -223,16 +230,20 @@ extension RigidArray where Element: ~Copyable { /// - items: An array whose contents to move into `self`. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: inout RigidArray, at index: Int - ) { + ) -> Range { // FIXME: Remove this in favor of a generic algorithm over consumable containers - guard !items.isEmpty else { return } - items.edit { source in + guard !items.isEmpty else { + _checkValidIndex(index) + return index ..< index + } + return items.edit { source in self.insert(moving: &source, at: index) } } @@ -258,14 +269,18 @@ extension RigidArray { /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `newElements.count`) @inlinable + @discardableResult public mutating func insert( copying newElements: UnsafeBufferPointer, at index: Int - ) { - guard newElements.count > 0 else { return } - self.insert(addingCount: newElements.count, at: index) { target in + ) -> Range { + guard newElements.count > 0 else { + _checkValidIndex(index) + return index ..< index + } + return self.insert(addingCount: newElements.count, at: index) { target in target._append(copying: newElements) } } @@ -288,14 +303,15 @@ extension RigidArray { /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `newElements.count`) @inlinable @inline(__always) + @discardableResult public mutating func insert( copying newElements: UnsafeMutableBufferPointer, at index: Int - ) { + ) -> Range { unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) } @@ -315,34 +331,39 @@ extension RigidArray { /// - 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `newElements.count`) @inlinable @inline(__always) + @discardableResult public mutating func insert( copying newElements: Span, at index: Int - ) { - guard newElements.count > 0 else { return } - self.insert(addingCount: newElements.count, at: index) { target in + ) -> Range { + guard newElements.count > 0 else { + _checkValidIndex(index) + return index ..< index + } + return self.insert(addingCount: newElements.count, at: index) { target in target._append(copying: newElements) } } @_alwaysEmitIntoClient + @discardableResult package mutating func _insertCollection( addingCount newCount: Int, copying items: some Collection, at index: Index - ) { + ) -> Range { // FIXME: Remove this -- RangeReplaceContainer already has this algorithm, // albeit with stricter availability. - let done: Void? = items.withContiguousStorageIfAvailable { buffer in + let res: Range? = items.withContiguousStorageIfAvailable { buffer in precondition(buffer.count == newCount, "Broken Collection: mismatching count") - self.insert(addingCount: buffer.count, at: index) { target in + return self.insert(addingCount: buffer.count, at: index) { target in target._append(copying: buffer) } } - if done != nil { return } + if let res { return res } var it = items.makeIterator() self.insert(addingCount: newCount, at: index) { target in while !target.isFull { @@ -351,6 +372,7 @@ extension RigidArray { } } precondition(it.next() == nil, "Broken Collection") + return index ..< (index + newCount) } /// Copies the elements of a collection into this array at the specified @@ -370,13 +392,14 @@ extension RigidArray { /// - items: 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `newElements.count`) @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func insert( copying items: some Collection, at index: Int - ) { + ) -> Range { _insertCollection(addingCount: items.count, copying: items, at: index) } } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift index f896a82a..59fa501c 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift @@ -19,6 +19,34 @@ import InternalCollectionsUtilities @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 element at the specified position. + /// + /// All the elements following the specified position are moved to close the + /// gap. + /// + /// - Parameter index: The position of the element to remove. `index` must be + /// a valid index of the array that is not equal to the end index. + /// On return, `index` is updated to address the position following the + /// removed element. + /// - Returns: The removed element. + /// + /// - Complexity: O(`count`) + @_alwaysEmitIntoClient + @inline(__always) + @discardableResult + public mutating func remove(at index: inout Int) -> Element { + remove(at: index) + } + /// Removes and returns the element at the specified position. /// /// All the elements following the specified position are moved to close the @@ -39,15 +67,6 @@ extension RigidArray where Element: ~Copyable { return old } - /// 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. @@ -93,27 +112,32 @@ extension RigidArray where Element: ~Copyable { /// resulting gap. /// /// - Parameter bounds: The subrange of the array to remove. The bounds - /// of the range must be valid indices of the array. - /// + /// of the range must be valid indices of the array. + /// - Returns: A valid index addressing the position following the removed + /// subrange. /// - Complexity: O(`count`) @inlinable - public mutating func removeSubrange(_ bounds: Range) { + @discardableResult + public mutating func removeSubrange(_ bounds: Range) -> Int { _checkValidBounds(bounds) - guard !bounds.isEmpty else { return } + guard !bounds.isEmpty else { return bounds.lowerBound } unsafe _storage.extracting(bounds).deinitialize() _closeGap(at: bounds.lowerBound, count: bounds.count) _count -= bounds.count + return bounds.lowerBound } /// 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. - /// + /// - Returns: A valid index addressing the position following the removed + /// subrange. /// - Complexity: O(`count`) @_alwaysEmitIntoClient - public mutating func removeSubrange(_ bounds: some RangeExpression) { - // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm. + @discardableResult + public mutating func removeSubrange(_ bounds: some RangeExpression) -> Int { + // FIXME: Remove this in favor of the DrainableContainer algorithm. removeSubrange(bounds.relative(to: indices)) } } @@ -128,7 +152,7 @@ extension RigidArray where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient public mutating func popLast() -> Element? { - // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm. + // FIXME: Remove this in favor of the DrainableContainer algorithm. if isEmpty { return nil } return removeLast() } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift index 8048f2e1..4b91f35d 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift @@ -57,32 +57,31 @@ extension RigidArray where Element: ~Copyable { /// - initializer: A callback that gets called at most once to directly /// populate newly reserved storage within the array. The function /// is always called with an empty output span. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity /// of the callback invocations. @inlinable - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { _checkValidBounds(subrange) precondition(newItemCount >= 0, "Cannot add a negative number of items") precondition( newItemCount - subrange.count <= freeCapacity, "RigidArray capacity overflow") - try _uncheckedReplace( - removing: subrange, - addingCount: newItemCount, - initializingWith: initializer) + return try _uncheckedReplaceSubrange( + subrange, addingCount: newItemCount, initializingWith: initializer) } @_alwaysEmitIntoClient - internal mutating func _uncheckedReplace( - removing subrange: Range, + internal mutating func _uncheckedReplaceSubrange( + _ subrange: Range, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { // Destroy removed items unsafe _items.extracting(subrange).deinitialize() let target = _resizeGap(in: subrange, to: newItemCount) @@ -98,6 +97,8 @@ extension RigidArray where Element: ~Copyable { span = OutputSpan() } try initializer(&span) + return Range(uncheckedBounds: ( + subrange.lowerBound, subrange.lowerBound + newItemCount)) } } @@ -148,35 +149,36 @@ extension RigidArray where Element: ~Copyable { /// - initializer: A callback that gets called at most once to directly /// populate newly reserved storage within the deque. The function /// is always called with an empty output span. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newItemCount`) in addition to the /// complexity of the callback invocations. @inlinable - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { _checkValidBounds(subrange) precondition(newItemCount >= 0, "Cannot add a negative number of items") precondition( newItemCount - subrange.count <= freeCapacity, "RigidArray capacity overflow") - try _uncheckedReplace( - removing: subrange, + return try _uncheckedReplaceSubrange( + subrange, consumingWith: consumer, addingCount: newItemCount, initializingWith: initializer) } @_alwaysEmitIntoClient - internal mutating func _uncheckedReplace( - removing subrange: Range, + internal mutating func _uncheckedReplaceSubrange( + _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) ->Range { do { // Consume items to be removed let buffer = unsafe _storage.extracting(subrange) @@ -200,6 +202,8 @@ extension RigidArray where Element: ~Copyable { } try initializer(&span) } + return Range(uncheckedBounds: ( + subrange.lowerBound, subrange.lowerBound + newItemCount)) } #endif } @@ -233,14 +237,15 @@ extension RigidArray where Element: ~Copyable { /// the range must be valid indices in the array. /// - newElements: A fully initialized buffer whose contents to move into /// the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving newElements: UnsafeMutableBufferPointer, - ) { - replace(removing: subrange, addingCount: newElements.count) { target in + ) -> Range { + replaceSubrange(subrange, addingCount: newElements.count) { target in target.withUnsafeMutableBufferPointer { buffer, count in count = unsafe buffer._moveInitializePrefix(from: newElements) } @@ -272,17 +277,18 @@ extension RigidArray where Element: ~Copyable { /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - items: An input span whose contents are to be moved into the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving items: inout InputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.replace(removing: subrange, moving: source) count = 0 + return unsafe self.replaceSubrange(subrange, moving: source) } } #endif @@ -311,17 +317,18 @@ extension RigidArray where Element: ~Copyable { /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - items: An output span whose contents are to be moved into the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving items: inout OutputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe self.replace(removing: subrange, moving: source) count = 0 + return unsafe self.replaceSubrange(subrange, moving: source) } } @@ -351,18 +358,19 @@ extension RigidArray where Element: ~Copyable { /// - 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`. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving newElements: inout RigidArray, - ) { - // FIXME: Remove this in favor of a generic algorithm over consumable containers + ) -> Range { + // FIXME: Remove this in favor of the generic algorithm over DrainableContainer unsafe newElements._unsafeEdit { buffer, count in let source = buffer._extracting(first: count) - unsafe self.replace(removing: subrange, moving: source) count = 0 + return unsafe self.replaceSubrange(subrange, moving: source) } } } @@ -393,15 +401,16 @@ extension RigidArray where Element: ~Copyable { /// - 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`. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, consuming newElements: consuming RigidArray, - ) { - // FIXME: Remove this in favor of the generic algorithm over drainable containers - replace(removing: subrange, moving: &newElements) + ) -> Range { + // FIXME: Remove this in favor of the generic algorithm over DrainableContainer + replaceSubrange(subrange, moving: &newElements) } } @@ -431,14 +440,15 @@ extension RigidArray { /// - 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying newElements: UnsafeBufferPointer - ) { - replace(removing: subrange, addingCount: newElements.count) { target in + ) -> Range { + replaceSubrange(subrange, addingCount: newElements.count) { target in target.withUnsafeMutableBufferPointer { buffer, count in count = unsafe buffer._initializePrefix(copying: newElements) } @@ -469,15 +479,16 @@ extension RigidArray { /// - 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying newElements: UnsafeMutableBufferPointer - ) { - unsafe self.replace( - removing: subrange, + ) -> Range { + unsafe self.replaceSubrange( + subrange, copying: UnsafeBufferPointer(newElements)) } @@ -505,25 +516,26 @@ extension RigidArray { /// - 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying newElements: Span - ) { + ) -> Range { newElements.withUnsafeBufferPointer { buffer in - unsafe self.replace(removing: subrange, copying: buffer) + unsafe self.replaceSubrange(subrange, copying: buffer) } } @inlinable - internal mutating func _replace( - removing subrange: Range, + internal mutating func _replaceSubrange( + _ subrange: Range, copyingCollection newElements: __owned some Collection, newCount: Int - ) { - self.replace(removing: subrange, addingCount: newCount) { target in + ) -> Range { + self.replaceSubrange(subrange, addingCount: newCount) { target in target.withUnsafeMutableBufferPointer { dst, dstCount in let done: Void? = newElements.withContiguousStorageIfAvailable { src in let i = unsafe dst._initializePrefix(copying: src) @@ -568,16 +580,17 @@ extension RigidArray { /// - 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) - @inlinable + @_alwaysEmitIntoClient @inline(__always) - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying newElements: __owned some Collection - ) { - _replace( - removing: subrange, + ) -> Range { + _replaceSubrange( + subrange, copyingCollection: newElements, newCount: newElements.count) } diff --git a/Sources/BasicContainers/RigidArray/RigidArray.swift b/Sources/BasicContainers/RigidArray/RigidArray.swift index 769b10b5..0e391213 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray.swift @@ -367,9 +367,10 @@ extension RigidArray where Element: ~Copyable { /// - Complexity: O(`count`) @inlinable public mutating func setCapacity(_ newCapacity: Int) { + let newCapacity = Swift.max(newCapacity, count) guard newCapacity != capacity else { return } let newStorage: UnsafeMutableBufferPointer = .allocate( - capacity: Swift.max(newCapacity, count)) + capacity: newCapacity) let i = unsafe newStorage.moveInitialize(fromContentsOf: self._items) assert(i == count) diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift index ace2e7e5..015ee2f1 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift @@ -56,13 +56,14 @@ extension UniqueArray where Element: ~Copyable { /// is allowed to initialize fewer than `uninitializedCount` items. /// The array is appended however many items the callback adds to the /// output span before it returns (or before it throws an error). - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`uninitializedCount`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { + ) throws(E) -> Range { _ensureFreeCapacity(newItemCount) return try _storage.append( addingCount: newItemCount, @@ -82,14 +83,15 @@ extension UniqueArray where Element: ~Copyable { /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: UnsafeMutableBufferPointer - ) { + ) -> Range { _ensureFreeCapacity(items.count) - _storage._appendUnchecked(moving: items) + return _storage._appendUnchecked(moving: items) } #if UnstableContainersPreview @@ -102,14 +104,15 @@ extension UniqueArray where Element: ~Copyable { /// /// - Parameters: /// - items: An input span whose contents need to be appended to this array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: inout InputSpan - ) { + ) -> Range { _ensureFreeCapacity(items.count) - _storage.append(moving: &items) + return _storage.append(moving: &items) } #endif @@ -122,17 +125,18 @@ extension UniqueArray where Element: ~Copyable { /// /// - Parameters: /// - items: An output span whose contents need to be appended to this array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: inout OutputSpan - ) { + ) -> Range { _ensureFreeCapacity(items.count) - items.withUnsafeMutableBufferPointer { buffer, count in + return items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe _storage._appendUnchecked(moving: source) count = 0 + return unsafe _storage._appendUnchecked(moving: source) } } @@ -146,19 +150,20 @@ extension UniqueArray where Element: ~Copyable { /// /// - Parameters: /// - items: An array whose items to move to the end of this array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many invocations on /// the same array @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: inout RigidArray - ) { + ) -> Range { // FIXME: Remove in favor of the generic RRC algorithm _ensureFreeCapacity(items.count) - items.edit { source in + return items.edit { source in source.withUnsafeMutableBufferPointer { buffer, count in - _storage.append(moving: buffer._extracting(first: count)) count = 0 + return _storage.append(moving: buffer._extracting(first: count)) } } } @@ -175,15 +180,16 @@ extension UniqueArray { /// - Parameters: /// - newElements: A fully initialized buffer whose contents to copy into /// the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`newElements.count`) when amortized over many /// invocations on the same array. @_alwaysEmitIntoClient + @discardableResult public mutating func append( copying newElements: UnsafeBufferPointer - ) { + ) -> Range { _ensureFreeCapacity(newElements.count) - unsafe _storage._appendUnchecked(copying: newElements) + return unsafe _storage._appendUnchecked(copying: newElements) } /// Copies the elements of a buffer to the end of this array. @@ -195,13 +201,14 @@ extension UniqueArray { /// - Parameters: /// - newElements: A fully initialized buffer whose contents to copy into /// the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`newElements.count`) when amortized over many /// invocations on the same array. @_alwaysEmitIntoClient + @discardableResult public mutating func append( copying newElements: UnsafeMutableBufferPointer - ) { + ) -> Range { unsafe self.append(copying: UnsafeBufferPointer(newElements)) } @@ -213,13 +220,14 @@ extension UniqueArray { /// /// - Parameters: /// - newElements: A span whose contents to copy into the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`newElements.count`) when amortized over many /// invocations on the same array. @_alwaysEmitIntoClient - public mutating func append(copying newElements: Span) { + @discardableResult + public mutating func append(copying newElements: Span) -> Range { _ensureFreeCapacity(newElements.count) - newElements.withUnsafeBufferPointer { source in + return newElements.withUnsafeBufferPointer { source in unsafe _storage._appendUnchecked(copying: source) } } @@ -240,7 +248,7 @@ extension UniqueArray { if span.isEmpty { break } _ensureFreeCapacity(span.count) span.withUnsafeBufferPointer { source in - unsafe _storage._appendUnchecked(copying: source) + _ = unsafe _storage._appendUnchecked(copying: source) } } } @@ -258,7 +266,6 @@ extension UniqueArray { /// /// - 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.4, *) @@ -285,14 +292,13 @@ extension UniqueArray { /// /// - 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._appendUnchecked(copying: buffer) + _ = unsafe _storage._appendUnchecked(copying: buffer) return } if done != nil { return } @@ -313,7 +319,6 @@ extension UniqueArray { /// /// - 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.4, *) diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift index 5ff9ec51..5d17eb6a 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift @@ -21,11 +21,6 @@ import SpanPreview #if UnstableContainersPreview @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - @_lifetime(&self) - public mutating func _consumeAll() -> InputSpan { - _storage._consumeAll() - } - /// Remove the specified subrange of items from this array, /// passing an input span to the given function to consume them in place. /// @@ -35,14 +30,16 @@ extension UniqueArray where Element: ~Copyable { /// The function is not required to consume all items in the span; /// however, the span's remaining items will still be removed from /// the array. - /// + /// - Returns: A valid index addressing the position following the consumed + /// range in the resulting array. /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient - public mutating func consume( + @discardableResult + public mutating func consumeSubrange( _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void - ) { - _storage.consume(subrange, consumingWith: consumer) + ) -> Index { + _storage.consumeSubrange(subrange, consumingWith: consumer) } /// Remove the specified subrange of items from this deque, @@ -60,15 +57,18 @@ extension UniqueArray where Element: ~Copyable { /// - Parameter consumer: A function taking an input span of the removed items, /// allowing them to be consumed straight out of the array's storage. /// The function is called at most once. - /// + /// - Returns: A valid index addressing the position following the consumed + /// range in the resulting array. /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient @inline(__always) - public mutating func consume>( + @discardableResult + public mutating func consumeSubrange>( _ subrange: R, consumingWith consumer: (inout InputSpan) -> Void - ) { - _storage.consume(subrange.relative(to: indices), consumingWith: consumer) + ) -> Index { + _storage.consumeSubrange( + subrange.relative(to: indices), consumingWith: consumer) } /// Remove all items currently in this array, passing an input @@ -81,13 +81,12 @@ extension UniqueArray where Element: ~Copyable { /// - Parameter consumer: A function taking an input span of the removed items, /// allowing them to be consumed straight out of the array's storage. /// The function is called at most once. - /// /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient public mutating func consumeAll( consumingWith consumer: (inout InputSpan) -> Void ) { - _storage.consume(indices, consumingWith: consumer) + _storage.consumeSubrange(indices, consumingWith: consumer) } /// Remove the specified number of items from the end of this array, @@ -124,7 +123,7 @@ extension UniqueArray where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) @_lifetime(&self) - public mutating func consume(_ subrange: Range) -> SubrangeConsumer { + public mutating func consumeSubrange(_ subrange: Range) -> SubrangeConsumer { SubrangeConsumer(_base: &self._storage, offsetRange: subrange) } } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift index ee90a15f..20e28695 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift @@ -11,6 +11,10 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import SpanPreview +#endif + #if compiler(>=6.2) @available(SwiftStdlib 5.0, *) @@ -55,6 +59,17 @@ extension UniqueArray where Element: ~Copyable { self.init(minimumCapacity: capacity) } + @available(*, deprecated) + @inlinable + @inline(__always) + public mutating func removeAll(keepingCapacity keepCapacity: Bool) { + if keepCapacity { + _storage.removeAll() + } else { + _storage = RigidArray(capacity: 0) + } + } + /// Append a given number of items to the end of this array by populating /// an output span. /// @@ -137,198 +152,81 @@ extension UniqueArray where Element: ~Copyable { _storage.reallocate(capacity: capacity) } - /// Replaces the specified range of elements by a given count of new items, - /// using a callback to directly initialize array storage by populating - /// an output span. - /// - /// This method has the effect of removing the specified range of elements - /// from the array and inserting room for 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 perform the replacement, - /// then this reallocates storage to extend its capacity, using a geometric - /// growth rate. - /// - /// If you pass a zero-length range as the `subrange` parameter, then - /// this method is equivalent to calling - /// `insert(count: newCount, initializingWith: body)`. - /// - /// Likewise, if you pass a zero for `newCount`, then this method - /// removes the elements in the given subrange without any replacement. - /// Calling `removeSubrange(subrange)` 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. - /// - newCount: the number of items to replace the old subrange. - /// - body: A callback that gets called exactly once to directly - /// populate newly reserved storage within the array. The function - /// is called with an empty output span of capacity `newCount`, - /// and it must fully populate it before returning. - /// - /// - Complexity: O(`self.count` + `newCount`) - @available(*, deprecated, renamed: "replace(removing:addingCount:initializingWith:)") + @available(*, deprecated, renamed: "replaceSubrange(_:addingCount:initializingWith:)") @inlinable - public mutating func replaceSubrange( - _ subrange: Range, - newCount: Int, - initializingWith body: (inout OutputSpan) -> Result - ) -> Result { - var result: Result? = nil - self.replace(removing: subrange, addingCount: newCount) { target in - result = body(&target) - } - return result! + public mutating func replace( + removing subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + try replaceSubrange( + subrange, addingCount: newItemCount, initializingWith: initializer) } - /// 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 perform the replacement, - /// then this reallocates the array's storage to extend its capacity, using a - /// geometric growth rate. - /// - /// 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`) - @available(*, deprecated, renamed: "replace(removing:moving:)") +#if UnstableContainersPreview + @available(*, deprecated, renamed: "replaceSubrange(_:consumingWith:addingCount:initializingWith:)") + @inlinable + public mutating func replace( + removing subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + try replaceSubrange( + subrange, + consumingWith: consumer, + addingCount: newItemCount, + initializingWith: initializer) + } +#endif + + @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, moving newElements: UnsafeMutableBufferPointer, ) { - self.replace(removing: subrange, moving: newElements) + replaceSubrange(subrange, moving: newElements) } - - /// Replaces the specified range of elements by moving the contents of an - /// output span into their place. On return, the span is left empty. - /// - /// 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 perform the replacement, - /// then this reallocates the array's storage to extend its capacity, using a - /// geometric growth rate. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `newElements` at `subrange.lowerBound`. Calling - /// the `insert(moving: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. - /// - items: An output span whose contents are to be moved into the array. - /// - /// - Complexity: O(`self.count` + `items.count`) - @available(*, deprecated, renamed: "replace(removing:moving:)") + +#if UnstableContainersPreview + @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, + moving items: inout InputSpan + ) { + replaceSubrange(subrange, moving: &items) + } +#endif + + @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, moving items: inout OutputSpan ) { - self.replace(removing: subrange, moving: &items) + 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, using a - /// geometric growth rate. - /// - /// 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`) - @available(*, deprecated, renamed: "replace(removing:moving:)") + + @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, moving newElements: inout RigidArray, ) { - self.replace(removing: subrange, moving: &newElements) + replaceSubrange(subrange, moving: &newElements) } - - /// 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 perform the replacement, - /// then this reallocates the array's storage to extend its capacity, using a - /// geometric growth rate. - /// - /// 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`) - @available(*, deprecated, renamed: "replace(removing:consuming:)") + + @available(*, deprecated, renamed: "replaceSubrange(_:consuming:)") @_alwaysEmitIntoClient - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, consuming newElements: consuming RigidArray, ) { - self.replace(removing: subrange, consuming: newElements) + replaceSubrange(subrange, consuming: newElements) } + } @available(SwiftStdlib 5.0, *) @@ -356,155 +254,40 @@ extension UniqueArray { clone(capacity: capacity) } - /// 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 perform the replacement, - /// then this reallocates the array's storage to extend its capacity, using a - /// geometric growth rate. - /// - /// 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`. - @available(*, deprecated, renamed: "replace(removing:copying:)") + @available(*, deprecated, renamed: "replace(_:copying:)") @inlinable - @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: UnsafeBufferPointer ) { - self.replace(removing: subrange, copying: newElements) + 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 the capacity of the array isn't sufficient to perform the replacement, - /// then this reallocates the array's storage to extend its capacity, using a - /// geometric growth rate. - /// - /// 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`. - @available(*, deprecated, renamed: "replace(removing:copying:)") + + @available(*, deprecated, renamed: "replace(_:copying:)") @inlinable - @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: UnsafeMutableBufferPointer ) { - self.replace(removing: subrange, copying: newElements) + self.replaceSubrange(subrange, copying: 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 perform the replacement, - /// then this reallocates the array's storage to extend its capacity, using a - /// geometric growth rate. - /// - /// 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(*, deprecated, renamed: "replace(removing:copying:)") + + @available(*, deprecated, renamed: "replace(_:copying:)") @inlinable - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: Span ) { - self.replace(removing: subrange, copying: newElements) + 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 the capacity of the array isn't sufficient to perform the replacement, - /// then this reallocates the array's storage to extend its capacity, using a - /// geometric growth rate. - /// - /// 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`. - @available(*, deprecated, renamed: "replace(removing:copying:)") + + @available(*, deprecated, renamed: "replace(_:copying:)") @inlinable - @inline(__always) - public mutating func replaceSubrange( - _ subrange: Range, + public mutating func replace( + removing subrange: Range, copying newElements: __owned some Collection ) { - self.replace(removing: subrange, copying: newElements) + replaceSubrange(subrange, copying: newElements) } } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift index 1da4fc41..89947c22 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift @@ -36,14 +36,15 @@ extension UniqueArray where Element: ~Copyable { /// - Parameter item: The new element to insert into the array. /// - Parameter index: The position at which to insert the new element. /// `index` must be a valid index in the array. - /// + /// - Returns: A valid index to the newly inserted item. /// - Complexity: O(`self.count`) @inlinable - public mutating func insert(_ item: consuming Element, at index: Int) { + @discardableResult + public mutating func insert(_ item: consuming Element, at index: Int) -> Int { precondition(index >= 0 && index <= count) // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(1) - _storage.insert(item, at: index) + return _storage.insert(item, at: index) } } @@ -79,17 +80,18 @@ extension UniqueArray where Element: ~Copyable { /// populate newly reserved storage within the array. The function /// is called with an empty output span of capacity matching the /// supplied count, and it must fully populate it before returning. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `count`) @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func insert( addingCount newItemCount: Int, at index: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { + ) throws(E) -> Range { _ensureFreeCapacity(newItemCount) - try _storage.insert( + return try _storage.insert( addingCount: newItemCount, at: index, initializingWith: initializer) @@ -109,16 +111,17 @@ extension UniqueArray where Element: ~Copyable { /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: UnsafeMutableBufferPointer, at index: Int - ) { + ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(items.count) - _storage.insert(moving: items, at: index) + return _storage.insert(moving: items, at: index) } #if UnstableContainersPreview @@ -137,16 +140,17 @@ extension UniqueArray where Element: ~Copyable { /// the array. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: inout InputSpan, at index: Int - ) { + ) -> Range { // FIXME: Remove when InputSpan starts conforming to RangeReplaceableContainer _ensureFreeCapacity(items.count) - _storage.insert(moving: &items, at: index) + return _storage.insert(moving: &items, at: index) } #endif @@ -165,16 +169,17 @@ extension UniqueArray where Element: ~Copyable { /// the array. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: inout OutputSpan, at index: Int - ) { + ) -> Range { // FIXME: Remove when OutputSpan starts conforming to RangeReplaceableContainer _ensureFreeCapacity(items.count) - _storage.insert(moving: &items, at: index) + return _storage.insert(moving: &items, at: index) } /// Inserts the elements of a given array into the given position in this @@ -189,16 +194,17 @@ extension UniqueArray where Element: ~Copyable { /// - Parameters: /// - items: An array whose contents to move into `self`. /// - index: The position in `self` at which to insert the new items. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: inout RigidArray, at index: Int - ) { + ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(items.count) - _storage.insert(moving: &items, at: index) + return _storage.insert(moving: &items, at: index) } } @@ -223,15 +229,16 @@ extension UniqueArray { /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) @inlinable + @discardableResult public mutating func insert( copying newElements: UnsafeBufferPointer, at index: Int - ) { + ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(newElements.count) - unsafe _storage.insert(copying: newElements, at: index) + return unsafe _storage.insert(copying: newElements, at: index) } /// Copies the elements of a fully initialized buffer pointer into this @@ -253,13 +260,14 @@ extension UniqueArray { /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be /// a valid index of the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) @inlinable + @discardableResult public mutating func insert( copying newElements: UnsafeMutableBufferPointer, at index: Int - ) { + ) -> Range { unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index) } @@ -280,15 +288,16 @@ extension UniqueArray { /// - 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) @inlinable + @discardableResult public mutating func insert( copying newElements: Span, at index: Int - ) { + ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(newElements.count) - _storage.insert(copying: newElements, at: index) + return _storage.insert(copying: newElements, at: index) } /// Copies the elements of a collection into this array at the specified @@ -309,19 +318,20 @@ extension UniqueArray { /// - 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) @inlinable + @discardableResult public mutating func insert( copying newElements: some Collection, at index: Int - ) { + ) -> Range { // FIXME: Remove this -- RangeReplaceContainer already has this algorithm. // (Note that this would be source breaking while RRC lives in the separate // ContainersPreview module.) // FIXME: Avoid moving the subsequent elements twice. let newCount = newElements.count _ensureFreeCapacity(newCount) - _storage._insertCollection( + return _storage._insertCollection( addingCount: newCount, copying: newElements, at: index) } } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift index 161aead0..459fd7b5 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift @@ -19,20 +19,52 @@ import InternalCollectionsUtilities @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { - /// Removes all elements from the array, optionally preserving its + /// Removes all elements from the array, preserving its /// allocated capacity. /// /// - Complexity: O(*n*), where *n* is the original count of the array. @inlinable @inline(__always) - public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { - if keepCapacity { - _storage.removeAll() - } else { - _storage = RigidArray(capacity: 0) - } + public mutating func removeAll() { + _storage.removeAll() } + /// Removes and returns the element at the specified position. + /// + /// All the elements following the specified position are moved to close the + /// gap. + /// + /// - Parameter index: The position of the element to remove. `index` must be + /// a valid index of the array that is not equal to the end index. + /// On return, `index` is updated to address the position following the + /// removed element. + /// - Returns: The removed element. + /// + /// - Complexity: O(`self.count`) + @inlinable + @inline(__always) + @discardableResult + public mutating func remove(at index: inout Int) -> Element { + _storage.remove(at: &index) + } + + /// Removes and returns the element at the specified position. + /// + /// All the elements following the specified position are moved to close the + /// gap. + /// + /// - Parameter index: 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 { + _storage.remove(at: index) + } + + /// Removes and returns the last element of the array. /// /// The array must not be empty. @@ -63,23 +95,6 @@ extension UniqueArray where Element: ~Copyable { _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 index: 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 @@ -90,7 +105,8 @@ extension UniqueArray where Element: ~Copyable { /// /// - Complexity: O(`self.count`) @inlinable - public mutating func removeSubrange(_ bounds: Range) { + @discardableResult + public mutating func removeSubrange(_ bounds: Range) -> Int { _storage.removeSubrange(bounds) } @@ -101,8 +117,11 @@ extension UniqueArray where Element: ~Copyable { /// /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient - public mutating func removeSubrange(_ bounds: some RangeExpression) { - // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm. + @discardableResult + public mutating func removeSubrange( + _ bounds: some RangeExpression + ) -> Int { + // FIXME: Remove this in favor of the DrainableContainer algorithm. removeSubrange(bounds.relative(to: indices)) } } @@ -117,7 +136,7 @@ extension UniqueArray where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient public mutating func popLast() -> Element? { - // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm. + // FIXME: Remove this in favor of the DrainableContainer algorithm. if isEmpty { return nil } return removeLast() } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift index f11bb85c..3a99080a 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift @@ -58,21 +58,22 @@ extension UniqueArray where Element: ~Copyable { /// - initializer: A callback that gets called at most once to directly /// populate newly reserved storage within the array. The function /// is always called with an empty output span. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity /// of the callback invocations. - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { _storage._checkValidBounds(subrange) precondition(newItemCount >= 0, "Cannot add a negative number of items") // FIXME: Avoid moving the subsequent elements twice on resize. _ensureFreeCapacity(newItemCount - subrange.count) - try _storage._uncheckedReplace( - removing: subrange, + return try _storage._uncheckedReplaceSubrange( + subrange, addingCount: newItemCount, initializingWith: initializer) } @@ -126,21 +127,22 @@ extension UniqueArray where Element: ~Copyable { /// - initializer: A callback that gets called at most once to directly /// populate newly reserved storage within the deque. The function /// is always called with an empty output span. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newItemCount`) in addition to the /// complexity of the callback invocations. - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { _storage._checkValidBounds(subrange) precondition(newItemCount >= 0, "Cannot add a negative number of items") _ensureFreeCapacity(newItemCount - subrange.count) - try _storage._uncheckedReplace( - removing: subrange, + return try _storage._uncheckedReplaceSubrange( + subrange, consumingWith: consumer, addingCount: newItemCount, initializingWith: initializer) @@ -177,16 +179,17 @@ extension UniqueArray where Element: ~Copyable { /// the range must be valid indices in the array. /// - newElements: A fully initialized buffer whose contents to move into /// the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving newElements: UnsafeMutableBufferPointer, - ) { + ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(newElements.count - subrange.count) - _storage.replace(removing: subrange, moving: newElements) + return _storage.replaceSubrange(subrange, moving: newElements) } #if UnstableContainersPreview @@ -215,16 +218,17 @@ extension UniqueArray where Element: ~Copyable { /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - items: An input span whose contents are to be moved into the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving items: inout InputSpan - ) { + ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(items.count - subrange.count) - _storage.replace(removing: subrange, moving: &items) + return _storage.replaceSubrange(subrange, moving: &items) } #endif @@ -253,16 +257,17 @@ extension UniqueArray where Element: ~Copyable { /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the array. /// - items: An output span whose contents are to be moved into the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving items: inout OutputSpan - ) { + ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(items.count - subrange.count) - _storage.replace(removing: subrange, moving: &items) + return _storage.replaceSubrange(subrange, moving: &items) } /// Replaces the specified range of elements by moving the elements of a @@ -292,16 +297,17 @@ extension UniqueArray where Element: ~Copyable { /// - 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`. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving newElements: inout RigidArray, - ) { + ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(newElements.count - subrange.count) - _storage.replace(removing: subrange, moving: &newElements) + return _storage.replaceSubrange(subrange, moving: &newElements) } } @@ -332,14 +338,15 @@ extension UniqueArray where Element: ~Copyable { /// - 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`. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, consuming newElements: consuming RigidArray, - ) { - replace(removing: subrange, moving: &newElements) + ) -> Range { + replaceSubrange(subrange, moving: &newElements) } } @@ -370,18 +377,19 @@ extension UniqueArray { /// - 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(*n* + *m*), where *n* is count of this array and /// *m* is the count of `newElements`. - @inlinable + @_alwaysEmitIntoClient @inline(__always) - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying newElements: UnsafeBufferPointer - ) { + ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(newElements.count - subrange.count) - unsafe _storage.replace(removing: subrange, copying: newElements) + return unsafe _storage.replaceSubrange(subrange, copying: newElements) } /// Replaces the specified subrange of elements by copying the elements of @@ -409,18 +417,17 @@ extension UniqueArray { /// - 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(*n* + *m*), where *n* is count of this array and /// *m* is the count of `newElements`. - @inlinable + @_alwaysEmitIntoClient @inline(__always) - public mutating func replace( - removing subrange: Range, + public mutating func replaceSubrange( + _ subrange: Range, copying newElements: UnsafeMutableBufferPointer ) { - unsafe self.replace( - removing: subrange, - copying: UnsafeBufferPointer(newElements)) + unsafe self.replaceSubrange( + subrange, copying: UnsafeBufferPointer(newElements)) } /// Replaces the specified subrange of elements by copying the elements of @@ -448,17 +455,18 @@ extension UniqueArray { /// - 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(*n* + *m*), where *n* is count of this array and /// *m* is the count of `newElements`. - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying newElements: Span - ) { + ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(newElements.count - subrange.count) - _storage.replace(removing: subrange, copying: newElements) + return _storage.replaceSubrange(subrange, copying: newElements) } /// Replaces the specified subrange of elements by copying the elements of @@ -486,20 +494,21 @@ extension UniqueArray { /// - 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. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(*n* + *m*), where *n* is count of this array and /// *m* is the count of `newElements`. - @inlinable + @_alwaysEmitIntoClient @inline(__always) - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying newElements: __owned some Collection - ) { + ) -> Range { // FIXME: Avoid moving the subsequent elements twice. let c = newElements.count _ensureFreeCapacity(c - subrange.count) - _storage._replace( - removing: subrange, + return _storage._replaceSubrange( + subrange, copyingCollection: newElements, newCount: c) } diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt index 97bcf602..644df079 100644 --- a/Sources/ContainersPreview/CMakeLists.txt +++ b/Sources/ContainersPreview/CMakeLists.txt @@ -55,6 +55,7 @@ target_sources(${module_name} PRIVATE "Protocols/Container/RangeExpression2.swift" "Protocols/Container/RangeReplaceableContainer.swift" "Protocols/Container/Strideable+Limits.swift" + "Protocols/Drain/ContainerDrain.swift" "Protocols/Drain/Drain.swift" "Protocols/Drain/Drain+Map.swift" "Protocols/Drain/Drain+Reduce.swift" diff --git a/Sources/ContainersPreview/Conformances/RigidArray+Container.swift b/Sources/ContainersPreview/Conformances/RigidArray+Container.swift index 82f57bb2..e34b7651 100644 --- a/Sources/ContainersPreview/Conformances/RigidArray+Container.swift +++ b/Sources/ContainersPreview/Conformances/RigidArray+Container.swift @@ -50,15 +50,15 @@ extension RigidArray: DrainableContainer where Element: ~Copyable {} extension RigidArray: RangeReplaceableContainer where Element: ~Copyable { @available(SwiftStdlib 6.4, *) @inlinable - internal mutating func _replace< + internal mutating func _replaceSubrange< C: Container & ~Copyable & ~Escapable >( - removing subrange: Range, + _ subrange: Range, copyingContainer items: borrowing C, newCount: Int - ) { + ) -> Range { var it = items.makeBorrowingIterator() - self.replace(removing: subrange, addingCount: newCount) { target in + return self.replaceSubrange(subrange, addingCount: newCount) { target in while !target.isFull { let source = it.nextSpan(maxCount: target.freeCapacity) precondition( @@ -99,16 +99,17 @@ extension RigidArray: RangeReplaceableContainer where Element: ~Copyable { /// /// - Complexity: O(`self.count` + `newElements.count`) @available(SwiftStdlib 6.4, *) - @inlinable + @_alwaysEmitIntoClient @inline(__always) - public mutating func replace< + @discardableResult + public mutating func replaceSubrange< C: Container & ~Copyable & ~Escapable >( - removing subrange: Range, + _ subrange: Range, copying newElements: borrowing C - ) { - _replace( - removing: subrange, + ) -> Range { + _replaceSubrange( + subrange, copyingContainer: newElements, newCount: newElements.count) } @@ -141,23 +142,174 @@ extension RigidArray: RangeReplaceableContainer where Element: ~Copyable { /// - Complexity: O(*n* + *m*), where *n* is count of this array and /// *m* is the count of `newElements`. @available(SwiftStdlib 6.4, *) - @inlinable + @_alwaysEmitIntoClient @inline(__always) - public mutating func replace< + @discardableResult + public mutating func replaceSubrange< C: Container & Collection >( - removing subrange: Range, + _ subrange: Range, copying newElements: C - ) { - _replace( - removing: subrange, + ) -> Range { + _replaceSubrange( + subrange, copyingContainer: newElements, newCount: newElements.count) } + + @_alwaysEmitIntoClient + public mutating func _customRemoveLast() -> Element? { + self.removeLast() + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func _customConsumeLast(_ n: Int) -> SubrangeConsumer? { + self.consumeLast(n) + } + + @_alwaysEmitIntoClient + public mutating func _customRemoveLast(_ n: Int) -> Bool { + self.removeLast(n) + return true + } } @available(SwiftStdlib 5.0, *) -extension RigidArray.SubrangeConsumer: Drain where Element: ~Copyable { +extension RigidArray.SubrangeConsumer: ContainerDrain where Element: ~Copyable { +} + +@available(SwiftStdlib 6.4, *) +extension RigidArray where Element: ~Copyable { + /// Creates a new rigid array of the specified capacity, populating it with + /// all items generated by a given producer. + /// + /// If the capacity is exhausted before the producer reaches its end, then + /// this triggers a runtime error. + /// + /// If the producer throws an error during this initializer, then all + /// previously produced items are discarded and the initializer rethrows the + /// error. + /// + /// - Parameters: + /// - capacity: The desired storage capacity of the new array. + /// - producer: A producer that generates the items to append to the new + /// array. + /// + /// - Complexity: O(`capacity`) + @_alwaysEmitIntoClient + public init< + E: Error, + P: Producer & ~Copyable & ~Escapable + >( + capacity: Int, + from producer: consuming P + ) throws(E) + where P.Element: ~Copyable + { + self.init(capacity: capacity) + try self.append(addingCount: capacity, from: &producer) + try producer._expectEnd("RigidDeque capacity overflow") + } + + /// Creates a new rigid array of the specified capacity, populating it with + /// all items generated by a given counted producer. + /// + /// If the capacity is exhausted before the producer reaches its end, then + /// this triggers a runtime error. + /// + /// If the producer throws an error during this initializer, then all + /// previously produced items are discarded and the initializer rethrows the + /// error. + /// + /// - Parameters: + /// - capacity: The desired storage capacity of the new array, or nil + /// to allocate exactly as much room as needed to store the new items. + /// - producer: A producer that generates the items to append to the new + /// array. + /// + /// - Complexity: O(`capacity`) + @_alwaysEmitIntoClient + public init< + E: Error, + P: CountedProducer & ~Copyable & ~Escapable + >( + capacity: Int? = nil, + from producer: consuming P + ) throws(E) + where P.Element: ~Copyable + { + let c = producer.count + let capacity = capacity ?? c + precondition(capacity >= c, "RigidDeque capacity overflow") + self.init(capacity: capacity) + try self.append(addingCount: c, from: &producer) + try producer._expectEnd("Invalid CountedProducer") + } + +} + +@available(SwiftStdlib 6.4, *) +extension RigidArray /* where Element: Copyable */ { + /// Creates a new array with the specified capacity, holding a copy + /// of the contents of the given container. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new array, or nil to allocate + /// just enough capacity to store the contents of the source container. + /// - span: The containers whose contents to copy into the new array. + /// The container must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init< + C: Container & ~Copyable & ~Escapable + >( + capacity: Int? = nil, + copying items: borrowing C + ) { + self.init(capacity: capacity ?? items.count) + self.append(copying: items) + } + + /// Creates a new array with the specified capacity, holding a copy + /// of the contents of the given container. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new array, or nil to allocate + /// just enough capacity to store the contents of the source container. + /// - span: The containers whose contents to copy into the new array. + /// The container must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init< + C: Container & Sequence + >( + capacity: Int? = nil, + copying items: __shared C + ) { + self.init(capacity: capacity ?? items.count) + self.append(copying: items) + } + + /// Creates a new array with the specified capacity, holding a copy + /// of the contents of the given container. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new array, or nil to allocate + /// just enough capacity to store the contents of the source container. + /// - span: The containers whose contents to copy into the new array. + /// The container must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init< + C: Container & Collection + >( + capacity: Int? = nil, + copying items: __shared C + ) { + self.init(capacity: capacity ?? items.count) + self.append(copying: items) + } } #endif diff --git a/Sources/ContainersPreview/Conformances/RigidDeque+Container.swift b/Sources/ContainersPreview/Conformances/RigidDeque+Container.swift index cbc4b015..96f14b2b 100644 --- a/Sources/ContainersPreview/Conformances/RigidDeque+Container.swift +++ b/Sources/ContainersPreview/Conformances/RigidDeque+Container.swift @@ -18,7 +18,7 @@ import DequeModule #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidDeque: Container where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) @@ -35,23 +35,26 @@ extension RigidDeque: Container where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidDeque: BidirectionalContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidDeque: RandomAccessContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidDeque: MutableContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) +extension RigidDeque: DrainableContainer where Element: ~Copyable {} + +@available(SwiftStdlib 6.4, *) extension RigidDeque: RangeReplaceableContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) -extension RigidDeque.SubrangeConsumer: Drain where Element: ~Copyable { +@available(SwiftStdlib 6.4, *) +extension RigidDeque.SubrangeConsumer: ContainerDrain where Element: ~Copyable { } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidDeque where Element: ~Copyable { /// Creates a new rigid deque of the specified capacity, populating it with /// all items generated by a given producer. @@ -64,91 +67,59 @@ extension RigidDeque where Element: ~Copyable { /// error. /// /// - Parameters: + /// - capacity: The desired storage capacity of the new array. /// - producer: A producer that generates the items to append to the new /// deque. /// /// - Complexity: O(`capacity`) + @_alwaysEmitIntoClient public init< E: Error, P: Producer & ~Copyable & ~Escapable >( capacity: Int, - from producer: inout P + from producer: consuming P ) throws(E) where P.Element: ~Copyable { self.init(capacity: capacity) - try self.append(from: &producer) + try self.append(addingCount: capacity, from: &producer) + try producer._expectEnd("RigidDeque capacity overflow") } - /// Appends at most `newItemCount` items generated by a producer to the end of - /// this deque. + /// Creates a new rigid deque of the specified capacity, populating it with + /// all items generated by a given counted producer. /// - /// If the target deque does not have sufficient capacity to hold the - /// specified number of new items, then this triggers a runtime error. + /// If the capacity is exhausted before the producer reaches its end, then + /// this triggers a runtime error. /// - /// This operation appends as many items as the producer can generate before - /// either reaching its end (or throwing an error), or filling the specified - /// capacity. This operation only consumes the first `newItemCount` items in the - /// producer; if the producer has more, then they remain available after this - /// method returns. + /// If the producer throws an error during this initializer, then all + /// previously produced items are discarded and the initializer rethrows the + /// error. /// /// - Parameters: - /// - newItemCount: The maximum number of items to append to the deque, or - /// nil to use all available capacity. - /// - producer: A producer that generates the items to append. + /// - capacity: The desired storage capacity of the new array, or nil + /// to allocate exactly as much room as needed to store the new items. + /// - producer: A producer that generates the items to append to the new + /// deque. /// - /// - Complexity: O(*n*), where *n* is the number of items + /// - Complexity: O(`capacity`) @_alwaysEmitIntoClient - public mutating func append< + public init< E: Error, - P: Producer & ~Copyable & ~Escapable + P: CountedProducer & ~Copyable & ~Escapable >( - addingCount newItemCount: Int, - from producer: inout P + capacity: Int? = nil, + from producer: consuming P ) throws(E) where P.Element: ~Copyable { - try self.append(addingCount: newItemCount) { target throws(E) in - while !target.isFull { - guard try producer.generate(into: &target) else { break } - } - } - } - - /// Appends all the items generated by a producer to the end of this deque. - /// - /// If the target deque does not have sufficient capacity to hold all the - /// new items, then this triggers a runtime error. - /// - /// - Parameters: - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(*n*), where *n* is the number of items produced. - @_alwaysEmitIntoClient - public mutating func append< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - from producer: inout P - ) throws(E) - where P.Element: ~Copyable - { - var done = false - try self.append( - addingCount: freeCapacity - ) { target throws(E) in - while !target.isFull { - guard try producer.generate(into: &target) else { - done = true - break - } - } - } - if !done { - done = (try producer.next() == nil) - } - precondition(done, "RigidDeque capacity overflow") + let c = producer.count + let capacity = capacity ?? c + precondition(capacity >= c, "RigidDeque capacity overflow") + self.init(capacity: capacity) + try self.append(addingCount: c, from: &producer) + try producer._expectEnd("Invalid CountedProducer") } /// Prepends at most `newItemCount` items generated by a producer to the @@ -169,137 +140,153 @@ extension RigidDeque where Element: ~Copyable { /// many items as promised. /// /// - Parameters: - /// - newItemCount: The maximum number of items to prepend to the deque, or - /// nil to use all available capacity. + /// - newItemCount: The maximum number of items to prepend to the deque. /// - producer: A producer that generates the items to prepend. - /// - /// - Complexity: O(`newItemCount ?? self.freeCapacity`) + /// - Returns: A valid index range addressing the newly inserted items. + /// - Complexity: O(`newItemCount`) @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func prepend< E: Error, P: Producer & ~Copyable & ~Escapable >( - addingCount newItemCount: Int? = nil, + addingCount newItemCount: Int, from producer: inout P - ) throws(E) + ) throws(E) -> Range where P.Element: ~Copyable { - try self.prepend( - addingCount: newItemCount ?? freeCapacity - ) { target throws(E) in + try self.prepend(addingCount: newItemCount) { target throws(E) in try producer.generate(into: &target) } } - /// Replaces the specified range of elements by at most `newItemCount` items - /// generated by a producer. + /// Prepends all items generated by a counted producer to the front of this deque. /// - /// This method has the effect of removing the specified range of elements - /// from the deque 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 deque 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 items generated by `producer` at `subrange.lowerBound`. This - /// case is more directly expressed by calling `insert(moving:at:)`. - /// - /// Likewise, if the given producer is empty, then this method removes the - /// elements in the given subrange without replacement. This case is more - /// directly expressed by calling `removeSubrange`. - /// - /// This operation inserts as many items as the producer can generate before - /// either reaching `newItemCount`, or the producer hitting its end, or - /// throwing an error. If the producer has more than `newItemCount` items left in - /// its underlying sequence, then extra items remain available after this - /// method returns. - /// - /// If the operation inserts fewer than `newItemCount` items, then it results in - /// a gap in ring buffer storage that needs to be closed by moving some - /// items to their correct positions given the adjusted count. This adds some - /// overhead compared to adding exactly as many items as promised. + /// If the target deque does not have sufficient capacity to hold all items + /// generated by the producer, then this triggers a runtime error. /// /// - Parameters: - /// - subrange: The subrange of the deque to replace. The bounds of - /// the range must be valid indices in the deque. - /// - newItemCount: The maximum number of items to insert into the deque. - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(`self.count` + `maxCount`) + /// - producer: A counted producer that generates the items to prepend. + /// - Returns: A valid index range addressing the newly inserted items. + /// - Complexity: O(`newItemCount`) @_alwaysEmitIntoClient - public mutating func replace< + @inline(__always) + @discardableResult + public mutating func prepend< E: Error, - P: Producer & ~Copyable & ~Escapable + P: CountedProducer & ~Copyable & ~Escapable >( - removing subrange: Range, - addingCount newItemCount: Int, - from producer: inout P - ) throws(E) + from producer: consuming P + ) throws(E) -> Range where P.Element: ~Copyable { - try replace( - removing: subrange, - addingCount: newItemCount - ) { target throws(E) in - while !target.isFull { - guard try producer.generate(into: &target) else { break } - } - } + let range = try self.prepend(addingCount: producer.count, from: &producer) + try producer._expectEnd("Invalid CountedProducer") + return range } - /// Inserts at most `newItemCount` items generated by a producer into this - /// deque, starting at the given index. + /// Moves the elements of a given container to the front of this deque, leaving + /// the source container empty. /// - /// Existing elements in the deque's storage are moved as needed to make room - /// for the new items. (The direction of the move depends on the location of - /// the insertion, minimizing the cost.) - /// - /// If the target deque does not have sufficient capacity to hold the - /// specified number of new items, then this triggers a runtime error. - /// - /// This operation inserts as many items as the producer can generate before - /// either reaching `newItemCount`, or the producer hitting its end, or - /// throwing an error. If the producer has more than `newItemCount` items - /// left in its underlying sequence, then extra items remain available after - /// this method returns. - /// - /// If the operation inserts fewer than `newItemCount` items, then it results - /// in a gap in ring buffer storage that needs to be closed by moving some - /// items to their correct positions given the adjusted count. This adds some - /// overhead compared to adding exactly as many items as promised. + /// The target deque must be able to accommodate all items in the source + /// container. /// /// - Parameters: - /// - newItemCount: The maximum number of items to insert into the deque. - /// - index: The position at which to insert the new items. - /// `index` must be a valid index in the deque. - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(`self.count` + `newItemCount`) + /// - items: A container whose contents to move into this container. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient - public mutating func insert< - E: Error, - P: Producer & ~Copyable & ~Escapable + @discardableResult + public mutating func prepend< + C: DrainableContainer & ~Copyable & ~Escapable >( - addingCount newItemCount: Int, - from producer: inout P, - at index: Int - ) throws(E) - where P.Element: ~Copyable - { - try insert(addingCount: newItemCount, at: index) { target throws(E) in - while !target.isFull, try producer.generate(into: &target) { - // Do nothing - } - } + moving items: inout C + ) -> Range + where C.Element: ~Copyable { + self.prepend(from: items.consumeAll()) + } + + @_alwaysEmitIntoClient + @discardableResult + public mutating func prepend< + C: DrainableContainer & ~Copyable & ~Escapable + >( + moving sourceSubrange: some RangeExpression2, + from source: inout C + ) -> Range + where C.Element: ~Copyable { + let sourceSubrange = sourceSubrange.relative(to: source) + let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) + var producer = source.consumeSubrange(sourceSubrange) + let range = self.prepend(addingCount: c, from: &producer) + producer._expectEnd("Invalid Container") + return range } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidDeque /*where Element: Copyable*/ { + /// Creates a new deque with the specified capacity, holding a copy + /// of the contents of the given container. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new deque, or nil to allocate + /// just enough capacity to store the contents of the source container. + /// - span: The containers whose contents to copy into the new deque. + /// The container must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init< + C: Container & ~Copyable & ~Escapable + >( + capacity: Int? = nil, + copying items: borrowing C + ) { + self.init(capacity: capacity ?? items.count) + self.append(copying: items) + } + + /// Creates a new deque with the specified capacity, holding a copy + /// of the contents of the given container. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new deque, or nil to allocate + /// just enough capacity to store the contents of the source container. + /// - span: The containers whose contents to copy into the new deque. + /// The container must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init< + C: Container & Sequence + >( + capacity: Int? = nil, + copying items: __shared C + ) { + self.init(capacity: capacity ?? items.count) + self.append(copying: items) + } + + /// Creates a new deque with the specified capacity, holding a copy + /// of the contents of the given container. + /// + /// - Parameters: + /// - capacity: The storage capacity of the new deque, or nil to allocate + /// just enough capacity to store the contents of the source container. + /// - span: The containers whose contents to copy into the new deque. + /// The container must not contain more than `capacity` elements. + @_alwaysEmitIntoClient + @inline(__always) + public init< + C: Container & Collection + >( + capacity: Int? = nil, + copying items: __shared C + ) { + self.init(capacity: capacity ?? items.count) + self.append(copying: items) + } + /// Copies the elements of a container and prepends them to the front /// of this deque. /// @@ -308,13 +295,13 @@ extension RigidDeque /*where Element: Copyable*/ { /// /// - Parameters: /// - items: The new elements to copy into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) - @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient + @discardableResult public mutating func prepend & ~Copyable & ~Escapable>( copying items: borrowing C - ) { + ) -> Range { self._prepend(copying: items, exactCount: items.count) } @@ -325,13 +312,13 @@ extension RigidDeque /*where Element: Copyable*/ { /// /// - Parameters: /// - items: The new elements to copy into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(*m*), where *m* is the length of `items`. - @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient + @discardableResult public mutating func prepend & Sequence>( copying items: borrowing C - ) { + ) -> Range { self._prepend(copying: items, exactCount: items.count) } @@ -342,198 +329,15 @@ extension RigidDeque /*where Element: Copyable*/ { /// /// - Parameters: /// - items: The new elements to copy into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(*m*), where *m* is the length of `items`. - @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient + @discardableResult public mutating func prepend & Collection>( copying items: borrowing C - ) { + ) -> Range { self._prepend(copying: items, exactCount: items.count) } - - @available(SwiftStdlib 6.4, *) - @inlinable - package mutating func _insertContainer< - C: Container & ~Copyable & ~Escapable - >( - at index: Int, - copying items: borrowing C, - newCount: Int - ) { - let expectedCount = self.count + newCount - var it = items.makeBorrowingIterator() - insert(addingCount: newCount, at: index) { target in - it._copyContents(into: &target) - } - precondition( - it.nextSpan().isEmpty && self.count == expectedCount, - "Broken Container: count doesn't match contents") - } - - /// Copies the elements of a container into this deque at the specified - /// position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the deque's `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the deque. - /// - /// Existing elements in the deque's storage are moved as needed to make room - /// for the new items. (The direction of the move depends on the location of - /// the insertion, minimizing the cost.) - /// - /// If the capacity of the deque isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// - Parameters: - /// - items: The new elements to insert into the deque. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the deque. - /// - /// - Complexity: O(`self.count` + `items.count`). - @available(SwiftStdlib 6.4, *) - @_alwaysEmitIntoClient - @inline(__always) - public mutating func insert< - C: Container & ~Copyable & ~Escapable - >( - copying items: borrowing C, at index: Int - ) { - _insertContainer( - at: index, copying: items, newCount: items.count) - } - - /// Copies the elements of a container into this deque at the specified - /// position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the deque's `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the deque. - /// - /// Existing elements in the deque's storage are moved as needed to make room - /// for the new items. (The direction of the move depends on the location of - /// the insertion, minimizing the cost.) - /// - /// If the capacity of the deque isn't sufficient to accommodate the new - /// elements, then this method triggers a runtime error. - /// - /// - Parameters: - /// - items: The new elements to insert into the deque. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the deque. - /// - /// - Complexity: O(`self.count` + `items.count`) - @available(SwiftStdlib 6.4, *) - @_alwaysEmitIntoClient - @inline(__always) - public mutating func insert< - C: Container & Collection - >( - copying items: borrowing C, at index: Int - ) { - _insertContainer( - at: index, copying: items, newCount: items.count) - } - - @available(SwiftStdlib 6.4, *) - @inlinable - internal mutating func _replace< - C: Container & ~Copyable & ~Escapable - >( - removing subrange: Range, - copyingContainer items: borrowing C, - newCount: Int - ) { - - let expectedCount = self.count - subrange.count + newCount - var it = items.makeBorrowingIterator() - self.replace(removing: subrange, addingCount: newCount) { target in - it._copyContents(into: &target) - } - precondition( - it.nextSpan().isEmpty && count == expectedCount, - "Broken Container: count doesn't match contents") - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given container. - /// - /// This method has the effect of removing the specified range of elements - /// from the deque 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 deque 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 `items` at `subrange.lowerBound`. This case - /// is more directly expressed by calling `insert(copying:at:)`. - /// - /// Likewise, if you pass a zero-length container as the `items` - /// parameter, this method removes the elements in the given subrange - /// without replacement. This case is more directly expressed by calling - /// `removeSubrange`. - /// - /// - Parameters: - /// - subrange: The subrange of the deque to replace. The bounds of - /// the range must be valid indices in the array. - /// - items: The new elements to copy into the collection. - /// - /// - Complexity: O(`self.count` + `items.count`) - @available(SwiftStdlib 6.4, *) - @inlinable - @inline(__always) - public mutating func replace< - C: Container & ~Copyable & ~Escapable - >( - removing subrange: Range, - copying items: borrowing C - ) { - _replace( - removing: subrange, copyingContainer: items, newCount: items.count) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given container. - /// - /// This method has the effect of removing the specified range of elements - /// from the deque 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 deque 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 `items` at `subrange.lowerBound`. This case - /// is more directly expressed by calling `insert(copying:at:)`. - /// - /// Likewise, if you pass a zero-length container as the `items` - /// parameter, this method removes the elements in the given subrange - /// without replacement. This case is more directly expressed by calling - /// `removeSubrange`. - /// - /// - Parameters: - /// - subrange: The subrange of the deque to replace. The bounds of - /// the range must be valid indices in the array. - /// - items: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this deque and - /// *m* is the count of `items`. - @available(SwiftStdlib 6.4, *) - @inlinable - @inline(__always) - public mutating func replace< - C: Container & Collection - >( - removing subrange: Range, - copying items: C - ) { - _replace( - removing: subrange, copyingContainer: items, newCount: items.count) - } - } #endif diff --git a/Sources/ContainersPreview/Conformances/RigidSet+Container.swift b/Sources/ContainersPreview/Conformances/RigidSet+Container.swift index fe014935..1723da9a 100644 --- a/Sources/ContainersPreview/Conformances/RigidSet+Container.swift +++ b/Sources/ContainersPreview/Conformances/RigidSet+Container.swift @@ -17,7 +17,7 @@ import BasicContainers #if compiler(>=6.4) && UnstableContainersPreview && UnstableHashedContainers -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RigidSet: Container where Element: ~Copyable { @_alwaysEmitIntoClient public func currentIndex(of iterator: inout BorrowingIterator) -> Index { diff --git a/Sources/ContainersPreview/Conformances/UniqueArray+Container.swift b/Sources/ContainersPreview/Conformances/UniqueArray+Container.swift index 47d345e4..ed655f52 100644 --- a/Sources/ContainersPreview/Conformances/UniqueArray+Container.swift +++ b/Sources/ContainersPreview/Conformances/UniqueArray+Container.swift @@ -41,14 +41,13 @@ extension UniqueArray: RandomAccessContainer where Element: ~Copyable {} @available(SwiftStdlib 6.4, *) extension UniqueArray: MutableContainer where Element: ~Copyable {} +@available(SwiftStdlib 6.4, *) +extension UniqueArray: DrainableContainer where Element: ~Copyable {} + @available(SwiftStdlib 6.4, *) extension UniqueArray: RangeReplaceableContainer where Element: ~Copyable {} @available(SwiftStdlib 6.4, *) extension UniqueArray: DynamicContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) -extension UniqueArray where Element: Copyable { -} - #endif diff --git a/Sources/ContainersPreview/Conformances/UniqueDeque+Container.swift b/Sources/ContainersPreview/Conformances/UniqueDeque+Container.swift index 8838024f..fc7f9aa1 100644 --- a/Sources/ContainersPreview/Conformances/UniqueDeque+Container.swift +++ b/Sources/ContainersPreview/Conformances/UniqueDeque+Container.swift @@ -18,7 +18,7 @@ import DequeModule #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueDeque: Container where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) @@ -34,87 +34,26 @@ extension UniqueDeque: Container where Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueDeque: BidirectionalContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueDeque: RandomAccessContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueDeque: MutableContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) +extension UniqueDeque: DrainableContainer where Element: ~Copyable {} + +@available(SwiftStdlib 6.4, *) extension UniqueDeque: RangeReplaceableContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueDeque: DynamicContainer where Element: ~Copyable {} -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueDeque where Element: ~Copyable { - /// Appends at most `newItemCount` items generated by a producer to the end of - /// this deque. - /// - /// If the deque doesn't have sufficient capacity to accommodate the specified - /// number of new elements, then this method reallocates the deque's storage - /// to grow it, using a geometric growth rate. - /// - /// This operation appends as many items as the producer can generate before - /// either reaching its end (or throwing an error), or filling the specified - /// capacity. This operation only consumes the first `newItemCount` items in the - /// producer; if the producer has more, then they remain available after this - /// method returns. - /// - /// - Parameters: - /// - newItemCount: The maximum number of items to append to the deque. - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(*n*) where *n* is the number of new items, when - /// amortized over many similar invocations on the same deque. - @_alwaysEmitIntoClient - public mutating func append< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - addingCount newItemCount: Int, - from producer: inout P - ) throws(E) - where P.Element: ~Copyable - { - _ensureFreeCapacity(newItemCount) - try _storage.append(addingCount: newItemCount, from: &producer) - } - - /// Appends all the items generated by a producer to the end of this deque. - /// - /// If the deque doesn't have sufficient capacity to accommodate all the - /// elements, then this method reallocates the deque's storage - /// to grow it, using a geometric growth rate. - /// - /// - Parameters: - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(*n*) where *n* is the number of new items, when - /// amortized over many similarly-sized invocations on the same deque. - @_alwaysEmitIntoClient - public mutating func append< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - from producer: inout P - ) throws(E) - where P.Element: ~Copyable - { - var done = false - while !done { - let c = Swift.max(producer.underestimatedCount, 1) - try self.append(addingCount: c) { target throws(E) in - while !target.isFull, !done { - done = try !producer.generate(into: &target) - } - } - } - } - /// Prepends at most `newItemCount` items generated by a producer to the front /// of this deque. /// @@ -136,22 +75,23 @@ extension UniqueDeque where Element: ~Copyable { /// - Parameters: /// - newItemCount: The maximum number of items to prepend to the deque. /// - producer: A producer that generates the items to prepend. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(*n*) where *n* is the number of new items, when /// amortized over many similar invocations on the same deque. @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func prepend< E: Error, P: Producer & ~Copyable & ~Escapable >( addingCount newItemCount: Int, from producer: inout P - ) throws(E) + ) throws(E) -> Range where P.Element: ~Copyable { _ensureFreeCapacity(newItemCount) - try _storage._handle.uncheckedPrepend( + return try _storage._handle.uncheckedPrepend( addingCount: newItemCount ) { target throws(E) in while !target.isFull, try producer.generate(into: &target) { @@ -167,266 +107,45 @@ extension UniqueDeque where Element: ~Copyable { /// using a geometric growth rate. /// /// - Parameters: - /// - producer: A producer that generates the items to prepend. - /// + /// - producer: A counted producer that generates the items to prepend. + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(*n*) where *n* is the number of new items, when /// amortized over many similarly-sized invocations on the same deque. @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func prepend< E: Error, P: Producer & ~Copyable & ~Escapable >( - from producer: inout P - ) throws(E) + from producer: consuming P + ) throws(E) -> Range where P.Element: ~Copyable { var done = false + var added = 0 while !done { let c = Swift.max(producer.underestimatedCount, 1) _ensureFreeCapacity(c) - try self.prepend(addingCount: freeCapacity) { target throws(E) in + _ = try _storage._handle.uncheckedPrepend( + addingCount: freeCapacity + ) { target throws(E) in + let origCount = target.count + defer { + let d = target.count - origCount + precondition(d >= 0, "Invalid Producer") + added &+= d + } while !target.isFull, !done { done = try !producer.generate(into: &target) } } } - } - - /// Creates a new unique deque of the specified capacity, populating it with - /// all items generated by a given producer. - /// - /// - Parameters: - /// - producer: A producer that generates the items to append to the new - /// deque. - /// - /// - Complexity: O(`capacity`) - public init< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - capacity: Int, - from producer: inout P - ) throws(E) - where P.Element: ~Copyable - { - self.init(minimumCapacity: capacity) - try self.append(addingCount: capacity, from: &producer) - } - - /// Creates a new unique deque, populating it with - /// all items generated by a given producer. - /// - /// - Parameters: - /// - producer: A producer that generates the items to append to the new - /// deque. - /// - /// - Complexity: O(`capacity`) - public init< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - from producer: inout P - ) throws(E) - where P.Element: ~Copyable - { - self.init(minimumCapacity: producer.underestimatedCount) - try self.append(from: &producer) - } - - /// Inserts at most `newItemCount` items generated by a producer into this - /// deque, starting at the given index. - /// - /// Existing elements in the deque's storage are moved as needed to make room - /// for the new items. (The direction of the move depends on the location of - /// the insertion, minimizing the cost.) - /// - /// If the deque does not have sufficient capacity to hold enough items, - /// then this reallocates the deque's storage to grow its capacity, using a - /// geometric growth rate. - /// - /// This operation inserts as many items as the producer can generate before - /// either reaching `newItemCount`, or the producer hitting its end, or - /// throwing an error. If the producer has more than `newItemCount` items - /// left in its underlying sequence, then extra items remain available after - /// this method returns. - /// - /// If the operation inserts fewer than `newItemCount` items, then it results - /// in a gap in ring buffer storage that needs to be closed by moving some - /// items to their correct positions given the adjusted count. This adds some - /// overhead compared to adding exactly as many items as promised. - /// - /// - Parameters: - /// - newItemCount: The maximum number of items to insert into the deque. - /// - index: The position at which to insert the new items. - /// `index` must be a valid index in the deque. - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(`self.count` + `newItemCount`) when amortized over many - /// similar invocations on the same deque. - @_alwaysEmitIntoClient - public mutating func insert< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - addingCount newItemCount: Int, - from producer: inout P, - at index: Int - ) throws(E) - where P.Element: ~Copyable - { - try insert(addingCount: newItemCount, at: index) { target throws(E) in - while !target.isFull, try producer.generate(into: &target) { - // Do nothing - } - } - } - - @available(SwiftStdlib 6.4, *) - @inlinable - internal mutating func _insertContainer< - C: Container & ~Copyable & ~Escapable - >( - at index: Int, - copying items: borrowing C, - newCount: Int - ) { - let expectedCount = self.count + newCount - var it = items.makeBorrowingIterator() - insert(addingCount: newCount, at: index) { target in - it._copyContents(into: &target) - } - precondition( - it.nextSpan().isEmpty && count == expectedCount, - "Broken Container: count doesn't match contents") - } - - /// Copies the elements of a container into this deque at the specified - /// position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the deque's `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the deque. - /// - /// Existing elements in the deque's storage are moved as needed to make room - /// for the new items. (The direction of the move depends on the location of - /// the insertion, minimizing the cost.) - /// - /// If the deque does not have sufficient capacity to hold enough items, - /// then this reallocates the deque's storage to grow its capacity, using a - /// geometric growth rate. - /// - /// - Parameters: - /// - items: The new elements to insert into the deque. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the deque. - /// - /// - Complexity: O(`self.count` + `items.count`) when amortized over many - /// similar invocations on the same deque. - @available(SwiftStdlib 6.4, *) - @_alwaysEmitIntoClient - @inline(__always) - public mutating func insert< - C: Container & ~Copyable & ~Escapable - >( - copying items: borrowing C, at index: Int - ) { - _insertContainer( - at: index, copying: items, newCount: items.count) - } - - /// Copies the elements of a container into this deque at the specified - /// position. - /// - /// The new elements are inserted before the element currently at the - /// specified index. If you pass the deque's `endIndex` as the `index` - /// parameter, then the new elements are appended to the end of the deque. - /// - /// Existing elements in the deque's storage are moved as needed to make room - /// for the new items. (The direction of the move depends on the location of - /// the insertion, minimizing the cost.) - /// - /// If the deque does not have sufficient capacity to hold enough items, - /// then this reallocates the deque's storage to grow its capacity, using a - /// geometric growth rate. - /// - /// - Parameters: - /// - items: The new elements to insert into the deque. - /// - index: The position at which to insert the new elements. It must be - /// a valid index of the deque. - /// - /// - Complexity: O(`self.count` + `items.count`) when amortized over many - /// similar invocations on the same deque. - @available(SwiftStdlib 6.4, *) - @_alwaysEmitIntoClient - @inline(__always) - public mutating func insert< - C: Container & Collection - >( - copying items: borrowing C, at index: Int - ) { - _insertContainer( - at: index, copying: items, newCount: items.count) - } - - /// Replaces the specified range of elements by at most `newItemCount` items - /// generated by a producer. - /// - /// This method has the effect of removing the specified range of elements - /// from the deque 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 deque doesn't have sufficient capacity to accommodate the new - /// elements, then this method reallocates the deque's storage to grow it, - /// using a geometric growth rate. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the items generated by `producer` at `subrange.lowerBound`. This - /// case is more directly expressed by calling `insert(moving:at:)`. - /// - /// Likewise, if the given producer is empty, then this method removes the - /// elements in the given subrange without replacement. This case is more - /// directly expressed by calling `removeSubrange`. - /// - /// This operation inserts as many items as the producer can generate before - /// either reaching `newItemCount`, or the producer hitting its end, or - /// throwing an error. If the producer has more than `newItemCount` items left in - /// its underlying sequence, then extra items remain available after this - /// method returns. - /// - /// If the operation inserts fewer than `newItemCount` items, then it results in - /// a gap in ring buffer storage that needs to be closed by moving some - /// items to their correct positions given the adjusted count. This adds some - /// overhead compared to adding exactly as many items as promised. - /// - /// - Parameters: - /// - subrange: The subrange of the deque to replace. The bounds of - /// the range must be valid indices in the deque. - /// - newItemCount: The maximum number of items to insert into the deque. - /// - producer: A producer that generates the items to append. - /// - /// - Complexity: O(`self.count` + `newItemCount`) - @_alwaysEmitIntoClient - public mutating func replace< - E: Error, - P: Producer & ~Copyable & ~Escapable - >( - removing subrange: Range, - addingCount newItemCount: Int, - from producer: inout P - ) throws(E) - where P.Element: ~Copyable - { - try replace(removing: subrange, addingCount: newItemCount) { target throws(E) in - while !target.isFull, try producer.generate(into: &target) { - // Do nothing - } - } + return Range(uncheckedBounds: (0, added)) } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueDeque /*where Element: Copyable*/ { /// Copies the elements of a container and prepends them to the front /// of this deque. @@ -436,14 +155,14 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Parameters: /// - items: The new elements to copy into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. - @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient + @discardableResult public mutating func prepend & ~Copyable & ~Escapable>( copying items: borrowing C - ) { + ) -> Range { self._prepend(copying: items, exactCount: items.count) } @@ -454,14 +173,14 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Parameters: /// - items: The new elements to copy into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(*m*), where *m* is the length of `items` when amortized /// over many similar invocations on the same deque. - @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient + @discardableResult public mutating func prepend & Sequence>( copying items: borrowing C - ) { + ) -> Range { self._prepend(copying: items, exactCount: items.count) } @@ -472,117 +191,16 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Parameters: /// - items: The new elements to copy into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(*m*), where *m* is the length of `items` when amortized /// over many similar invocations on the same deque. - @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient + @discardableResult public mutating func prepend & Collection>( copying items: C - ) { + ) -> Range { self._prepend(copying: items, exactCount: items.count) } - - @available(SwiftStdlib 6.4, *) - @inlinable - internal mutating func _replace< - C: Container & ~Copyable & ~Escapable - >( - removing subrange: Range, - copyingContainer items: borrowing C, - newCount: Int - ) { - - let expectedCount = self.count - subrange.count + newCount - var it = items.makeBorrowingIterator() - self.replace(removing: subrange, addingCount: newCount) { target in - it._copyContents(into: &target) - } - precondition( - it.nextSpan().isEmpty && count == expectedCount, - "Broken Container: count doesn't match contents") - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given container. - /// - /// This method has the effect of removing the specified range of elements - /// from the deque 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 deque doesn't have sufficient capacity to accommodate the new - /// elements, then this method reallocates the deque's storage to grow it, - /// using a geometric growth rate. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `items` at `subrange.lowerBound`. This case - /// is more directly expressed by calling `insert(copying:at:)`. - /// - /// Likewise, if you pass a zero-length container as the `items` - /// parameter, this method removes the elements in the given subrange - /// without replacement. This case is more directly expressed by calling - /// `removeSubrange`. - /// - /// - Parameters: - /// - subrange: The subrange of the deque to replace. The bounds of - /// the range must be valid indices in the array. - /// - items: The new elements to copy into the collection. - /// - /// - Complexity: O(`self.count` + `items.count`) - @available(SwiftStdlib 6.4, *) - @inlinable - @inline(__always) - public mutating func replace< - C: Container & ~Copyable & ~Escapable - >( - removing subrange: Range, - copying items: borrowing C - ) { - _replace( - removing: subrange, copyingContainer: items, newCount: items.count) - } - - /// Replaces the specified subrange of elements by copying the elements of - /// the given container. - /// - /// This method has the effect of removing the specified range of elements - /// from the deque 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 deque doesn't have sufficient capacity to accommodate the new - /// elements, then this method reallocates the deque's storage to grow it, - /// using a geometric growth rate. - /// - /// If you pass a zero-length range as the `subrange` parameter, this method - /// inserts the elements of `items` at `subrange.lowerBound`. This case - /// is more directly expressed by calling `insert(copying:at:)`. - /// - /// Likewise, if you pass a zero-length container as the `items` - /// parameter, this method removes the elements in the given subrange - /// without replacement. This case is more directly expressed by calling - /// `removeSubrange`. - /// - /// - Parameters: - /// - subrange: The subrange of the deque to replace. The bounds of - /// the range must be valid indices in the array. - /// - items: The new elements to copy into the collection. - /// - /// - Complexity: O(*n* + *m*), where *n* is count of this deque and - /// *m* is the count of `items`. - @available(SwiftStdlib 6.4, *) - @inlinable - @inline(__always) - public mutating func replace< - C: Container & Collection - >( - removing subrange: Range, - copying items: C - ) { - _replace( - removing: subrange, copyingContainer: items, newCount: items.count) - } } #endif diff --git a/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift b/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift index 164b21b9..56d5bdf0 100644 --- a/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift +++ b/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift @@ -18,7 +18,7 @@ import SpanPreview #if compiler(>=6.4) && UnstableContainersPreview && UnstableHashedContainers -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueSet: Container where Element: ~Copyable { @_alwaysEmitIntoClient public func currentIndex(of iterator: inout BorrowingIterator) -> Index { @@ -47,7 +47,7 @@ extension UniqueSet: DrainableContainer where Element: ~Copyable { } #endif -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension UniqueSet where Element: ~Copyable { @_alwaysEmitIntoClient public init< diff --git a/Sources/ContainersPreview/Protocols/Container/DrainableContainer.swift b/Sources/ContainersPreview/Protocols/Container/DrainableContainer.swift index a0c18c60..ff554c3a 100644 --- a/Sources/ContainersPreview/Protocols/Container/DrainableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/DrainableContainer.swift @@ -29,24 +29,48 @@ where { // MARK: Core requirements - associatedtype SubrangeConsumer: Drain & ~Copyable & ~Escapable + associatedtype SubrangeConsumer: + ContainerDrain & ~Copyable & ~Escapable + where SubrangeConsumer.Index == Index @_lifetime(&self) - mutating func consume(_ subrange: Range) -> SubrangeConsumer + mutating func consumeSubrange(_ subrange: Range) -> SubrangeConsumer + // FIXME: `consumeAll(where:)` // FIXME: `removeAll(where:)` - // FIXME: `consumeAll(where:)`? // These should ideally be using SubrangeConsumer, but that requires Drain // to support partial consumption -- a large complication. // MARK: Requirements with default implementations - mutating func remove(at index: Index) -> Element - mutating func removeSubrange(_ bounds: Range) + /// Removes and returns the element at the specified position. + /// + /// - Parameter index: The position of the element to remove. `index` must be + /// a valid index that is not equal to the end index. + /// On return, `index` is updated to address the position following the + /// removed element. + /// - Returns: The removed element. + @discardableResult + mutating func remove(at index: inout Index) -> Element + + @discardableResult + mutating func consumeSubrange( + _ bounds: Range, + consumingWith consumer: (inout InputSpan) -> Void + ) -> Index + + @discardableResult + mutating func removeSubrange(_ bounds: Range) -> Index + mutating func removeAll() - mutating func removeFirst() -> Element + mutating func removeFirst(_ n: Int) + mutating func _customRemoveLast() -> Element? + + @_lifetime(&self) + mutating func _customConsumeLast(_ n: Int) -> SubrangeConsumer? + mutating func _customRemoveLast(_ n: Int) -> Bool } @@ -57,10 +81,10 @@ extension DrainableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient - public mutating func remove(at index: Index) -> Element { + public mutating func remove(at index: inout Index) -> Element { let range = Range(uncheckedBounds: (index, self.index(after: index))) var result: Element? - self.consume(range) { + index = self.consumeSubrange(range) { result = $0.removeFirst() } guard let result else { @@ -70,16 +94,14 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } @_alwaysEmitIntoClient - public mutating func removeSubrange(_ bounds: Range) { - _ = consume(bounds) + @discardableResult + public mutating func removeSubrange(_ bounds: Range) -> Index { + consumeSubrange(bounds) { _ in } } @_alwaysEmitIntoClient - public mutating func removeFirst() -> Element { - precondition( - !isEmpty, - "Can't remove first element from an empty container") - return self.remove(at: self.startIndex) + public mutating func removeAll() { + removeSubrange(startIndex ..< endIndex) } @_alwaysEmitIntoClient @@ -87,9 +109,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable if n == 0 { return } precondition(n >= 0, "Number of elements to remove should be non-negative") let start = self.startIndex - guard - let end = self.index(start, offsetBy: n, limitedBy: endIndex) - else { + guard let end = self.index(start, offsetBy: n, limitedBy: endIndex) else { preconditionFailure( "Can't remove more items from a container than it has") } @@ -101,6 +121,12 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable nil } + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func _customConsumeLast(_ n: Int) -> SubrangeConsumer? { + nil + } + @_alwaysEmitIntoClient public mutating func _customRemoveLast(_ n: Int) -> Bool { false @@ -113,31 +139,18 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable extension DrainableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @_alwaysEmitIntoClient - public mutating func consume( - _ subrange: Range, - consumingWith consumer: (inout InputSpan) -> Void - ) { - var drain = self.consume(subrange) - while true { - var chunk = drain.drainNext() - guard !chunk.isEmpty else { break } - consumer(&chunk) - } - } - @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consumeAll() -> SubrangeConsumer { - consume(startIndex ..< endIndex) + consumeSubrange(startIndex ..< endIndex) } @_alwaysEmitIntoClient @_lifetime(&self) - public mutating func consume( + public mutating func consumeSubrange( _ subrange: some RangeExpression2 ) -> SubrangeConsumer { - consume(subrange.relative(to: self)) + consumeSubrange(subrange.relative(to: self)) } // This unavailable default implementation of the protocol requirement @@ -146,16 +159,18 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable @available(*, unavailable) @_alwaysEmitIntoClient @_lifetime(&self) - public mutating func consume(_ subrange: Range) -> SubrangeConsumer { + public mutating func consumeSubrange( + _ subrange: Range + ) -> SubrangeConsumer { fatalError() } @_alwaysEmitIntoClient @_lifetime(&self) - public mutating func consume( + public mutating func consumeSubrange( _ subrange: UnboundedRange ) -> SubrangeConsumer { - consume(startIndex ..< endIndex) + consumeAll() } @_alwaysEmitIntoClient @@ -167,7 +182,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable var n = n self.formIndex(&i, offsetBy: &n, limitedBy: self.endIndex) precondition(n == 0, "Count of elements to consume is out of bounds") - return consume(start ..< i) + return consumeSubrange(start ..< i) } } @@ -181,13 +196,68 @@ where @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consumeLast(_ n: Int) -> SubrangeConsumer { + if let drain = self._customConsumeLast(n) { + return drain + } precondition(n >= 0, "Count of elements to consume is out of bounds") let end = self.endIndex var i = end var distance = -n self.formIndex(&i, offsetBy: &distance, limitedBy: self.startIndex) precondition(distance == 0, "Count of elements to consume is out of bounds") - return consume(i ..< end) + return consumeSubrange(i ..< end) + } +} + +@available(SwiftStdlib 6.4, *) +extension DrainableContainer +where Self: ~Copyable & ~Escapable, Element: ~Copyable +{ + /// - Returns: A valid index addressing the position following the consumed + /// subrange. + @_alwaysEmitIntoClient + @discardableResult + public mutating func consumeSubrange( + _ bounds: Range, + consumingWith consumer: (inout InputSpan) -> Void + ) -> Index { + var drain = self.consumeSubrange(bounds) + while true { + var span = drain.drainNext() + guard !span.isEmpty else { break } + consumer(&span) + } + return drain.finalize() + } + + @_alwaysEmitIntoClient + public mutating func consumeAll( + consumingWith consumer: (inout InputSpan) -> Void + ) { + consumeSubrange(startIndex ..< endIndex, consumingWith: consumer) + } + + /// - Returns: A valid index addressing the position following the consumed + /// subrange. + @_alwaysEmitIntoClient + @discardableResult + public mutating func consumeSubrange( + _ subrange: some RangeExpression2, + consumingWith consumer: (inout InputSpan) -> Void + ) -> Index { + consumeSubrange(subrange.relative(to: self), consumingWith: consumer) + } + + /// - Returns: A valid index addressing the position following the consumed + /// subrange. + @_alwaysEmitIntoClient + @discardableResult + public mutating func consumeSubrange( + _ subrange: UnboundedRange, + consumingWith consumer: (inout InputSpan) -> Void + ) -> Index { + consumeAll(consumingWith: consumer) + return self.endIndex } } @@ -196,22 +266,42 @@ extension DrainableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient - public mutating func removeAll() { - removeSubrange(startIndex ..< endIndex) + @inline(always) + @discardableResult + public mutating func remove(at index: Index) -> Element { + var index = index + return remove(at: &index) } @_alwaysEmitIntoClient - public mutating func removeSubrange( - _ bounds: some RangeExpression2 - ) { - removeSubrange(bounds.relative(to: self)) + public mutating func removeFirst() -> Element { + precondition( + !isEmpty, + "Can't remove first element from an empty container") + return self.remove(at: self.startIndex) } + /// - Returns: A valid index addressing the position following the removed + /// subrange. @_alwaysEmitIntoClient + @inline(always) + @discardableResult public mutating func removeSubrange( - _ bounds: UnboundedRange - ) { - removeAll() + _ subrange: some RangeExpression2 + ) -> Index { + self.removeSubrange(subrange.relative(to: self)) + } + + /// - Returns: A valid index addressing the position following the removed + /// subrange. + @_alwaysEmitIntoClient + @inline(always) + @discardableResult + public mutating func removeSubrange( + _ subrange: UnboundedRange + ) -> Index { + self.removeAll() + return self.startIndex } } @@ -257,5 +347,4 @@ where Self: BidirectionalContainer & ~Copyable & ~Escapable, Element: ~Copyable } } - #endif diff --git a/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift b/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift index 08b2b425..b0add86a 100644 --- a/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift @@ -57,6 +57,16 @@ extension DynamicContainer where Self: ~Copyable, Element: ~Copyable { try self.append(addingCount: minimumCapacity, initializingWith: initializer) } + /// Creates a new instance of the container, populating it with all items + /// generated by a given producer. + /// + /// - Parameters: + /// - minimumCapacity: The desired minimum storage capacity, or nil to + /// indicate that the result should be sized automatically. + /// - producer: A producer that generates the items to append to the new + /// deque. + /// + /// - Complexity: O(`capacity`) @_alwaysEmitIntoClient public init< E: Error, diff --git a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift index 6312f5a7..a464290c 100644 --- a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift @@ -31,29 +31,39 @@ where var freeCapacity: Int { get } - mutating func replace( - removing subrange: Range, + /// - Returns: A valid index range addressing the newly inserted items. + @discardableResult + mutating func replaceSubrange( + _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) + ) throws(E) -> Range // MARK: Requirements with default implementations + /// - Returns: A valid index range addressing the newly inserted items. + @discardableResult mutating func insert( addingCount newItemCount: Int, at index: Index, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) + ) throws(E) -> Range - mutating func insert(_ item: consuming Element, at index: Index) + /// - Returns: A valid index addressing the newly inserted item. + @discardableResult + mutating func insert(_ item: consuming Element, at index: Index) -> Index + /// - Returns: A valid index range addressing the newly inserted items. + @discardableResult mutating func append( addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) + ) throws(E) -> Range - mutating func append(_ item: consuming Element) + /// - Returns: A valid index addressing the newly inserted item. + @discardableResult + mutating func append(_ item: consuming Element) -> Index } //MARK: - Default Implementations @@ -63,33 +73,38 @@ extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient + @discardableResult public mutating func insert( addingCount newItemCount: Int, at index: Index, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { - try self.replace( - removing: index ..< index, + ) throws(E) -> Range { + try self.replaceSubrange( + index ..< index, consumingWith: { _ in }, addingCount: newItemCount, initializingWith: initializer) } @_alwaysEmitIntoClient + @discardableResult public mutating func insert( _ item: consuming Element, at index: Index - ) { + ) -> Index { var item: Optional = item - insert(addingCount: 1, at: index) { target in + let range = insert(addingCount: 1, at: index) { target in target.append(item.take()!) } + precondition(!range.isEmpty) + return range.lowerBound } @_alwaysEmitIntoClient + @discardableResult public mutating func append( addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { + ) throws(E) -> Range { try self.insert( addingCount: newItemCount, at: endIndex, @@ -97,7 +112,8 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } @_alwaysEmitIntoClient - public mutating func append(_ item: consuming Element) { + @discardableResult + public mutating func append(_ item: consuming Element) -> Index { insert(item, at: endIndex) } } @@ -143,21 +159,22 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable /// the range must be valid indices in the container. /// - newItemCount: The maximum number of items to insert into the container. /// - producer: A producer that generates the items to insert. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newItemCount`) @_alwaysEmitIntoClient - public mutating func replace< + @discardableResult + public mutating func replaceSubrange< E: Error, P: Producer & ~Copyable & ~Escapable >( - removing subrange: some RangeExpression2, + _ subrange: some RangeExpression2, addingCount newItemCount: Int, from producer: inout P - ) throws(P.Failure) + ) throws(P.Failure) -> Range where P.Element: ~Copyable { - try replace( - removing: subrange.relative(to: self), + try replaceSubrange( + subrange.relative(to: self), consumingWith: { _ in }, addingCount: newItemCount, initializingWith: { target throws(E) in @@ -167,31 +184,31 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } @_alwaysEmitIntoClient - public mutating func replace< + @discardableResult + public mutating func replaceSubrange< E: Error, P: CountedProducer & ~Copyable & ~Escapable >( - removing subrange: some RangeExpression2, + _ subrange: some RangeExpression2, addingFrom producer: consuming P - ) throws(P.Failure) + ) throws(P.Failure) -> Range where P.Element: ~Copyable { - try replace( - removing: subrange, - addingCount: producer.count, - from: &producer) + let range = try replaceSubrange(subrange, addingCount: producer.count, from: &producer) try producer._expectEnd("Invalid Container") + return range } @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: some RangeExpression2, + @discardableResult + public mutating func replaceSubrange( + _ subrange: some RangeExpression2, consumingWith consumer: (inout InputSpan) -> Void, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { - try replace( - removing: subrange.relative(to: self), + ) throws(E) -> Range { + try replaceSubrange( + subrange.relative(to: self), consumingWith: consumer, addingCount: newItemCount, initializingWith: initializer) @@ -202,52 +219,59 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable // satisfying the protocol through the use of the generic algorithm above. @available(*, unavailable) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { + ) throws(E) -> Range { fatalError() } @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: some RangeExpression2, + @discardableResult + public mutating func replaceSubrange( + _ subrange: some RangeExpression2, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { - try replace( - removing: subrange.relative(to: self), + ) throws(E) -> Range { + try replaceSubrange( + subrange.relative(to: self), consumingWith: { _ in }, addingCount: newItemCount, initializingWith: initializer) } @_alwaysEmitIntoClient - public mutating func replace< + @discardableResult + public mutating func replaceSubrange< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( - removing targetSubrange: some RangeExpression2, + _ targetSubrange: some RangeExpression2, moving source: inout C - ) where C.Element: ~Copyable { - replace(removing: targetSubrange, addingFrom: source.consumeAll()) + ) -> Range + where C.Element: ~Copyable { + replaceSubrange(targetSubrange, addingFrom: source.consumeAll()) } @_alwaysEmitIntoClient - public mutating func replace< + @discardableResult + public mutating func replaceSubrange< C: DrainableContainer & ~Copyable & ~Escapable >( - removing targetSubrange: some RangeExpression2, + _ targetSubrange: some RangeExpression2, moving sourceSubrange: some RangeExpression2, from source: inout C - ) where C.Element: ~Copyable { + ) -> Range + where C.Element: ~Copyable { let sourceSubrange = sourceSubrange.relative(to: source) let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) - var producer = source.consume(sourceSubrange) + var producer = source.consumeSubrange(sourceSubrange) let targetSubrange = targetSubrange.relative(to: self) - self.replace(removing: targetSubrange, addingCount: c, from: &producer) + let range = self.replaceSubrange(targetSubrange, addingCount: c, from: &producer) producer._expectEnd("Invalid Container") + return range } /// Replaces the specified range of elements by moving the elements of a @@ -277,13 +301,15 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable /// /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient - public mutating func replace< + @discardableResult + public mutating func replaceSubrange< C: DrainableContainer & ~Copyable & ~Escapable >( - removing targetSubrange: some RangeExpression2, + _ targetSubrange: some RangeExpression2, consuming source: consuming C - ) where C.Element: ~Copyable { - replace(removing: targetSubrange, addingFrom: source.consumeAll()) + ) -> Range + where C.Element: ~Copyable { + replaceSubrange(targetSubrange, addingFrom: source.consumeAll()) } } @@ -312,7 +338,9 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable /// - index: The position at which to insert the new items. /// `index` must be a valid index in the container. /// - producer: A producer that generates the items to append. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient + @discardableResult public mutating func insert< E: Error, P: Producer & ~Copyable & ~Escapable @@ -320,7 +348,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable addingCount newItemCount: Int, from producer: inout P, at index: Index - ) throws(E) + ) throws(E) -> Range where P.Element: ~Copyable { try self.insert(addingCount: newItemCount, at: index) { target throws(E) in @@ -350,56 +378,66 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable /// - index: The position at which to insert the new items. /// `index` must be a valid index in the container. /// - producer: A producer that generates the items to append. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient + @discardableResult public mutating func insert< E: Error, P: CountedProducer & ~Copyable & ~Escapable >( from producer: consuming P, at index: Index - ) throws(E) + ) throws(E) -> Range where P.Element: ~Copyable { let c = producer.count - try self.insert(addingCount: c, at: index) { target throws(E) in + let range = try self.insert(addingCount: c, at: index) { target throws(E) in while !target.isFull, try producer.generate(into: &target) { } } try producer._expectEnd("Invalid Container") + return range } @_alwaysEmitIntoClient + @discardableResult public mutating func insert< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( moving source: inout C, at index: Index - ) where C.Element: ~Copyable { + ) -> Range + where C.Element: ~Copyable { self.insert(from: source.consumeAll(), at: index) } @_alwaysEmitIntoClient + @discardableResult public mutating func insert< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( moving sourceSubrange: some RangeExpression2, from source: inout C, at index: Index - ) where C.Element: ~Copyable { + ) -> Range + where C.Element: ~Copyable { let sourceSubrange = sourceSubrange.relative(to: source) let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) - var producer = source.consume(sourceSubrange) - self.insert(addingCount: c, from: &producer, at: index) + var producer = source.consumeSubrange(sourceSubrange) + let range = self.insert(addingCount: c, from: &producer, at: index) producer._expectEnd("Invalid Container") + return range } @_alwaysEmitIntoClient + @discardableResult public mutating func insert< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( consuming source: consuming C, at index: Index - ) where C.Element: ~Copyable { + ) -> Range + where C.Element: ~Copyable { self.insert(from: source.consumeAll(), at: index) } } @@ -422,14 +460,16 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// - Parameters: /// - newItemCount: The number of items to append to the container. /// - producer: A producer that generates the items to append. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient + @discardableResult public mutating func append< E: Error, P: Producer & ~Copyable & ~Escapable >( addingCount newItemCount: Int, from producer: inout P - ) throws(E) + ) throws(E) -> Range where P.Element: ~Copyable { try insert(addingCount: newItemCount, from: &producer, at: endIndex) @@ -447,17 +487,20 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// /// - Parameters: /// - producer: A producer that generates the items to append. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient + @discardableResult public mutating func append< E: Error, P: CountedProducer & ~Copyable & ~Escapable >( from producer: consuming P - ) throws(E) + ) throws(E) -> Range where P.Element: ~Copyable { - try append(addingCount: producer.count, from: &producer) - try producer._expectEnd("Invalid Container") + let range = try append(addingCount: producer.count, from: &producer) + try producer._expectEnd("Invalid CountedProducer") + return range } /// Moves the elements of a given container into the end of this one, leaving @@ -468,27 +511,33 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// /// - Parameters: /// - items: A container whose contents to move into this container. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient + @discardableResult public mutating func append< - C: RangeReplaceableContainer & ~Copyable & ~Escapable + C: DrainableContainer & ~Copyable & ~Escapable >( moving items: inout C - ) where C.Element: ~Copyable { + ) -> Range + where C.Element: ~Copyable { self.append(from: items.consumeAll()) } @_alwaysEmitIntoClient + @discardableResult public mutating func append< - C: RangeReplaceableContainer & ~Copyable & ~Escapable + C: DrainableContainer & ~Copyable & ~Escapable >( moving sourceSubrange: some RangeExpression2, from source: inout C - ) where C.Element: ~Copyable { + ) -> Range + where C.Element: ~Copyable { let sourceSubrange = sourceSubrange.relative(to: source) let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) - var producer = source.consume(sourceSubrange) - self.append(addingCount: c, from: &producer) + var producer = source.consumeSubrange(sourceSubrange) + let range = self.append(addingCount: c, from: &producer) producer._expectEnd("Invalid Container") + return range } /// Appends the elements of a given container to the end of this one by @@ -499,12 +548,15 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// /// - Parameters: /// - items: A container whose contents to move into this container. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient + @discardableResult public mutating func append< - C: RangeReplaceableContainer & ~Copyable & ~Escapable + C: DrainableContainer & ~Copyable & ~Escapable >( consuming items: consuming C - ) where C.Element: ~Copyable { + ) -> Range + where C.Element: ~Copyable { self.append(from: items.consumeAll()) } } @@ -518,18 +570,22 @@ where Element: Copyable { @_alwaysEmitIntoClient - public mutating func _replaceContainer & ~Copyable & ~Escapable>( - removing subrange: Range, + @discardableResult + public mutating func _replaceContainerSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, copying items: borrowing C - ) { + ) -> Range { var c = items.count var i = items.startIndex - self.replace(removing: subrange, addingCount: c) { target in + let range = self.replaceSubrange(subrange, addingCount: c) { target in let source = items.nextSpan(after: &i, maxCount: target.freeCapacity) target._append(copying: source) c -= source.count } precondition(c == 0, "Invalid RangeReplaceableContainer") + return range } /// Replaces the specified subrange of elements by copying the elements of @@ -556,12 +612,16 @@ where /// - subrange: The subrange of the container to replace. The bounds of /// the range must be valid indices in the container. /// - items: The new elements to copy into the container. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient - public mutating func replace & ~Copyable & ~Escapable>( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange< + C: Container & ~Copyable & ~Escapable + >( + _ subrange: Range, copying items: borrowing C - ) { - _replaceContainer(removing: subrange, copying: items) + ) -> Range { + _replaceContainerSubrange(subrange, copying: items) } /// Replaces the specified subrange of elements by copying the elements of @@ -588,25 +648,28 @@ where /// - subrange: The subrange of the container to replace. The bounds of /// the range must be valid indices in the container. /// - items: The new elements to copy into the container. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient - public mutating func replace>( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange>( + _ subrange: Range, copying items: C - ) { + ) -> Range { var c = items.count - let done: Void? = items.withContiguousStorageIfAvailable { buffer in + let res: Range? = items.withContiguousStorageIfAvailable { buffer in precondition(buffer.count == c, "Broken Collection: mismatching count") var buffer = buffer - self.replace(removing: subrange, addingCount: c) { target in + let res = self.replaceSubrange(subrange, addingCount: c) { target in target._append(copying: buffer._trim(first: target.freeCapacity)) } precondition(buffer.count == 0, "Invalid RangeReplaceableContainer") + return res } - if done != nil { return } + if let res { return res } var it = items.makeIterator() - self.replace(removing: subrange, addingCount: c) { target in + let range = self.replaceSubrange(subrange, addingCount: c) { target in while !target.isFull { guard let item = it.next() else { preconditionFailure("Broken Collection: mismatching count") @@ -617,26 +680,30 @@ where } precondition(it.next() == nil, "Broken Collection") precondition(c == 0, "Invalid RangeReplaceableContainer") + return range } @_alwaysEmitIntoClient - public mutating func replace & Collection>( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange< + C: Container & Collection + >( + _ subrange: Range, copying items: borrowing C - ) { - _replaceContainer(removing: subrange, copying: items) + ) -> Range { + _replaceContainerSubrange(subrange, copying: items) } @_alwaysEmitIntoClient - internal mutating func _insertContainer< + package mutating func _insertContainer< C: Container & ~Copyable & ~Escapable >( addingCount newCount: Int, copying items: borrowing C, at index: Index - ) { + ) -> Range { var it = items.makeBorrowingIterator() - insert(addingCount: newCount, at: index) { target in + let range = insert(addingCount: newCount, at: index) { target in while !target.isFull { let source = it.nextSpan(maxCount: target.freeCapacity) precondition(!source.isEmpty, "Broken container: mismatching count") @@ -644,6 +711,7 @@ where } } precondition(it.nextSpan().isEmpty, "Broken container: mismatching count") + return range } @_alwaysEmitIntoClient @@ -651,22 +719,23 @@ where addingCount newCount: Int, copying items: some Collection, at index: Index - ) { - let done: Void? = items.withContiguousStorageIfAvailable { buffer in + ) -> Range { + let res: Range? = items.withContiguousStorageIfAvailable { buffer in precondition(buffer.count == newCount, "Broken Collection: mismatching count") - self.insert(addingCount: buffer.count, at: index) { target in + return self.insert(addingCount: buffer.count, at: index) { target in target._append(copying: buffer) } } - if done != nil { return } + if let res { return res } var it = items.makeIterator() - self.insert(addingCount: newCount, at: index) { target in + let range = self.insert(addingCount: newCount, at: index) { target in while !target.isFull { guard let item = it.next() else { preconditionFailure() } target.append(item) } } precondition(it.next() == nil, "Broken Collection") + return range } /// Copies the elements of a source container into this container, starting @@ -683,14 +752,16 @@ where /// - items: The new elements to insert into the container. /// - index: The position at which to insert the new elements. It must be /// a valid index of `self`. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func insert< C: Container & ~Copyable & ~Escapable >( copying items: borrowing C, at index: Index - ) { + ) -> Range { _insertContainer( addingCount: items.count, copying: items, at: index) } @@ -709,11 +780,13 @@ where /// - items: The new elements to insert into the container. /// - index: The position at which to insert the new elements. It must be /// a valid index of `self`. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func insert( copying items: some Collection, at index: Index - ) { + ) -> Range { _insertCollection(addingCount: items.count, copying: items, at: index) } @@ -731,27 +804,31 @@ where /// - items: The new elements to insert into the container. /// - index: The position at which to insert the new elements. It must be /// a valid index of `self`. + /// - Returns: A valid index range addressing the newly inserted items. @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func insert< C: Container & Collection >( copying items: borrowing C, at index: Index - ) { + ) -> Range { _insertContainer( addingCount: items.count, copying: items, at: index) } @_alwaysEmitIntoClient + @discardableResult public mutating func append( copying items: Span - ) { - guard !items.isEmpty else { return } + ) -> Range { + guard !items.isEmpty else { return endIndex ..< endIndex } var items = items - append(addingCount: items.count) { target in + let range = append(addingCount: items.count) { target in target._append(copying: items._trim(first: target.freeCapacity)) } precondition(items.isEmpty, "Invalid RangeReplaceableContainer") + return range } @_alwaysEmitIntoClient diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Experimental.swift b/Sources/ContainersPreview/Protocols/Drain/ContainerDrain.swift similarity index 51% rename from Sources/DequeModule/UniqueDeque/UniqueDeque+Experimental.swift rename to Sources/ContainersPreview/Protocols/Drain/ContainerDrain.swift index b2156dc0..74890bc2 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Experimental.swift +++ b/Sources/ContainersPreview/Protocols/Drain/ContainerDrain.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2026 Apple Inc. and the Swift project authors +// Copyright (c) 2024 - 2026 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 @@ -12,26 +12,17 @@ //===----------------------------------------------------------------------===// #if !COLLECTIONS_SINGLE_MODULE -import InternalCollectionsUtilities +import SpanPreview #endif -#if compiler(>=6.2) +#if compiler(>=6.4) && UnstableContainersPreview -#if false // FIXME +@available(SwiftStdlib 5.0, *) +public protocol ContainerDrain: Drain, ~Copyable, ~Escapable +where Element: ~Copyable +{ + associatedtype Index -@_alwaysEmitIntoClient -@_transparent -@_lifetime(borrow self) -public func borrowElement(at index: Int) -> Ref { - _storage.borrowElement(at: index) + consuming func finalize() -> Index } - -@_alwaysEmitIntoClient -@_transparent -@_lifetime(&self) -public mutating func mutateElement(at index: Int) -> MutableRef { - _storage.mutateElement(at: index) -} - -#endif #endif diff --git a/Sources/ContainersPreview/Protocols/Producer/Producer.swift b/Sources/ContainersPreview/Protocols/Producer/Producer.swift index 95e306e2..453cda21 100644 --- a/Sources/ContainersPreview/Protocols/Producer/Producer.swift +++ b/Sources/ContainersPreview/Protocols/Producer/Producer.swift @@ -337,7 +337,7 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { ) throws(Failure) { var c = 1 try skip(by: &c) - precondition(c == 0, message) + precondition(c == 1, message) } } diff --git a/Sources/DequeModule/CMakeLists.txt b/Sources/DequeModule/CMakeLists.txt index e2c6022b..e8d90962 100644 --- a/Sources/DequeModule/CMakeLists.txt +++ b/Sources/DequeModule/CMakeLists.txt @@ -48,7 +48,6 @@ target_sources(${module_name} PRIVATE "RigidDeque/RigidDeque+ContainerOperations.swift" "RigidDeque/RigidDeque+Descriptions.swift" "RigidDeque/RigidDeque+Equatable.swift" - "RigidDeque/RigidDeque+Experimental.swift" "RigidDeque/RigidDeque+Hashable.swift" "RigidDeque/RigidDeque+Initializers.swift" "RigidDeque/RigidDeque+Insertions.swift" @@ -64,7 +63,6 @@ target_sources(${module_name} PRIVATE "UniqueDeque/UniqueDeque+Deprecated.swift" "UniqueDeque/UniqueDeque+Descriptions.swift" "UniqueDeque/UniqueDeque+Equatable.swift" - "UniqueDeque/UniqueDeque+Experimental.swift" "UniqueDeque/UniqueDeque+Hashable.swift" "UniqueDeque/UniqueDeque+Initializers.swift" "UniqueDeque/UniqueDeque+Insertions.swift" diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift index 00ae6bad..52072bdd 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift @@ -97,19 +97,22 @@ extension RigidDeque where Element: ~Copyable { /// - newItemCount: The maximum number of items to append to the deque. /// - body: A callback that gets called at most twice to directly /// populate newly reserved storage within the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`newItemCount`) in addition to the complexity of the callback /// invocations. @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func append( addingCount newItemCount: Int, initializingWith body: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { precondition(newItemCount >= 0, "Cannot append a negative number of items") - guard newItemCount > 0 else { return } + guard newItemCount > 0 else { + return Range(uncheckedBounds: (count, count)) + } precondition(freeCapacity >= newItemCount, "RigidDeque capacity overflow") - try _handle.uncheckedAppend(addingCount: newItemCount, initializingWith: body) + return try _handle.uncheckedAppend(addingCount: newItemCount, initializingWith: body) } } @@ -124,14 +127,15 @@ extension RigidDeque where Element: ~Copyable { /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: UnsafeMutableBufferPointer - ) { + ) -> Range { precondition(items.count <= freeCapacity, "RigidDeque capacity overflow") - _handle.uncheckedAppend(moving: items) + return _handle.uncheckedAppend(moving: items) } #if UnstableContainersPreview @@ -143,16 +147,17 @@ extension RigidDeque where Element: ~Copyable { /// /// - Parameters: /// - items: An input span whose contents need to be appended to this deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: inout InputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.append(moving: source) count = 0 + return unsafe self.append(moving: source) } } #endif @@ -165,16 +170,17 @@ extension RigidDeque where Element: ~Copyable { /// /// - Parameters: /// - items: An output span whose contents need to be appended to this deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: inout OutputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe self.append(moving: source) count = 0 + return unsafe self.append(moving: source) } } } @@ -190,16 +196,17 @@ extension RigidDeque /*where Element: Copyable*/ { /// - Parameters: /// - items: A fully initialized buffer whose contents to copy into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( copying items: UnsafeBufferPointer - ) { + ) -> Range { precondition( items.count <= freeCapacity, "RigidDeque capacity overflow") - _handle.uncheckedAppend(copying: items) + return _handle.uncheckedAppend(copying: items) } /// Copies the elements of a buffer and append them to the end of this @@ -211,12 +218,13 @@ extension RigidDeque /*where Element: Copyable*/ { /// - Parameters: /// - items: A fully initialized buffer whose contents to copy into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func append( copying items: UnsafeMutableBufferPointer - ) { + ) -> Range { unsafe self.append(copying: UnsafeBufferPointer(items)) } @@ -227,10 +235,11 @@ extension RigidDeque /*where Element: Copyable*/ { /// /// - Parameters: /// - items: A span whose contents to copy into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient - public mutating func append(copying items: Span) { + @discardableResult + public mutating func append(copying items: Span) -> Range { items.withUnsafeBufferPointer { source in unsafe self.append(copying: source) } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift index 6d853007..25cf8507 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift @@ -35,18 +35,20 @@ extension RigidDeque where Element: ~Copyable { /// - Parameter subrange: The subrange of items to consume from this deque. /// - Parameter consumer: A function taking an input span of removed items, /// allowing them to be consumed straight out of the deque's storage. - /// + /// - Returns: A valid index addressing the position following the consumed + /// range. /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient - @inline(__always) - public mutating func consume( + @discardableResult + public mutating func consumeSubrange( _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void - ) { + ) -> Index { _checkValidBounds(subrange) let segments = self._handle.mutableSegments(forOffsets: subrange) - var span = InputSpan(buffer: segments.first, initializedCount: segments.first.count) + var span = InputSpan( + buffer: segments.first, initializedCount: segments.first.count) consumer(&span) _ = consume span @@ -56,6 +58,7 @@ extension RigidDeque where Element: ~Copyable { _ = consume span } _handle.closeGap(offsets: subrange) + return subrange.lowerBound } /// Remove the specified subrange of items from this deque, @@ -72,15 +75,17 @@ extension RigidDeque where Element: ~Copyable { /// - Parameter subrange: The subrange of items to consume from this deque. /// - Parameter consumer: A function taking an input span of the removed items, /// allowing them to be consumed straight out of the deque's storage. - /// + /// - Returns: A valid index addressing the position following the consumed + /// range. /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient @inline(__always) - public mutating func consume>( + @discardableResult + public mutating func consumeSubrange>( _ subrange: R, consumingWith consumer: (inout InputSpan) -> Void - ) { - consume(subrange.relative(to: indices), consumingWith: consumer) + ) -> Index { + consumeSubrange(subrange.relative(to: indices), consumingWith: consumer) } /// Remove all items currently in this deque, passing a series of input @@ -101,7 +106,7 @@ extension RigidDeque where Element: ~Copyable { public mutating func consumeAll( consumingWith consumer: (inout InputSpan) -> Void ) { - consume(indices, consumingWith: consumer) + consumeSubrange(indices, consumingWith: consumer) } /// Remove the specified number of items from the end of this deque, @@ -130,7 +135,7 @@ extension RigidDeque where Element: ~Copyable { precondition( n >= 0 && n <= self.count, "Count of elements to consume is out of bounds") - consume(self.count &- n ..< self.count, consumingWith: consumer) + consumeSubrange(self.count &- n ..< self.count, consumingWith: consumer) } /// Remove the specified number of items from the front of this deque, @@ -159,7 +164,7 @@ extension RigidDeque where Element: ~Copyable { precondition( n >= 0 && n <= self.count, "Count of elements to consume is out of bounds") - consume(0 ..< n, consumingWith: consumer) + consumeSubrange(0 ..< n, consumingWith: consumer) } #endif } @@ -171,7 +176,9 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) @_lifetime(&self) - public mutating func consume(_ subrange: Range) -> SubrangeConsumer { + public mutating func consumeSubrange( + _ subrange: Range + ) -> SubrangeConsumer { SubrangeConsumer(_base: &self, offsetRange: subrange) } } @@ -223,6 +230,8 @@ extension RigidDeque where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidDeque.SubrangeConsumer where Element: ~Copyable { + public typealias Index = Int + @inlinable public var count: Int { _buffer1.count + _buffer2.count @@ -243,6 +252,11 @@ extension RigidDeque.SubrangeConsumer where Element: ~Copyable { InputSpan(buffer: buffer, initializedCount: buffer.count), mutating: &self) } + + @inlinable + public consuming func finalize() -> Int { + _offsetRange.lowerBound + } } #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Deprecations.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Deprecations.swift new file mode 100644 index 00000000..a9a4687d --- /dev/null +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Deprecations.swift @@ -0,0 +1,307 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2026 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 +// +// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception +// +//===----------------------------------------------------------------------===// + +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +import SpanPreview +#endif + +#if compiler(>=6.2) + +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: ~Copyable { + /// Grow or shrink the capacity of a rigid deque instance without discarding + /// its contents. + /// + /// This operation replaces the deque's storage buffer with a newly allocated + /// buffer of the specified capacity, moving all existing elements + /// to its new storage. The old storage is then deallocated. + /// + /// - Parameter newCapacity: The desired new capacity. `newCapacity` must be + /// greater than or equal to the current count. + /// + /// - Complexity: O(`count`) + @available(*, deprecated, renamed: "setCapacity(_:)") + @_alwaysEmitIntoClient + public mutating func reallocate(capacity newCapacity: Int) { + _handle.reallocate(capacity: newCapacity) + } + + /// Replaces the specified range of elements by a given count of new items, + /// using a callback to directly initialize deque storage by populating + /// a series of output spans. + /// + /// This method has the same overall effect as calling + /// + /// try deque.removeSubrange(subrange) + /// try deque.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the deque twice. + /// + /// If the capacity of the deque isn't sufficient to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// The newly inserted items are not guaranteed to form a single contiguous + /// storage region. Therefore, the supplied callback may be invoked multiple + /// times to initialize each successive chunk of storage. However, invocations + /// cease if the callback fails to fully populate its output span or if + /// it throws an error. In such cases, the deque keeps all items that were + /// successfully initialized before the callback terminated the replacement. + /// + /// Partial insertions create a gap in ring buffer storage that needs to be + /// closed by moving newly inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - initializer: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations. + @available(*, deprecated, renamed: "replaceSubrange(_:addingCount:initializingWith:)") + @inlinable + public mutating func replace( + removing subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + try replaceSubrange( + subrange, addingCount: newItemCount, initializingWith: initializer) + } + + /// 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 deque 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 deque 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 `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + moving items: UnsafeMutableBufferPointer, + ) { + replaceSubrange(subrange, moving: items) + } + + /// Replaces the specified range of elements by moving the contents of an + /// output span into their place. On return, the span is left empty. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque 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 deque 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 `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: An output span whose contents are to be moved into the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + moving items: inout OutputSpan + ) { + } +} + +@available(SwiftStdlib 5.0, *) +extension RigidDeque /* where Element: Copyable */ { + /// 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 deque 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 deque 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 `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") + @inlinable + public mutating func replace( + removing subrange: Range, + copying items: UnsafeBufferPointer + ) { + replaceSubrange(subrange, copying: items) + } + + /// 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 deque 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 deque 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 `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") + @inlinable + public mutating func replace( + removing subrange: Range, + copying items: UnsafeMutableBufferPointer + ) { + replaceSubrange(subrange, copying: items) + } + + /// 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 deque 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 deque 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 `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length span as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") + @inlinable + public mutating func replace( + removing subrange: Range, + copying items: Span + ) { + replaceSubrange(subrange, copying: items) + } + + /// 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 deque 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 `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length collection as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") + @inlinable + @inline(__always) + public mutating func replace( + removing subrange: Range, + copying items: __owned some Collection + ) { + replaceSubrange(subrange, copying: items) + } +} + +#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Experimental.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Experimental.swift deleted file mode 100644 index 33c8006e..00000000 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Experimental.swift +++ /dev/null @@ -1,43 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2026 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 -// -// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception -// -//===----------------------------------------------------------------------===// - -#if !COLLECTIONS_SINGLE_MODULE -import InternalCollectionsUtilities -#endif - -#if compiler(>=6.2) - -#if false // FIXME -@available(SwiftStdlib 5.0, *) -extension RigidDeque where Element: ~Copyable { - @_alwaysEmitIntoClient - @_transparent - @_lifetime(borrow self) - public func borrowElement(at index: Int) -> Ref { - _checkItemIndex(index) - let slot = _handle.slot(forOffset: index) - return Ref(unsafeAddress: _handle.ptr(at: slot), borrowing: self) - } - - @_alwaysEmitIntoClient - @_transparent - @_lifetime(&self) - public mutating func mutateElement(at index: Int) -> MutableRef { - _checkItemIndex(index) - let slot = _handle.slot(forOffset: index) - return MutableRef(unsafeAddress: _handle.mutablePtr(at: slot), mutating: &self) - } -} -#endif - -#endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift index 99fc0b69..96e3b01b 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift @@ -36,14 +36,15 @@ extension RigidDeque where Element: ~Copyable { /// - Parameter item: The new element to insert into the deque. /// - Parameter index: The position at which to insert the new element. /// `index` must be a valid index in the deque. - /// + /// - Returns: A valid index to the newly inserted item. /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient @inline(__always) - public mutating func insert(_ item: consuming Element, at index: Int) { + @discardableResult + public mutating func insert(_ item: consuming Element, at index: Int) -> Int { precondition(!isFull, "RigidDeque capacity overflow") _checkValidIndex(index) - _handle.uncheckedInsert(item, at: index) + return _handle.uncheckedInsert(item, at: index) } } @@ -90,21 +91,22 @@ extension RigidDeque where Element: ~Copyable { /// - initializer: A callback that gets called at most twice to directly /// populate newly reserved storage within the deque. The function /// is always called with an empty output span. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity /// of the callback invocations. @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func insert( addingCount newItemCount: Int, at index: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { + ) throws(E) -> Range { _checkValidIndex(index) precondition(newItemCount >= 0, "Cannot add a negative number of items") - guard newItemCount > 0 else { return } + guard newItemCount > 0 else { return index ..< index } precondition(newItemCount <= freeCapacity, "RigidDeque capacity overflow") - try _handle.uncheckedInsert( + return try _handle.uncheckedInsert( addingCount: newItemCount, at: index, initializingWith: initializer) } } @@ -127,16 +129,17 @@ extension RigidDeque where Element: ~Copyable { /// the deque. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: UnsafeMutableBufferPointer, at index: Int - ) { - guard !items.isEmpty else { return } + ) -> Range { + guard !items.isEmpty else { return index ..< index } var remainder = items - insert(addingCount: items.count, at: index) { target in + let range = insert(addingCount: items.count, at: index) { target in target.withUnsafeMutableBufferPointer { buffer, count in buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) @@ -144,6 +147,7 @@ extension RigidDeque where Element: ~Copyable { } } assert(remainder.isEmpty) + return range } #if UnstableContainersPreview @@ -162,17 +166,18 @@ extension RigidDeque where Element: ~Copyable { /// the deque. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: inout InputSpan, at index: Int - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.insert(moving: source, at: index) count = 0 + return unsafe self.insert(moving: source, at: index) } } #endif @@ -192,17 +197,18 @@ extension RigidDeque where Element: ~Copyable { /// the deque. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: inout OutputSpan, at index: Int - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe self.insert(moving: source, at: index) count = 0 + return unsafe self.insert(moving: source, at: index) } } } @@ -228,15 +234,16 @@ extension RigidDeque /* where Element: Copyable */ { /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be /// a valid index of `self`. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `items.count`) @inlinable + @discardableResult public mutating func insert( copying items: UnsafeBufferPointer, at index: Int - ) { - guard items.count > 0 else { return } + ) -> Range { + guard items.count > 0 else { return index ..< index } var remainder = items - insert(addingCount: remainder.count, at: index) { target in + let range = insert(addingCount: remainder.count, at: index) { target in target.withUnsafeMutableBufferPointer { buffer, count in buffer.initializeAll( fromContentsOf: remainder._extracting(first: buffer.count)) @@ -245,6 +252,7 @@ extension RigidDeque /* where Element: Copyable */ { } } assert(remainder.isEmpty) + return range } /// Copies the elements of a fully initialized buffer pointer into this @@ -266,13 +274,14 @@ extension RigidDeque /* where Element: Copyable */ { /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be /// a valid index of `self`. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `items.count`) @inlinable + @discardableResult public mutating func insert( copying items: UnsafeMutableBufferPointer, at index: Int - ) { + ) -> Range { unsafe self.insert(copying: UnsafeBufferPointer(items), at: index) } @@ -293,12 +302,13 @@ extension RigidDeque /* where Element: Copyable */ { /// - items: The new elements to insert into the deque. /// - index: The position at which to insert the new elements. It must be /// a valid index of the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `items.count`) @inlinable + @discardableResult public mutating func insert( copying items: Span, at index: Int - ) { + ) -> Range { items.withUnsafeBufferPointer { unsafe self.insert(copying: $0, at: index) } @@ -309,21 +319,23 @@ extension RigidDeque /* where Element: Copyable */ { at index: Int, copying items: some Collection, newCount: Int - ) { - let done: Void? = items.withContiguousStorageIfAvailable { src in + ) -> Range { + let res: Range? = items.withContiguousStorageIfAvailable { src in self.insert(copying: src, at: index) } - if done != nil { return } + if let res { return res } var i = items.startIndex - self.insert(addingCount: newCount, at: index) { target in + let range = self.insert(addingCount: newCount, at: index) { target in while !target.isFull { target.append(items[i]) items.formIndex(after: &i) } } - precondition(i == items.endIndex, - "Broken Collection: count doesn't match contents") + precondition( + i == items.endIndex, + "Broken Collection: count doesn't match contents") + return range } /// Copies the elements of a collection into this deque at the specified @@ -344,13 +356,14 @@ extension RigidDeque /* where Element: Copyable */ { /// - items: The new elements to insert into the deque. /// - index: The position at which to insert the new elements. It must be /// a valid index of the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `newElements.count`) @inlinable @inline(__always) + @discardableResult public mutating func insert( copying items: some Collection, at index: Int - ) { + ) -> Range { _insertCollection( at: index, copying: items, newCount: items.count) } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift index 98c2aac7..48b7f458 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift @@ -43,7 +43,6 @@ extension RigidDeque where Element: ~Copyable { /// /// - Parameter item: The element to prepend to the deque. /// - Returns: `item` if the deque is full; otherwise nil. - /// /// - Complexity: O(1) @_alwaysEmitIntoClient @_transparent @@ -102,18 +101,20 @@ extension RigidDeque where Element: ~Copyable { /// - newItemCount: The maximum number of items to prepend to the deque. /// - body: A callback that gets called at most twice to directly /// populate newly reserved storage within the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`newItemCount`) in addition to the complexity of the callback /// invocations. @_alwaysEmitIntoClient + @discardableResult public mutating func prepend( addingCount newItemCount: Int, initializingWith body: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { precondition(newItemCount >= 0, "Cannot prepend a negative number of items") - guard newItemCount > 0 else { return } + guard newItemCount > 0 else { return 0 ..< 0 } precondition(freeCapacity >= newItemCount, "RigidDeque capacity overflow") - try _handle.uncheckedPrepend(addingCount: newItemCount, initializingWith: body) + return try _handle.uncheckedPrepend( + addingCount: newItemCount, initializingWith: body) } } @@ -128,15 +129,16 @@ extension RigidDeque where Element: ~Copyable { /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func prepend( moving items: UnsafeMutableBufferPointer - ) { + ) -> Range { precondition(items.count <= freeCapacity, "RigidDeque capacity overflow") - _handle.uncheckedPrepend(moving: items) + return _handle.uncheckedPrepend(moving: items) } #if UnstableContainersPreview @@ -148,16 +150,17 @@ extension RigidDeque where Element: ~Copyable { /// /// - Parameters: /// - items: An input span whose contents need to be prepended to this deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func prepend( moving items: inout InputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.prepend(moving: source) count = 0 + return unsafe self.prepend(moving: source) } } #endif @@ -170,16 +173,17 @@ extension RigidDeque where Element: ~Copyable { /// /// - Parameters: /// - items: An output span whose contents need to be prepended to this deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient + @discardableResult public mutating func prepend( moving items: inout OutputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe self.prepend(moving: source) count = 0 + return unsafe self.prepend(moving: source) } } } @@ -195,17 +199,18 @@ extension RigidDeque /*where Element: Copyable*/ { /// - Parameters: /// - items: A fully initialized buffer whose contents to copy into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @inlinable @_alwaysEmitIntoClient + @discardableResult public mutating func prepend( copying items: UnsafeBufferPointer - ) { + ) -> Range { precondition( items.count <= freeCapacity, "RigidDeque capacity overflow") - _handle.uncheckedPrepend(copying: items) + return _handle.uncheckedPrepend(copying: items) } /// Copies the elements of a buffer and prepend them to the front of this @@ -217,13 +222,14 @@ extension RigidDeque /*where Element: Copyable*/ { /// - Parameters: /// - items: A fully initialized buffer whose contents to copy into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @inlinable @_alwaysEmitIntoClient + @discardableResult public mutating func prepend( copying items: UnsafeMutableBufferPointer - ) { + ) -> Range { unsafe self.prepend(copying: UnsafeBufferPointer(items)) } @@ -234,11 +240,12 @@ extension RigidDeque /*where Element: Copyable*/ { /// /// - Parameters: /// - items: A span whose contents to copy into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) @inlinable @_alwaysEmitIntoClient - public mutating func prepend(copying items: Span) { + @discardableResult + public mutating func prepend(copying items: Span) -> Range { items.withUnsafeBufferPointer { source in unsafe self.prepend(copying: source) } @@ -272,10 +279,10 @@ extension RigidDeque /*where Element: Copyable*/ { >( copying items: borrowing S, exactCount: Int - ) throws(S.Failure) + ) throws(S.Failure) -> Range where S.Element == Element { var it = items.makeBorrowingIterator() - try self.prepend(addingCount: exactCount) { (target) throws(S.Failure) in + return try self.prepend(addingCount: exactCount) { (target) throws(S.Failure) in let span = try it.nextSpan(maxCount: target.freeCapacity) target._append(copying: span) } @@ -360,18 +367,18 @@ extension RigidDeque /*where Element: Copyable*/ { /// - Complexity: O(`items.count`) @inlinable @_alwaysEmitIntoClient + @discardableResult public mutating func prepend( copying items: some Collection - ) { - let done: Void? = items.withContiguousStorageIfAvailable { source in - unsafe self.prepend(copying: source) - return + ) -> Range { + let res: Range? = items.withContiguousStorageIfAvailable { source in + return unsafe self.prepend(copying: source) } - guard done == nil else { return } + if let res { return res } let c = items.count - guard c > 0 else { return } + guard c > 0 else { return 0 ..< 0 } precondition(c <= freeCapacity, "RigidDeque capacity overflow") - _handle.uncheckedPrepend(copying: items, exactCount: c) + return _handle.uncheckedPrepend(copying: items, exactCount: c) } #if compiler(>=6.4) @@ -404,9 +411,10 @@ extension RigidDeque /*where Element: Copyable*/ { /// - Complexity: O(*m*), where *m* is the length of `items`. @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient + @discardableResult public mutating func prepend>( copying items: borrowing S - ) throws(S.Failure) + ) throws(S.Failure) -> Range where S.Element == Element { try self._prepend(copying: items, exactCount: items.count) } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift index 305927bb..4ae2b20e 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift @@ -19,6 +19,26 @@ import InternalCollectionsUtilities @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: ~Copyable { + /// Removes and returns the element at the specified position. + /// + /// Existing elements in the deque's storage are moved as needed to close the + /// gap left by the removed item. (The direction of the move depends on the + /// location of the removal, minimizing the cost.) + /// + /// - Parameter index: The position of the element to remove. `index` must be + /// a valid index of the deque that is not equal to the end index. + /// On return, `index` is updated to address the position following the + /// removed element. + /// - Returns: The removed element. + /// + /// - Complexity: O(`count`) + @discardableResult + @_alwaysEmitIntoClient + @inline(__always) + public mutating func remove(at index: inout Int) -> Element { + remove(at: index) + } + /// Removes and returns the element at the specified position. /// /// Existing elements in the deque's storage are moved as needed to close the @@ -36,7 +56,7 @@ extension RigidDeque where Element: ~Copyable { _checkItemIndex(index) return _handle.uncheckedRemove(at: index) } - + /// Removes all elements from the deque, preserving its allocated capacity. /// /// - Complexity: O(`count`) @@ -127,14 +147,16 @@ extension RigidDeque where Element: ~Copyable { /// /// - Parameter bounds: The subrange to remove. The bounds of the /// range must be valid indices of the deque. - /// + /// - Returns: A valid index addressing the position following the removed + /// subrange. /// - Complexity: O(`count`) @_alwaysEmitIntoClient - public mutating func removeSubrange(_ bounds: Range) { + @discardableResult + public mutating func removeSubrange(_ bounds: Range) -> Int { precondition( bounds.lowerBound >= 0 && bounds.upperBound <= count, "Subrange out of bounds") - _handle.uncheckedRemove(offsets: bounds) + return _handle.uncheckedRemove(offsets: bounds) } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift index d20a8083..a7034356 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift @@ -57,22 +57,23 @@ extension RigidDeque where Element: ~Copyable { /// - initializer: A callback that gets called at most twice to directly /// populate newly reserved storage within the deque. The function /// is always called with an empty output span. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity /// of the callback invocations. - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { _checkValidBounds(subrange) precondition(newItemCount >= 0, "Cannot add a negative number of items") precondition( count - subrange.count + newItemCount <= capacity, "RigidDeque capacity overflow") - try _handle.uncheckedReplace( - removing: subrange, + return try _handle.uncheckedReplaceSubrange( + subrange, addingCount: newItemCount, initializingWith: initializer) } @@ -131,23 +132,24 @@ extension RigidDeque where Element: ~Copyable { /// - initializer: A callback that gets called at most twice to directly /// populate newly reserved storage within the deque. The function /// is always called with an empty output span. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newItemCount`) in addition to the /// complexity of the callback invocations. - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { _checkValidBounds(subrange) precondition(newItemCount >= 0, "Cannot add a negative number of items") precondition( count - subrange.count + newItemCount <= capacity, "RigidDeque capacity overflow") - try _handle.uncheckedReplace( - removing: subrange, + return try _handle.uncheckedReplaceSubrange( + subrange, consumingWith: consumer, addingCount: newItemCount, initializingWith: initializer) @@ -183,15 +185,16 @@ extension RigidDeque where Element: ~Copyable { /// the range must be valid indices in the deque. /// - items: A fully initialized buffer whose contents to move into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving items: UnsafeMutableBufferPointer, - ) { + ) -> Range { var remainder = items - replace(removing: subrange, addingCount: remainder.count) { target in + let range = replaceSubrange(subrange, addingCount: remainder.count) { target in target.withUnsafeMutableBufferPointer { buffer, count in buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) @@ -199,6 +202,7 @@ extension RigidDeque where Element: ~Copyable { } } assert(remainder.isEmpty) + return range } #if UnstableContainersPreview @@ -226,17 +230,18 @@ extension RigidDeque where Element: ~Copyable { /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. /// - items: An input span whose contents are to be moved into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving items: inout InputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.replace(removing: subrange, moving: source) count = 0 + return unsafe self.replaceSubrange(subrange, moving: source) } } #endif @@ -265,17 +270,18 @@ extension RigidDeque where Element: ~Copyable { /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the deque. /// - items: An output span whose contents are to be moved into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving items: inout OutputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe self.replace(removing: subrange, moving: source) count = 0 + return unsafe self.replaceSubrange(subrange, moving: source) } } } @@ -306,21 +312,23 @@ extension RigidDeque /* where Element: Copyable */ { /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. /// - items: The new elements to copy into the collection. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying items: UnsafeBufferPointer - ) { + ) -> Range { var remainder = items - replace(removing: subrange, addingCount: remainder.count) { target in + let range = replaceSubrange(subrange, addingCount: remainder.count) { target in target.withUnsafeMutableBufferPointer { dst, dstCount in dst.initializeAll(fromContentsOf: remainder._trim(first: dst.count)) dstCount += dst.count } } assert(remainder.isEmpty) + return range } /// Replaces the specified subrange of elements by copying the elements of @@ -347,16 +355,15 @@ extension RigidDeque /* where Element: Copyable */ { /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. /// - items: The new elements to copy into the collection. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying items: UnsafeMutableBufferPointer - ) { - unsafe self.replace( - removing: subrange, - copying: UnsafeBufferPointer(items)) + ) -> Range { + unsafe self.replaceSubrange(subrange, copying: UnsafeBufferPointer(items)) } /// Replaces the specified subrange of elements by copying the elements of @@ -383,34 +390,35 @@ extension RigidDeque /* where Element: Copyable */ { /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. /// - items: The new elements to copy into the collection. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying items: Span - ) { + ) -> Range { items.withUnsafeBufferPointer { buffer in - unsafe self.replace(removing: subrange, copying: buffer) + unsafe self.replaceSubrange(subrange, copying: buffer) } } - @inlinable - internal mutating func _replace( - removing subrange: Range, + @_alwaysEmitIntoClient + internal mutating func _replaceSubrange( + _ subrange: Range, copyingCollection items: __owned some Collection, newCount: Int - ) { - let done: Void? = items.withContiguousStorageIfAvailable { src in + ) -> Range { + let res: Range? = items.withContiguousStorageIfAvailable { src in precondition( src.count == newCount, "Broken Collection: count doesn't match contents") - self.replace(removing: subrange, copying: src) + return self.replaceSubrange(subrange, copying: src) } - if done != nil { return } + if let res { return res } var i = items.startIndex - self.replace(removing: subrange, addingCount: newCount) { target in + let range = self.replaceSubrange(subrange, addingCount: newCount) { target in while !target.isFull { target.append(items[i]) items.formIndex(after: &i) @@ -419,6 +427,7 @@ extension RigidDeque /* where Element: Copyable */ { precondition( i == items.endIndex, "Broken Collection: count doesn't match contents") + return range } /// Replaces the specified subrange of elements by copying the elements of @@ -445,16 +454,16 @@ extension RigidDeque /* where Element: Copyable */ { /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. /// - items: The new elements to copy into the collection. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) - @inlinable + @_alwaysEmitIntoClient @inline(__always) - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying items: __owned some Collection - ) { - _replace( - removing: subrange, copyingCollection: items, newCount: items.count) + ) -> Range { + _replaceSubrange(subrange, copyingCollection: items, newCount: items.count) } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque.swift b/Sources/DequeModule/RigidDeque/RigidDeque.swift index 7eeb6e67..f740ab87 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque.swift @@ -334,8 +334,8 @@ extension RigidDeque where Element: ~Copyable { /// greater than or equal to the current count. /// /// - Complexity: O(`count`) - @_alwaysEmitIntoClient - public mutating func reallocate(capacity newCapacity: Int) { + @inlinable + public mutating func setCapacity(_ newCapacity: Int) { _handle.reallocate(capacity: newCapacity) } @@ -350,7 +350,7 @@ extension RigidDeque where Element: ~Copyable { @inlinable public mutating func reserveCapacity(_ n: Int) { guard capacity < n else { return } - reallocate(capacity: n) + setCapacity(n) } } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift index 31b12a61..79a0766d 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift @@ -80,19 +80,20 @@ extension UniqueDeque where Element: ~Copyable { /// - newItemCount: The maximum number of items to append to the deque. /// - body: A callback that gets called at most twice to directly /// populate newly reserved storage within the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`newItemCount`) in addition to the complexity of the callback /// invocations, when amortized over many similar invocations on the same /// deque. @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func append( addingCount newItemCount: Int, initializingWith body: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { - guard newItemCount > 0 else { return } + ) throws(E) -> Range { + guard newItemCount > 0 else { return count ..< count } _ensureFreeCapacity(newItemCount) - try _storage._handle.uncheckedAppend( + return try _storage._handle.uncheckedAppend( addingCount: newItemCount, initializingWith: body) } } @@ -109,15 +110,16 @@ extension UniqueDeque where Element: ~Copyable { /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: UnsafeMutableBufferPointer - ) { + ) -> Range { _ensureFreeCapacity(items.count) - _storage._handle.uncheckedAppend(moving: items) + return _storage._handle.uncheckedAppend(moving: items) } #if UnstableContainersPreview @@ -130,17 +132,18 @@ extension UniqueDeque where Element: ~Copyable { /// /// - Parameters: /// - items: An input span whose contents need to be appended to this deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: inout InputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.append(moving: source) count = 0 + return unsafe self.append(moving: source) } } #endif @@ -154,17 +157,18 @@ extension UniqueDeque where Element: ~Copyable { /// /// - Parameters: /// - items: An output span whose contents need to be appended to this deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient + @discardableResult public mutating func append( moving items: inout OutputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe self.append(moving: source) count = 0 + return unsafe self.append(moving: source) } } } @@ -182,15 +186,16 @@ extension UniqueDeque /*where Element: Copyable*/ { /// - Parameters: /// - items: A fully initialized buffer whose contents to copy into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient + @discardableResult public mutating func append( copying items: UnsafeBufferPointer - ) { + ) -> Range { _ensureFreeCapacity(items.count) - unsafe _storage.append(copying: items) + return unsafe _storage.append(copying: items) } /// Copies the elements of a buffer to the end of this deque. @@ -202,13 +207,14 @@ extension UniqueDeque /*where Element: Copyable*/ { /// - Parameters: /// - items: A fully initialized buffer whose contents to copy into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient + @discardableResult public mutating func append( copying items: UnsafeMutableBufferPointer - ) { + ) -> Range { unsafe self.append(copying: UnsafeBufferPointer(items)) } @@ -220,13 +226,14 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Parameters: /// - items: A span whose contents to copy into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient - public mutating func append(copying items: Span) { + @discardableResult + public mutating func append(copying items: Span) -> Range { _ensureFreeCapacity(items.count) - _storage.append(copying: items) + return _storage.append(copying: items) } #if compiler(>=6.4) diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift index 146ca2b0..a4f44a64 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift @@ -39,11 +39,11 @@ extension UniqueDeque where Element: ~Copyable { /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient @inline(__always) - public mutating func consume( + public mutating func consumeSubrange( _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void ) { - _storage.consume(subrange, consumingWith: consumer) + _storage.consumeSubrange(subrange, consumingWith: consumer) } /// Remove the specified subrange of items from this deque, @@ -64,11 +64,11 @@ extension UniqueDeque where Element: ~Copyable { /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient @inline(__always) - public mutating func consume>( + public mutating func consumeSubrange>( _ subrange: R, consumingWith consumer: (inout InputSpan) -> Void ) { - consume(subrange.relative(to: indices), consumingWith: consumer) + consumeSubrange(subrange.relative(to: indices), consumingWith: consumer) } /// Remove all items currently in this deque, passing a series of input @@ -89,7 +89,7 @@ extension UniqueDeque where Element: ~Copyable { public mutating func consumeAll( consumingWith consumer: (inout InputSpan) -> Void ) { - consume(indices, consumingWith: consumer) + consumeSubrange(indices, consumingWith: consumer) } /// Remove the specified number of items from the end of this deque, @@ -155,10 +155,10 @@ extension UniqueDeque where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) @_lifetime(&self) - public mutating func consume( + public mutating func consumeSubrange( _ subrange: Range ) -> SubrangeConsumer { - _storage.consume(subrange) + _storage.consumeSubrange(subrange) } } #endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Deprecated.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Deprecated.swift index d2abb396..06d20d0c 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Deprecated.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Deprecated.swift @@ -22,6 +22,311 @@ extension UniqueDeque where Element: ~Copyable { public init(capacity: Int) { _storage = .init(capacity: capacity) } + + /// Grow or shrink the capacity of this deque instance without discarding + /// its contents. + /// + /// This operation replaces the deque's storage buffer with a newly allocated + /// buffer of the specified capacity, moving all existing elements + /// to its new storage. The old storage is then deallocated. + /// + /// - Parameter capacity: The desired new capacity. `capacity` must be + /// greater than or equal to the current count. + /// + /// - Complexity: O(`count`) + @available(*, deprecated, renamed: "setCapacity(_:)") + @inlinable + public mutating func reallocate(capacity: Int) { + _storage.setCapacity(capacity) + } + + /// Replaces the specified range of elements by a given count of new items, + /// using a callback to directly initialize deque storage by populating + /// a series of output spans. + /// + /// The number of new elements need not match the number of elements being + /// removed. + /// + /// This method has the same overall effect as calling + /// + /// try deque.consume(subrange, consumingWith: consumer) + /// try deque.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the deque twice. + /// + /// If the deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// Neither the removed nor the newly inserted items are guaranteed to form a + /// single contiguous storage region. Therefore, the supplied callbacks may be + /// invoked multiple times to consume, then initialize successive chunks of + /// storage. Calls to `consumer` do not get interleaved with calls to + /// `initializer`: no new item is inserted until every replaced item has been + /// fully consumed. + /// + /// The `consumer` callback is not required to fully depopulate its input + /// span. Any items the callback leaves in the span still get removed and + /// discarded from the deque before insertions begin. If there are more + /// spans to consume, the callback will get called again after such a partial + /// consumption. + /// + /// The `initializer` callback is not required to fully populate its + /// output span, and it is allowed to throw an error. In such cases, the + /// replacement operation ends, and the deque keeps all items that were + /// successfully initialized before the callback terminated. + /// + /// Partial insertions create a gap in ring buffer storage that needs to be + /// closed by moving newly inserted items to their correct positions given + /// the adjusted count. This adds some overhead compared to adding exactly as + /// many items as promised. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - initializer: A callback that gets called at most twice to directly + /// populate newly reserved storage within the deque. The function + /// is always called with an empty output span. + /// + /// - Complexity: O(`self.count` + `newCount`) + @available(*, deprecated, renamed: "replaceSubrange(_:addingCount:initializingWith:)") + @inlinable + public mutating func replace( + removing subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + try replaceSubrange( + subrange, addingCount: newItemCount, initializingWith: initializer) + } + + /// 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 deque 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 deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: A fully initialized buffer whose contents to move into + /// the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + moving items: UnsafeMutableBufferPointer, + ) { + replaceSubrange(subrange, moving: items) + } + + /// Replaces the specified range of elements by moving the contents of an + /// output span into their place. On return, the span is left empty. + /// + /// This method has the effect of removing the specified range of elements + /// from the deque 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 deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(moving:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the array to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: An output span whose contents are to be moved into the deque. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + moving items: inout OutputSpan + ) { + replaceSubrange(subrange, moving: &items) + } +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque /* where Element: Copyable */ { + /// 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 deque 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 deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") + @inlinable + public mutating func replace( + removing subrange: Range, + copying items: UnsafeBufferPointer + ) { + replaceSubrange(subrange, copying: items) + } + + /// 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 deque 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 deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length buffer as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") + @inlinable + public mutating func replace( + removing subrange: Range, + copying items: UnsafeMutableBufferPointer + ) { + replaceSubrange(subrange, copying: items) + } + + /// 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 deque 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 deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length span as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") + @inlinable + public mutating func replace( + removing subrange: Range, + copying items: Span + ) { + replaceSubrange(subrange, copying: items) + } + + /// 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 deque doesn't have sufficient capacity to accommodate the new + /// elements, then this method reallocates the deque's storage to grow it, + /// using a geometric growth rate. + /// + /// If you pass a zero-length range as the `subrange` parameter, this method + /// inserts the elements of `items` at `subrange.lowerBound`. This case + /// is more directly expressed by calling `insert(copying:at:)`. + /// + /// Likewise, if you pass a zero-length collection as the `items` + /// parameter, this method removes the elements in the given subrange + /// without replacement. This case is more directly expressed by calling + /// `removeSubrange`. + /// + /// - Parameters: + /// - subrange: The subrange of the deque to replace. The bounds of + /// the range must be valid indices in the deque. + /// - items: The new elements to copy into the collection. + /// + /// - Complexity: O(`self.count` + `items.count`) + @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") + @inlinable + @inline(__always) + public mutating func replace( + removing subrange: Range, + copying items: __owned some Collection + ) { + replaceSubrange(subrange, copying: items) + } + } #endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift index 783c082d..68fd47eb 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift @@ -37,15 +37,16 @@ extension UniqueDeque where Element: ~Copyable { /// - Parameter item: The new element to insert into the deque. /// - Parameter index: The position at which to insert the new element. /// `index` must be a valid index in the deque. - /// + /// - Returns: A valid index addressing the newly inserted element. /// - Complexity: O(`self.count`) when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient @_transparent - public mutating func insert(_ item: consuming Element, at index: Int) { + @discardableResult + public mutating func insert(_ item: consuming Element, at index: Int) -> Int { _storage._checkValidIndex(index) _ensureFreeCapacity(1) - _storage._handle.uncheckedInsert(item, at: index) + return _storage._handle.uncheckedInsert(item, at: index) } } @@ -93,22 +94,23 @@ extension UniqueDeque where Element: ~Copyable { /// - initializer: A callback that gets called at most twice to directly /// populate newly reserved storage within the deque. The function /// is always called with an empty output span. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity /// of the callback invocations when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func insert( addingCount newItemCount: Int, at index: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) { + ) throws(E) -> Range { _storage._checkValidIndex(index) precondition(newItemCount >= 0, "Cannot add a negative number of items") - guard newItemCount > 0 else { return } + guard newItemCount > 0 else { return index ..< index } _ensureFreeCapacity(newItemCount) - try _storage._handle.uncheckedInsert( + return try _storage._handle.uncheckedInsert( addingCount: newItemCount, at: index, initializingWith: initializer) } } @@ -132,17 +134,18 @@ extension UniqueDeque where Element: ~Copyable { /// the deque. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) when amortized over many /// similar invocations on the same deque. @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: UnsafeMutableBufferPointer, at index: Int - ) { - guard !items.isEmpty else { return } + ) -> Range { + guard !items.isEmpty else { return index ..< index } var remainder = items - insert(addingCount: items.count, at: index) { target in + let range = insert(addingCount: items.count, at: index) { target in target.withUnsafeMutableBufferPointer { buffer, count in buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) @@ -150,6 +153,7 @@ extension UniqueDeque where Element: ~Copyable { } } assert(remainder.isEmpty) + return range } #if UnstableContainersPreview @@ -169,18 +173,19 @@ extension UniqueDeque where Element: ~Copyable { /// the deque. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) when amortized over many /// similar invocations on the same deque. @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: inout InputSpan, at index: Int - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.insert(moving: source, at: index) count = 0 + return unsafe self.insert(moving: source, at: index) } } #endif @@ -201,18 +206,19 @@ extension UniqueDeque where Element: ~Copyable { /// the deque. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) when amortized over many /// similar invocations on the same deque. @_alwaysEmitIntoClient + @discardableResult public mutating func insert( moving items: inout OutputSpan, at index: Int - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe self.insert(moving: source, at: index) count = 0 + return unsafe self.insert(moving: source, at: index) } } } @@ -239,16 +245,17 @@ extension UniqueDeque /* where Element: Copyable */ { /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be /// a valid index of `self`. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `newElements.count`) when amortized over many /// similar invocations on the same deque. - @inlinable + @_alwaysEmitIntoClient + @discardableResult public mutating func insert( copying items: UnsafeBufferPointer, at index: Int - ) { - guard items.count > 0 else { return } + ) -> Range { + guard items.count > 0 else { return index ..< index } var remainder = items - insert(addingCount: remainder.count, at: index) { target in + let range = insert(addingCount: remainder.count, at: index) { target in target.withUnsafeMutableBufferPointer { buffer, count in buffer.initializeAll( fromContentsOf: remainder._extracting(first: buffer.count)) @@ -257,6 +264,7 @@ extension UniqueDeque /* where Element: Copyable */ { } } assert(remainder.isEmpty) + return range } /// Copies the elements of a fully initialized buffer pointer into this @@ -279,14 +287,15 @@ extension UniqueDeque /* where Element: Copyable */ { /// must be fully initialized. /// - index: The position at which to insert the new elements. It must be /// a valid index of `self`. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `newElements.count`) when amortized over many /// similar invocations on the same deque. - @inlinable + @_alwaysEmitIntoClient + @discardableResult public mutating func insert( copying items: UnsafeMutableBufferPointer, at index: Int - ) { + ) -> Range { unsafe self.insert(copying: UnsafeBufferPointer(items), at: index) } @@ -308,31 +317,32 @@ extension UniqueDeque /* where Element: Copyable */ { /// - items: The new elements to insert into the deque. /// - index: The position at which to insert the new elements. It must be /// a valid index of the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`count` + `items.count`) when amortized over many similar /// invocations on the same deque. - @inlinable + @_alwaysEmitIntoClient + @discardableResult public mutating func insert( copying items: Span, at index: Int - ) { + ) -> Range { items.withUnsafeBufferPointer { unsafe self.insert(copying: $0, at: index) } } - @inlinable + @_alwaysEmitIntoClient package mutating func _insertCollection( at index: Int, copying items: some Collection, newCount: Int - ) { - let done: Void? = items.withContiguousStorageIfAvailable { src in + ) -> Range { + let done: Range? = items.withContiguousStorageIfAvailable { src in self.insert(copying: src, at: index) } - if done != nil { return } + if let done { return done } var i = items.startIndex - self.insert(addingCount: newCount, at: index) { target in + let range = self.insert(addingCount: newCount, at: index) { target in while !target.isFull { target.append(items[i]) items.formIndex(after: &i) @@ -341,6 +351,7 @@ extension UniqueDeque /* where Element: Copyable */ { precondition( i == items.endIndex, "Broken Collection: count doesn't match contents") + return range } /// Copies the elements of a collection into this deque at the specified @@ -365,11 +376,12 @@ extension UniqueDeque /* where Element: Copyable */ { /// /// - Complexity: O(`count` + `newElements.count`) when amortized over many /// similar invocations on the same deque. - @inlinable + @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func insert( copying items: some Collection, at index: Int - ) { + ) -> Range { _insertCollection( at: index, copying: items, newCount: items.count) } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift index 0725992a..2190630d 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift @@ -85,18 +85,19 @@ extension UniqueDeque where Element: ~Copyable { /// - newItemCount: The maximum number of items to prepend to the deque. /// - body: A callback that gets called at most twice to directly /// populate newly reserved storage within the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`newItemCount`) in addition to the complexity of the callback /// invocations, when amortized over many similar invocations on the same /// deque. @_alwaysEmitIntoClient + @discardableResult public mutating func prepend( addingCount newItemCount: Int, initializingWith body: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { - guard newItemCount > 0 else { return } + ) throws(E) -> Range { + guard newItemCount > 0 else { return 0 ..< 0 } _ensureFreeCapacity(newItemCount) - try _storage._handle.uncheckedPrepend( + return try _storage._handle.uncheckedPrepend( addingCount: newItemCount, initializingWith: body) } } @@ -113,16 +114,17 @@ extension UniqueDeque where Element: ~Copyable { /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient @inline(__always) + @discardableResult public mutating func prepend( moving items: UnsafeMutableBufferPointer - ) { + ) -> Range { _ensureFreeCapacity(items.count) - _storage._handle.uncheckedPrepend(moving: items) + return _storage._handle.uncheckedPrepend(moving: items) } #if UnstableContainersPreview @@ -135,17 +137,18 @@ extension UniqueDeque where Element: ~Copyable { /// /// - Parameters: /// - items: An input span whose contents need to be prepended to this deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient + @discardableResult public mutating func prepend( moving items: inout InputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.prepend(moving: source) count = 0 + return unsafe self.prepend(moving: source) } } #endif @@ -159,17 +162,18 @@ extension UniqueDeque where Element: ~Copyable { /// /// - Parameters: /// - items: An output span whose contents need to be prepended to this deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient + @discardableResult public mutating func prepend( moving items: inout OutputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe self.prepend(moving: source) count = 0 + return unsafe self.prepend(moving: source) } } } @@ -186,16 +190,16 @@ extension UniqueDeque /*where Element: Copyable*/ { /// - Parameters: /// - items: A fully initialized buffer whose contents to copy into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. - @inlinable @_alwaysEmitIntoClient + @discardableResult public mutating func prepend( copying items: UnsafeBufferPointer - ) { + ) -> Range { _ensureFreeCapacity(items.count) - _storage._handle.uncheckedPrepend(copying: items) + return _storage._handle.uncheckedPrepend(copying: items) } /// Copies the elements of a buffer and prepend them to the front of this @@ -208,14 +212,13 @@ extension UniqueDeque /*where Element: Copyable*/ { /// - Parameters: /// - items: A fully initialized buffer whose contents to copy into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. - @inlinable @_alwaysEmitIntoClient public mutating func prepend( copying items: UnsafeMutableBufferPointer - ) { + ) -> Range { unsafe self.prepend(copying: UnsafeBufferPointer(items)) } @@ -226,12 +229,12 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Parameters: /// - items: A span whose contents to copy into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. - @inlinable @_alwaysEmitIntoClient - public mutating func prepend(copying items: Span) { + @discardableResult + public mutating func prepend(copying items: Span) -> Range { items.withUnsafeBufferPointer { source in unsafe self.prepend(copying: source) } @@ -258,14 +261,14 @@ extension UniqueDeque /*where Element: Copyable*/ { } @available(SwiftStdlib 6.4, *) - @inlinable + @_alwaysEmitIntoClient package mutating func _prepend( copying items: borrowing S, exactCount: Int - ) throws(S.Failure) + ) throws(S.Failure) -> Range where S.Element == Element { var it = items.makeBorrowingIterator() - try self.prepend(addingCount: exactCount) { (target) throws(S.Failure) in + return try self.prepend(addingCount: exactCount) { (target) throws(S.Failure) in let span = try it.nextSpan(maxCount: target.freeCapacity) target._append(copying: span) } @@ -350,23 +353,22 @@ extension UniqueDeque /*where Element: Copyable*/ { /// // `numbers` now contains [10, 11, 12, 13, 14, 15, 1, 2, 3, 4, 5] /// /// - Parameter items: The elements to prepend to the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. @inlinable @_alwaysEmitIntoClient public mutating func prepend( copying items: some Collection - ) { - let done: Void? = items.withContiguousStorageIfAvailable { source in + ) -> Range { + let done: Range? = items.withContiguousStorageIfAvailable { source in unsafe self.prepend(copying: source) - return } - guard done == nil else { return } + if let done { return done } let c = items.count - guard c > 0 else { return } + guard c > 0 else { return 0 ..< 0 } _ensureFreeCapacity(c) - _storage._handle.uncheckedPrepend(copying: items, exactCount: c) + return _storage._handle.uncheckedPrepend(copying: items, exactCount: c) } #if compiler(>=6.4) @@ -396,14 +398,15 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Parameters: /// - items: The new elements to copy into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(*m*), where *m* is the length of `items` when amortized /// over many similar invocations on the same deque. @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient + @discardableResult public mutating func prepend>( copying items: borrowing S - ) throws(S.Failure) + ) throws(S.Failure) -> Range where S.Element == Element { try self._prepend(copying: items, exactCount: items.count) } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift index 0c70d975..60788d49 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift @@ -72,19 +72,20 @@ extension UniqueDeque where Element: ~Copyable { /// - initializer: A callback that gets called at most twice to directly /// populate newly reserved storage within the deque. The function /// is always called with an empty output span. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newCount`) - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { _storage._checkValidBounds(subrange) precondition(newItemCount >= 0, "Cannot add a negative number of items") _ensureFreeCapacity(newItemCount - subrange.count) - try _storage._handle.uncheckedReplace( - removing: subrange, + return try _storage._handle.uncheckedReplaceSubrange( + subrange, addingCount: newItemCount, initializingWith: initializer) } @@ -138,21 +139,22 @@ extension UniqueDeque where Element: ~Copyable { /// - initializer: A callback that gets called at most twice to directly /// populate newly reserved storage within the deque. The function /// is always called with an empty output span. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity /// of the callback invocations. - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { _storage._checkValidBounds(subrange) precondition(newItemCount >= 0, "Cannot add a negative number of items") _ensureFreeCapacity(newItemCount - subrange.count) - try _storage._handle.uncheckedReplace( - removing: subrange, + return try _storage._handle.uncheckedReplaceSubrange( + subrange, consumingWith: consumer, addingCount: newItemCount, initializingWith: initializer) @@ -189,15 +191,18 @@ extension UniqueDeque where Element: ~Copyable { /// the range must be valid indices in the deque. /// - items: A fully initialized buffer whose contents to move into /// the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving items: UnsafeMutableBufferPointer, - ) { + ) -> Range { var remainder = items - replace(removing: subrange, addingCount: remainder.count) { target in + let range = replaceSubrange( + subrange, addingCount: remainder.count + ) { target in target.withUnsafeMutableBufferPointer { buffer, count in buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) @@ -205,6 +210,7 @@ extension UniqueDeque where Element: ~Copyable { } } assert(remainder.isEmpty) + return range } #if UnstableContainersPreview @@ -233,17 +239,18 @@ extension UniqueDeque where Element: ~Copyable { /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. /// - items: An input span whose contents are to be moved into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving items: inout InputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(last: count) - unsafe self.replace(removing: subrange, moving: source) count = 0 + return unsafe self.replaceSubrange(subrange, moving: source) } } #endif @@ -273,17 +280,18 @@ extension UniqueDeque where Element: ~Copyable { /// - subrange: The subrange of the array to replace. The bounds of /// the range must be valid indices in the deque. /// - items: An output span whose contents are to be moved into the deque. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, moving items: inout OutputSpan - ) { + ) -> Range { items.withUnsafeMutableBufferPointer { buffer, count in let source = buffer._extracting(first: count) - unsafe self.replace(removing: subrange, moving: source) count = 0 + return unsafe self.replaceSubrange(subrange, moving: source) } } } @@ -315,21 +323,23 @@ extension UniqueDeque /* where Element: Copyable */ { /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. /// - items: The new elements to copy into the collection. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying items: UnsafeBufferPointer - ) { + ) -> Range { var remainder = items - replace(removing: subrange, addingCount: remainder.count) { target in + let range = replaceSubrange(subrange, addingCount: remainder.count) { target in target.withUnsafeMutableBufferPointer { dst, dstCount in dst.initializeAll(fromContentsOf: remainder._trim(first: dst.count)) dstCount += dst.count } } assert(remainder.isEmpty) + return range } /// Replaces the specified subrange of elements by copying the elements of @@ -357,16 +367,15 @@ extension UniqueDeque /* where Element: Copyable */ { /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. /// - items: The new elements to copy into the collection. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying items: UnsafeMutableBufferPointer - ) { - unsafe self.replace( - removing: subrange, - copying: UnsafeBufferPointer(items)) + ) -> Range { + unsafe self.replaceSubrange(subrange, copying: UnsafeBufferPointer(items)) } /// Replaces the specified subrange of elements by copying the elements of @@ -394,34 +403,35 @@ extension UniqueDeque /* where Element: Copyable */ { /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. /// - items: The new elements to copy into the collection. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) - @inlinable - public mutating func replace( - removing subrange: Range, + @_alwaysEmitIntoClient + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying items: Span - ) { + ) -> Range { items.withUnsafeBufferPointer { buffer in - unsafe self.replace(removing: subrange, copying: buffer) + unsafe self.replaceSubrange(subrange, copying: buffer) } } - @inlinable - internal mutating func _replace( - removing subrange: Range, + @_alwaysEmitIntoClient + internal mutating func _replaceSubrange( + _ subrange: Range, copyingCollection items: __owned some Collection, newCount: Int - ) { - let done: Void? = items.withContiguousStorageIfAvailable { src in + ) -> Range { + let done: Range? = items.withContiguousStorageIfAvailable { src in precondition( src.count == newCount, "Broken Collection: count doesn't match contents") - self.replace(removing: subrange, copying: src) + return self.replaceSubrange(subrange, copying: src) } - if done != nil { return } + if let done { return done } var i = items.startIndex - self.replace(removing: subrange, addingCount: newCount) { target in + let range = self.replaceSubrange(subrange, addingCount: newCount) { target in while !target.isFull { target.append(items[i]) items.formIndex(after: &i) @@ -430,6 +440,7 @@ extension UniqueDeque /* where Element: Copyable */ { precondition( i == items.endIndex, "Broken Collection: count doesn't match contents") + return range } /// Replaces the specified subrange of elements by copying the elements of @@ -457,16 +468,16 @@ extension UniqueDeque /* where Element: Copyable */ { /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. /// - items: The new elements to copy into the collection. - /// + /// - Returns: A valid index range addressing the newly inserted items. /// - Complexity: O(`self.count` + `items.count`) - @inlinable + @_alwaysEmitIntoClient @inline(__always) - public mutating func replace( - removing subrange: Range, + @discardableResult + public mutating func replaceSubrange( + _ subrange: Range, copying items: __owned some Collection - ) { - _replace( - removing: subrange, copyingCollection: items, newCount: items.count) + ) -> Range { + _replaceSubrange(subrange, copyingCollection: items, newCount: items.count) } } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift index c244c6b2..43db99d0 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift @@ -271,8 +271,8 @@ extension UniqueDeque where Element: ~Copyable { /// /// - Complexity: O(`count`) @inlinable - public mutating func reallocate(capacity: Int) { - _storage.reallocate(capacity: capacity) + public mutating func setCapacity(_ newCapacity: Int) { + _storage.setCapacity(newCapacity) } /// Ensure that the array has capacity to store the specified number of @@ -307,7 +307,7 @@ extension UniqueDeque where Element: ~Copyable { @inlinable internal mutating func _ensureFreeCapacitySlow(_ freeCapacity: Int) { let newCapacity = _grow(freeCapacity: freeCapacity) - reallocate(capacity: newCapacity) + setCapacity(newCapacity) } } diff --git a/Sources/DequeModule/_UnsafeDequeHandle.swift b/Sources/DequeModule/_UnsafeDequeHandle.swift index 5072e3b6..d3bb4623 100644 --- a/Sources/DequeModule/_UnsafeDequeHandle.swift +++ b/Sources/DequeModule/_UnsafeDequeHandle.swift @@ -528,7 +528,7 @@ extension _UnsafeDequeHandle { extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient internal mutating func reallocate(capacity newCapacity: Int) { - precondition(newCapacity >= count, "Capacity overflow") + let newCapacity = Swift.max(newCapacity, count) guard newCapacity != capacity else { return } var new = _UnsafeDequeHandle.allocate(capacity: newCapacity) @@ -707,6 +707,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { internal mutating func _append( count: Int ) -> _UnsafeMutableDequeSegments? { + assert(self.count + count <= capacity) guard count > 0 else { return nil } let origCount = self.count self.count &+= count @@ -718,11 +719,10 @@ extension _UnsafeDequeHandle where Element: ~Copyable { count: Int ) -> _UnsafeMutableDequeSegments? { assert(self.count + count <= capacity) - guard count > 0 else { return .init() } + guard count > 0 else { return nil } let oldStart = self.startSlot self.startSlot = self.slot(startSlot, offsetBy: -count) self.count &+= count - return self.mutableSegments(between: self.startSlot, and: oldStart) } } @@ -751,13 +751,14 @@ extension _UnsafeDequeHandle where Element: ~Copyable { /// is allowed to initialize fewer than `count` items. The deque is /// appended however many items the callback adds to the output span /// before it returns (or before it throws an error). - /// + /// - Returns: A valid offset range addressing the newly inserted items. /// - Complexity: O(`capacity`) @_alwaysEmitIntoClient internal mutating func uncheckedAppend( addingCount newItemCount: Int, initializingWith body: (inout OutputSpan) throws(E) -> Void - ) throws(E) { + ) throws(E) -> Range { + let origCount = count let gap = self.mutableSegments(forOffsets: count ..< count + newItemCount) let c = self.count &+ gap.first.count try gap.first._initialize( @@ -766,6 +767,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { try second._initialize( initializedCount: &self.count, initializingWith: body) } + return Range(uncheckedBounds: (origCount, count)) } /// Prepend a given number of items to the end of this deque by populating @@ -811,15 +813,15 @@ extension _UnsafeDequeHandle where Element: ~Copyable { /// is allowed to initialize fewer than `count` items. The deque is /// prepended however many items the callback adds to output span /// before it returns (or before it throws an error). - /// + /// - Returns: A valid offset range addressing the newly inserted items. /// - Complexity: O(`count`) @_alwaysEmitIntoClient package mutating func uncheckedPrepend( addingCount newItemCount: Int, initializingWith body: (inout OutputSpan) throws(E) -> Void - ) throws(E) { - guard let gap = self._prepend(count: newItemCount) else { return } - + ) throws(E) -> Range { + guard let gap = self._prepend(count: newItemCount) else { return 0 ..< 0 } + var c = 0 defer { if c < newItemCount { @@ -830,6 +832,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { if c == gap.first.count, let second = gap.second { try second._initialize(initializedCount: &c, initializingWith: body) } + return Range(uncheckedBounds: (0, c)) } } #endif @@ -845,14 +848,14 @@ extension _UnsafeDequeHandle where Element: ~Copyable { /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the deque. - /// + /// - Returns: A valid offset range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient internal mutating func uncheckedAppend( moving items: UnsafeMutableBufferPointer - ) { - guard let gap = _append(count: items.count) else { return } - + ) -> Range { + guard let gap = _append(count: items.count) else { return count ..< count } + gap.first.moveInitializeAll( fromContentsOf: items._extracting(first: gap.first.count)) @@ -861,6 +864,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { second.moveInitializeAll( fromContentsOf: items._extracting(last: second.count)) } + return Range(uncheckedBounds: (count &- items.count, count)) } /// Prepends the elements of a buffer to the front of this deque, leaving the @@ -872,14 +876,14 @@ extension _UnsafeDequeHandle where Element: ~Copyable { /// - Parameters: /// - items: A fully initialized buffer whose contents to move into /// the deque. - /// + /// - Returns: A valid offset range addressing the newly inserted items. /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient internal mutating func uncheckedPrepend( moving items: UnsafeMutableBufferPointer - ) { - guard let gap = _prepend(count: items.count) else { return } - + ) -> Range { + guard let gap = _prepend(count: items.count) else { return 0 ..< 0 } + gap.first.moveInitializeAll( fromContentsOf: items._extracting(first: gap.first.count)) @@ -888,6 +892,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { second.moveInitializeAll( fromContentsOf: items._extracting(last: second.count)) } + return Range(uncheckedBounds: (0, items.count)) } } @@ -899,9 +904,12 @@ extension _UnsafeDequeHandle { /// does it ensure that the storage buffer is uniquely referenced. @_alwaysEmitIntoClient @_transparent - internal mutating func uncheckedAppend(copying source: UnsafeBufferPointer) { - guard let gap = _append(count: source.count) else { return } + internal mutating func uncheckedAppend( + copying source: UnsafeBufferPointer + ) -> Range { + guard let gap = _append(count: source.count) else { return count ..< count } gap.initialize(copying: source) + return Range(uncheckedBounds: (count &- source.count, count)) } /// Prepend the contents of `source` to this buffer. The buffer must have @@ -911,9 +919,12 @@ extension _UnsafeDequeHandle { /// does it ensure that the storage buffer is uniquely referenced. @_alwaysEmitIntoClient @_transparent - internal mutating func uncheckedPrepend(copying source: UnsafeBufferPointer) { - guard let gap = _prepend(count: source.count) else { return } + internal mutating func uncheckedPrepend( + copying source: UnsafeBufferPointer + ) -> Range { + guard let gap = _prepend(count: source.count) else { return 0 ..< 0 } gap.initialize(copying: source) + return Range(uncheckedBounds: (0, source.count)) } } @@ -936,11 +947,12 @@ extension _UnsafeDequeHandle { internal mutating func uncheckedPrepend>( copying items: C, exactCount: Int - ) { + ) -> Range { // Note: You're supposed to handle contiguous sequences before calling // this function. You do this by invoking `withContiguousStorageIfAvailable`. - guard let gap = self._prepend(count: exactCount) else { return } + guard let gap = self._prepend(count: exactCount) else { return 0 ..< 0 } gap.initialize(copying: items) + return Range(uncheckedBounds: (0, exactCount)) } } @@ -1262,19 +1274,20 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_transparent internal mutating func uncheckedInsert( _ newElement: consuming Element, at offset: Int - ) { + ) -> Int { assert(count < capacity) if offset == 0 { uncheckedPrepend(newElement) - return + return offset } if offset == count { uncheckedAppend(newElement) - return + return offset } let gap = openGap(ofSize: 1, atOffset: offset) assert(gap.first.count == 1) gap.first.baseAddress!.initialize(to: newElement) + return offset } } @@ -1286,8 +1299,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { addingCount newItemCount: Int, at offset: Int, initializingWith body: (inout OutputSpan) throws(E) -> Void - ) throws(E) { - guard newItemCount > 0 else { return } + ) throws(E) -> Range { + guard newItemCount > 0 else { return offset ..< offset } let gap = self.openGap(ofSize: newItemCount, atOffset: offset) var c = 0 @@ -1300,6 +1313,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { if c == gap.first.count, let second = gap.second { try second._initialize(initializedCount: &c, initializingWith: body) } + return Range(uncheckedBounds: (offset, offset &+ c)) } } #endif @@ -1404,12 +1418,13 @@ extension _UnsafeDequeHandle where Element: ~Copyable { /// does it ensure that the storage buffer is uniquely referenced. @_alwaysEmitIntoClient @_transparent - internal mutating func uncheckedRemove(offsets bounds: Range) { + internal mutating func uncheckedRemove(offsets bounds: Range) -> Int { assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count) // Deinitialize elements in `bounds`. mutableSegments(forOffsets: bounds).deinitialize() closeGap(offsets: bounds) + return bounds.lowerBound } } @@ -1423,7 +1438,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { _ subrange: Range, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { // Note: we're careful to open/close the gap in a direction that does not // lead to trying to move slots we deinitialized above. let delta = newItemCount - subrange.count @@ -1452,21 +1467,22 @@ extension _UnsafeDequeHandle where Element: ~Copyable { if c == gap.first.count, let second = gap.second { try second._initialize(initializedCount: &c, initializingWith: initializer) } + return Range(uncheckedBounds: (newRange.lowerBound, newRange.lowerBound &+ c)) } @_alwaysEmitIntoClient - internal mutating func uncheckedReplace( - removing subrange: Range, + internal mutating func uncheckedReplaceSubrange( + _ subrange: Range, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { assert( subrange.lowerBound >= 0 && subrange.upperBound <= count, "Subrange out of bounds") assert(newItemCount >= 0, "Cannot add a negative number of items") assert(count + newItemCount - subrange.count <= capacity, "RigidDeque capacity overflow") self.mutableSegments(forOffsets: subrange).deinitialize() - try _insertAfterReplace( + return try _insertAfterReplace( subrange, addingCount: newItemCount, initializingWith: initializer) @@ -1474,12 +1490,12 @@ extension _UnsafeDequeHandle where Element: ~Copyable { #if UnstableContainersPreview @_alwaysEmitIntoClient - internal mutating func uncheckedReplace( - removing subrange: Range, + internal mutating func uncheckedReplaceSubrange( + _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void, addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void - ) throws(E) -> Void { + ) throws(E) -> Range { assert( subrange.lowerBound >= 0 && subrange.upperBound <= count, "Subrange out of bounds") @@ -1496,7 +1512,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { consumer(&span) } } - try _insertAfterReplace( + return try _insertAfterReplace( subrange, addingCount: newItemCount, initializingWith: initializer) diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index 4a83fa3e..8982eb7b 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -1252,7 +1252,7 @@ class RigidArrayTests: CollectionTestCase { withLifetimeTracking { tracker in var a = tracker.rigidArray(layout: layout) - a.replace(removing: subrange, addingCount: c) { target in + a.replaceSubrange(subrange, addingCount: c) { target in expectEqual(target.freeCapacity, c) for i in 0 ..< c { target.append(tracker.instance(for: layout.count + i)) @@ -1284,7 +1284,7 @@ class RigidArrayTests: CollectionTestCase { withLifetimeTracking { tracker in var a = tracker.rigidArray(layout: layout) - a.replace(removing: subrange, addingCount: c) { target in + a.replaceSubrange(subrange, addingCount: c) { target in expectTrue(target.isEmpty) expectEqual(target.freeCapacity, c) for i in 0 ..< n { @@ -1318,8 +1318,8 @@ class RigidArrayTests: CollectionTestCase { withLifetimeTracking { tracker in var a = tracker.rigidArray(layout: layout) - a.replace( - removing: subrange, + a.replaceSubrange( + subrange, consumingWith: { span in for i in 0 ..< subrange.count { expectEqual(span[i].payload, subrange.lowerBound + i) @@ -1358,8 +1358,8 @@ class RigidArrayTests: CollectionTestCase { withLifetimeTracking { tracker in var a = tracker.rigidArray(layout: layout) - a.replace( - removing: subrange, + a.replaceSubrange( + subrange, consumingWith: { span in for i in 0 ..< subrange.count { expectEqual(span[i].payload, subrange.lowerBound + i) @@ -1408,7 +1408,7 @@ class RigidArrayTests: CollectionTestCase { addition.map { tracker.instance(for: $0) }, isContiguous: isContiguous) var a = tracker.rigidArray(layout: layout) - a.replace(removing: range, copying: trackedAddition) + a.replaceSubrange(range, copying: trackedAddition) expectRigidArrayContents( a, @@ -1433,7 +1433,7 @@ class RigidArrayTests: CollectionTestCase { var a = tracker.rigidArray(layout: layout) let trackedAddition = RigidArray(copying: addition.map { tracker.instance(for: $0) }) - a.replace(removing: range, copying: trackedAddition.span) + a.replaceSubrange(range, copying: trackedAddition.span) expectRigidArrayContents( a, @@ -1463,7 +1463,7 @@ class RigidArrayTests: CollectionTestCase { let trackedAddition = StaccatoContainer( contents: RigidArray(copying: addition.map { tracker.instance(for: $0) }), spanCounts: [spanCount]) - a.replace(removing: range, copying: trackedAddition) + a.replaceSubrange(range, copying: trackedAddition) expectRigidArrayContents( a, @@ -1518,7 +1518,7 @@ class RigidArrayTests: CollectionTestCase { a.append(tracker.instance(for: i)) } - var consumer = a.consume(0 ..< 2) + var consumer = a.consumeSubrange(0 ..< 2) let span = consumer.drainNext(maxCount: .max) expectEqual(span.count, 2) diff --git a/Tests/BasicContainersTests/UniqueArrayTests.swift b/Tests/BasicContainersTests/UniqueArrayTests.swift index 06e96fb7..6d2e8264 100644 --- a/Tests/BasicContainersTests/UniqueArrayTests.swift +++ b/Tests/BasicContainersTests/UniqueArrayTests.swift @@ -534,12 +534,13 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) a.removeAll() expectTrue(a.isEmpty) - expectEqual(a.capacity, 0) + expectEqual(a.capacity, layout.capacity) expectEqual(tracker.instances, 0) } } } + @available(*, deprecated) func test_removeAll_keepingCapacity() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -940,7 +941,7 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) let trackedAddition = addition.map { tracker.instance(for: $0) } - a.replace(removing: range, copying: trackedAddition) + a.replaceSubrange(range, copying: trackedAddition) expectUniqueArrayContents( a, @@ -970,7 +971,7 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) let trackedAddition = RigidArray( copying: addition.map { tracker.instance(for: $0) }) - a.replace(removing: range, copying: trackedAddition.span) + a.replaceSubrange(range, copying: trackedAddition.span) expectUniqueArrayContents( a, @@ -1002,7 +1003,7 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) trackedAddition.span.withUnsafeBufferPointer { buffer in - a.replace(removing: range, copying: buffer) + _ = a.replaceSubrange(range, copying: buffer) } expectUniqueArrayContents( diff --git a/Tests/DequeTests/RigidDequeTests.swift b/Tests/DequeTests/RigidDequeTests.swift index a98d1ecb..4ab4a0bd 100644 --- a/Tests/DequeTests/RigidDequeTests.swift +++ b/Tests/DequeTests/RigidDequeTests.swift @@ -213,7 +213,7 @@ final class RigidDequeTests: CollectionTestCase { } } - func test_reallocate() { + func test_setCapacity() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery( "newCapacity", @@ -221,7 +221,7 @@ final class RigidDequeTests: CollectionTestCase { ) { newCapacity in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - data.deque.reallocate(capacity: newCapacity) + data.deque.setCapacity(newCapacity) expectEqual(data.deque.capacity, newCapacity) expectEqual(data.deque.count, layout.count) @@ -358,12 +358,13 @@ final class RigidDequeTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_initFromProducer() { withEvery("count", in: 0 ..< 10) { count in withEvery("capacity", in: [count, count + 1, 2 * count] as Set) { capacity in withLifetimeTracking { tracker in var invocations = 0 - var producer = CustomProducer, Never> { + let producer = CustomProducer, Never> { if invocations >= count { return nil } @@ -371,7 +372,7 @@ final class RigidDequeTests: CollectionTestCase { return tracker.structInstance(for: invocations) } - let deque = RigidDeque(capacity: capacity, from: &producer) + let deque = RigidDeque(capacity: capacity, from: producer) expectEqual(invocations, count) expectEqual(deque.count, count) expectEqual(tracker.instances, count) @@ -385,21 +386,22 @@ final class RigidDequeTests: CollectionTestCase { } } + @available(SwiftStdlib 6.4, *) func test_initFromThrowingProducer() { withEvery("count", in: 0 ..< 10) { (count: Int) in withLifetimeTracking { tracker in var invocations = 0 - var producer = CustomProducer, TestError> - { () throws(TestError) in - if invocations >= count { - throw TestError(42) - } - defer { invocations += 1 } - return tracker.structInstance(for: invocations) - } - expectThrows { () throws(TestError) in - let _ = try RigidDeque(capacity: count + 10, from: &producer) + let producer = CustomProducer, TestError> + { () throws(TestError) in + if invocations >= count { + throw TestError(42) + } + defer { invocations += 1 } + return tracker.structInstance(for: invocations) + } + + let _ = try RigidDeque(capacity: count + 10, from: producer) } errorHandler: { error in expectEqual(error.value, 42) @@ -781,6 +783,7 @@ final class RigidDequeTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_prepend_Producer_full() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in withEvery("producerSize", in: 0 ..< 6) { producerSize in @@ -796,7 +799,7 @@ final class RigidDequeTests: CollectionTestCase { return extras.removeFirst() } - data.deque.prepend(from: &producer) + data.deque.prepend(addingCount: layout.freeCapacity, from: &producer) expectEqual(extras.count, max(0, producerSize - layout.freeCapacity)) expectRigidDequeContents(data.deque, equalTo: data.contents) } @@ -806,6 +809,7 @@ final class RigidDequeTests: CollectionTestCase { #endif #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_append_Producer() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in withEvery("producerSize", in: 0 ..< layout.freeCapacity) { producerSize in @@ -821,7 +825,7 @@ final class RigidDequeTests: CollectionTestCase { return extras.removeFirst() } - data.deque.append(from: &producer) + data.deque.append(addingCount: extras.count, from: &producer) expectEqual(extras.count, max(0, producerSize - layout.freeCapacity)) expectRigidDequeContents(data.deque, equalTo: data.contents) } @@ -831,6 +835,7 @@ final class RigidDequeTests: CollectionTestCase { #endif #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_prepend_Producer_failing() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in guard layout.freeCapacity > 0 else { return } @@ -840,15 +845,14 @@ final class RigidDequeTests: CollectionTestCase { var extras = tracker.instances(for: 0 ..< producerSize) - data.contents.insert(contentsOf: extras, at: 0) + data.contents.insert(contentsOf: extras.reversed(), at: 0) var producer = CustomProducer, TestError> { () throws(TestError) in guard !extras.isEmpty else { throw TestError(23) } - return extras.removeFirst() + return extras.removeLast() } - expectThrows { () throws(TestError) in - try data.deque.prepend(from: &producer) + try data.deque.prepend(addingCount: layout.freeCapacity, from: &producer) } errorHandler: { error in expectEqual(error.value, 23) @@ -862,6 +866,7 @@ final class RigidDequeTests: CollectionTestCase { #endif #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_append_Producer_failing() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in guard layout.freeCapacity > 0 else { return } @@ -871,15 +876,15 @@ final class RigidDequeTests: CollectionTestCase { var extras = tracker.instances(for: 0 ..< producerSize) - data.contents.append(contentsOf: extras) + data.contents.append(contentsOf: extras.reversed()) var producer = CustomProducer, TestError> { () throws(TestError) in guard !extras.isEmpty else { throw TestError(23) } - return extras.removeFirst() + return extras.removeLast() } expectThrows { () throws(TestError) in - try data.deque.append(from: &producer) + try data.deque.append(addingCount: layout.freeCapacity, from: &producer) } errorHandler: { error in expectEqual(error.value, 23) @@ -1188,6 +1193,7 @@ final class RigidDequeTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_insert_fromProducer() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in withEvery("i", in: 0 ... layout.count) { i in @@ -1220,6 +1226,7 @@ final class RigidDequeTests: CollectionTestCase { #endif #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_insert_fromProducer_failing() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in guard layout.freeCapacity > 0 else { return } @@ -1307,7 +1314,7 @@ final class RigidDequeTests: CollectionTestCase { var a = tracker.rigidDeque(with: layout).consume() var i = 0 - a.replace(removing: subrange, addingCount: c) { target in + a.replaceSubrange(subrange, addingCount: c) { target in while !target.isFull { target.append(tracker.instance(for: layout.count + i)) i += 1 @@ -1341,7 +1348,7 @@ final class RigidDequeTests: CollectionTestCase { var a = tracker.rigidDeque(with: layout).consume() var i = 0 - a.replace(removing: subrange, addingCount: c) { target in + a.replaceSubrange(subrange, addingCount: c) { target in while !target.isFull, i < n { target.append(tracker.instance(for: layout.count + i)) i += 1 @@ -1376,8 +1383,8 @@ final class RigidDequeTests: CollectionTestCase { var i = subrange.lowerBound var j = 0 - a.replace( - removing: subrange, + a.replaceSubrange( + subrange, consumingWith: { source in while let next = source.popFirst() { expectEqual(next.payload, i) @@ -1424,8 +1431,8 @@ final class RigidDequeTests: CollectionTestCase { var i = subrange.lowerBound var j = 0 - a.replace( - removing: subrange, + a.replaceSubrange( + subrange, consumingWith: { source in while let next = source.popFirst() { expectEqual(next.payload, i) @@ -1566,7 +1573,7 @@ final class RigidDequeTests: CollectionTestCase { withEvery("to", in: from ... layout.count) { to in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - data.deque.consume(from ..< to, consumingWith: { _ in }) + data.deque.consumeSubrange(from ..< to, consumingWith: { _ in }) data.contents.removeSubrange(from ..< to) expectEqual(data.deque.count, data.contents.count) expectRigidDequeContents(data.deque, equalTo: data.contents) diff --git a/Tests/DequeTests/UniqueDequeTests.swift b/Tests/DequeTests/UniqueDequeTests.swift index 3df8d6bb..388cb073 100644 --- a/Tests/DequeTests/UniqueDequeTests.swift +++ b/Tests/DequeTests/UniqueDequeTests.swift @@ -203,7 +203,7 @@ final class UniqueDequeTests: CollectionTestCase { var data = tracker.uniqueDeque(with: layout) let newItems = tracker.instances(for: 100 ..< 100 + newCount) var src = newItems.makeIterator() - data.deque.replace(removing: from ..< to, addingCount: newCount) { target in + data.deque.replaceSubrange(from ..< to, addingCount: newCount) { target in while !target.isFull, let item = src.next() { target.append(item) }