From 06f2ec073ddca0a5b3b9ca70c4660bd72962d8bc Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 4 Feb 2026 14:26:57 -0800 Subject: [PATCH] Rigid, Unique types: Rework OutputSpan-based append/prepend/insert/replaceSubrange primitives --- .../RigidArray/RigidArray+Append.swift | 42 ++-- .../RigidArray/RigidArray+Initializers.swift | 4 +- .../RigidArray/RigidArray+Insertions.swift | 92 ++++++-- .../RigidArray/RigidArray+Removals.swift | 8 +- .../RigidArray/RigidArray+Replacements.swift | 211 ++++++++++++++++-- .../RigidArray/RigidArray.swift | 47 ++-- .../UniqueArray/UniqueArray+Append.swift | 44 +++- .../UniqueArray/UniqueArray+Insertions.swift | 63 +++++- .../UniqueArray/UniqueArray+Removals.swift | 6 +- .../UniqueArray+Replacements.swift | 146 +++++++++++- .../RigidDeque/RigidDeque+Consumption.swift | 129 +++++++++++ .../RigidDeque/RigidDeque+Insertions.swift | 48 ++-- .../RigidDeque/RigidDeque+Prepend.swift | 16 +- .../RigidDeque/RigidDeque+Replacements.swift | 96 ++++---- .../UniqueDeque/UniqueDeque+Insertions.swift | 44 ++-- .../UniqueDeque/UniqueDeque+Prepend.swift | 4 +- .../UniqueDeque+Replacements.swift | 83 ++++--- Sources/DequeModule/_UnsafeDequeHandle.swift | 48 ++-- Tests/DequeTests/RigidDequeTests.swift | 16 +- 19 files changed, 887 insertions(+), 260 deletions(-) diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift index 96608c54..e2bb6999 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift @@ -60,29 +60,33 @@ extension RigidArray where Element: ~Copyable { /// If the array does not have sufficient capacity to store the new items in /// the buffer, then this triggers a runtime error. /// - /// - Parameters - /// - uninitializedCount: The number of items to append to the array. - /// - body: A callback that gets called at most once to directly + /// If the callback fails to fully populate its output span or if + /// it throws an error, then the array keeps all items that were + /// successfully initialized before the callback terminated the insertion. + /// + /// - Parameters: + /// - newItemCount: The number of items to append to the array. + /// - initializer: A callback that gets called at most once to directly /// populate newly reserved storage within the array. The function - /// is allowed to initialize fewer than `uninitializedCount` items. + /// 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). /// - /// - Complexity: O(`uninitializedCount`) + /// - Complexity: O(`newItemCount`) @_alwaysEmitIntoClient public mutating func append( - addingCapacity uninitializedCount: Int, - initializingWith body: (inout OutputSpan) throws(E) -> Void + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) { - precondition(uninitializedCount >= 0, "Negative count") - precondition(freeCapacity >= uninitializedCount, "RigidArray capacity overflow") - let buffer = _freeSpace._extracting(first: uninitializedCount) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + precondition(freeCapacity >= newItemCount, "RigidArray capacity overflow") + let buffer = _freeSpace._extracting(first: newItemCount) var span = OutputSpan(buffer: buffer, initializedCount: 0) defer { _count &+= span.finalize(for: buffer) span = OutputSpan() } - return try body(&span) + return try initializer(&span) } /// Append a given number of items to the end of this array by populating @@ -91,29 +95,25 @@ extension RigidArray where Element: ~Copyable { /// If the array does not have sufficient capacity to store the new items in /// the buffer, then this triggers a runtime error. /// - /// If the callback fails to fully populate its output span or if - /// it throws an error, then the items that were successfully initialized - /// still get appended to the end of the array. - /// - /// - Parameters + /// - Parameters: /// - count: The number of items to append to the array. - /// - body: A callback that gets called at most once to directly + /// - initializer: A callback that gets called at most once to directly /// populate newly reserved storage within the array. The function /// is allowed to initialize fewer than `count` items. The array is /// appended however many items the callback adds to the output span /// before it returns (or before it throws an error). /// /// - Complexity: O(`count`) - @available(*, deprecated, renamed: "append(addingCapacity:initializingWith:)") + @available(*, deprecated, renamed: "append(addingCount:initializingWith:)") @_alwaysEmitIntoClient @inline(__always) public mutating func append( count: Int, - initializingWith body: (inout OutputSpan) throws(E) -> Result + initializingWith initializer: (inout OutputSpan) throws(E) -> Result ) throws(E) -> Result { var result: Result? = nil - try append(addingCapacity: count) { target throws(E) in - result = try body(&target) + try append(addingCount: count) { target throws(E) in + result = try initializer(&target) } return result.take()! } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift index 4f001442..59b5f8b6 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift @@ -55,10 +55,10 @@ extension RigidArray where Element: ~Copyable { @inlinable public init( capacity: Int, - initializingWith body: (inout OutputSpan) throws(E) -> Void + initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) { self.init(capacity: capacity) - try edit(body) + try edit(initializer) } } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift index 47018162..1e8f9327 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift @@ -52,6 +52,69 @@ extension RigidArray where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { + /// Inserts a given number of new items into this array at the specified + /// position, using a callback to directly initialize array storage by + /// populating an output span. + /// + /// Existing elements in the array's storage are moved towards the back as + /// needed to make room for the new items. + /// + /// If the capacity of the array isn't sufficient to accommodate the specified + /// number of new elements, then this method triggers a runtime error. + /// + /// var buffer = RigidArray(capacity: 20) + /// buffer.append([-999, 999]) + /// var i = 0 + /// buffer.insert(capacity: 3, at: 1) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [-999, 0, 1, 2, 999] + /// + /// If the callback fails to fully populate its output span or if + /// it throws an error, then the array keeps all items that were + /// successfully initialized before the callback terminated the insertion. + /// + /// Partial insertions create a gap in array storage that needs to be + /// closed by moving already inserted 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 array. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the array. + /// - 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. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert( + addingCount newItemCount: Int, + at index: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + precondition(index >= 0 && index <= self.count, "Index out of bounds") + precondition(newItemCount >= 0, "Cannot add a negative number of items") + precondition(newItemCount <= freeCapacity, "RigidArray capacity overflow") + let target = unsafe _openGap(at: index, count: newItemCount) + var span = OutputSpan(buffer: target, initializedCount: 0) + defer { + let c = span.finalize(for: target) + if c < newItemCount { + _closeGap(at: index &+ c, count: newItemCount &- c) + } + _count &+= c + span = OutputSpan() + } + try initializer(&span) + } + /// Inserts a given number of new items into this array at the specified /// position, using a callback to directly initialize array storage by /// populating an output span. @@ -66,31 +129,24 @@ extension RigidArray where Element: ~Copyable { /// - count: The number of items to insert into the array. /// - index: The position at which to insert the new items. /// `index` must be a valid index in the array. - /// - body: A callback that gets called at most once to directly + /// - 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 matching the /// supplied count, and it must fully populate it before returning. /// /// - Complexity: O(`self.count` + `count`) + @available(*, deprecated, renamed: "insert(addingCount:at:initializingWith:)") @inlinable public mutating func insert( count: Int, at index: Int, initializingWith body: (inout OutputSpan) -> Result ) -> Result { - // FIXME: This does not allow `body` to throw, to prevent having to move the tail twice. Is that okay? - precondition(index >= 0 && index <= self.count, "Index out of bounds") - precondition(count >= 0, "Negative count") - precondition(count <= freeCapacity, "RigidArray capacity overflow") - let target = unsafe _openGap(at: index, count: count) - var span = OutputSpan(buffer: target, initializedCount: 0) - defer { - let c = span.finalize(for: target) - precondition(c == count, "Inserted fewer items than promised") - _count &+= c - span = OutputSpan() + var result: Result? = nil + self.insert(addingCount: count, at: index) { target in + result = body(&target) } - return body(&span) + return result! } } @@ -118,7 +174,7 @@ extension RigidArray where Element: ~Copyable { moving items: UnsafeMutableBufferPointer, at index: Int ) { - insert(count: items.count, at: index) { target in + insert(addingCount: items.count, at: index) { target in target._append(moving: items) } } @@ -205,7 +261,7 @@ extension RigidArray where Element: ~Copyable { ) { // FIXME: Remove this in favor of a generic algorithm over consumable containers guard !items.isEmpty else { return } - insert(count: items.count, at: index) { target in + insert(addingCount: items.count, at: index) { target in items.edit { source in target._append(moving: &source) } @@ -270,7 +326,7 @@ extension RigidArray { copying newElements: UnsafeBufferPointer, at index: Int ) { guard newElements.count > 0 else { return } - self.insert(count: newElements.count, at: index) { target in + self.insert(addingCount: newElements.count, at: index) { target in target._append(copying: newElements) } } @@ -328,7 +384,7 @@ extension RigidArray { copying newElements: Span, at index: Int ) { guard newElements.count > 0 else { return } - self.insert(count: newElements.count, at: index) { target in + self.insert(addingCount: newElements.count, at: index) { target in target._append(copying: newElements) } } @@ -343,7 +399,7 @@ extension RigidArray { copying items: borrowing C, newCount: Int ) { - insert(count: newCount, at: index) { target in + insert(addingCount: newCount, at: index) { target in target.withUnsafeMutableBufferPointer { buffer, count in let copied = items._copyContents(intoPrefixOf: buffer) precondition( diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift index c0103111..1ff2d247 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift @@ -181,7 +181,7 @@ extension RigidArray where Element: ~Copyable { /// passing an input span to the given function to consume them in place. /// /// - Parameter bounds: The subrange of items to consume from this array. - /// - Parameter body: A function taking an input span of the removed items, + /// - 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 not required to consume all items in the span; /// however, the span's remaining items will still be removed from @@ -191,14 +191,14 @@ extension RigidArray where Element: ~Copyable { @_alwaysEmitIntoClient public mutating func consumeSubrange( _ bounds: Range, - consumingWith body: (inout InputSpan) throws(E) -> Result + consumingWith consumer: (inout InputSpan) throws(E) -> Result ) throws(E) -> Result { precondition( bounds.lowerBound >= 0 && bounds.upperBound <= _count, "Subrange out of bounds") guard !bounds.isEmpty else { var span = InputSpan() - return try body(&span) + return try consumer(&span) } let buffer = unsafe _storage.extracting(bounds) var span = InputSpan(buffer: buffer, initializedCount: buffer.count) @@ -209,7 +209,7 @@ extension RigidArray where Element: ~Copyable { _count -= bounds.count span = InputSpan() } - return try body(&span) + return try consumer(&span) } } #endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift index 19a0744a..c5469f43 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift @@ -18,6 +18,87 @@ import ContainersPreview @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { + /// 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. + /// + /// The number of new items need not match the number of elements being + /// removed. + /// + /// This method has the same overall effect as calling + /// + /// try array.removeSubrange(subrange) + /// try array.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the array twice. + /// + /// If the array does not have sufficient capacity to accommodate the new + /// elements, then this method triggers a runtime error. + /// + /// If the callback fails to fully populate its output span or if + /// it throws an error, then the array keeps all items that were + /// successfully initialized before the callback terminated the prepend. + /// + /// Partial insertions create a gap in array 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 array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - 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. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations. + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + 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") + try _uncheckedReplaceSubrange( + subrange, + addingCount: newItemCount, + initializingWith: initializer) + } + + @_alwaysEmitIntoClient + internal mutating func _uncheckedReplaceSubrange( + _ subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + // Destroy removed items + unsafe _items.extracting(subrange).deinitialize() + let target = _resizeGap(in: subrange, to: newItemCount) + var span = OutputSpan(buffer: target, initializedCount: 0) + defer { + let c = span.finalize(for: target) + if c < newItemCount { + self._closeGap( + at: subrange.lowerBound &+ c, + count: capacity &- c) + } + span = OutputSpan() + } + try initializer(&span) + } + /// 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. @@ -42,32 +123,132 @@ 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. /// - newCount: the number of items to replace the old subrange. - /// - body: A callback that gets called at most once to directly + /// - 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: "replaceSubrange(_:addingCapacity:initializingWith:)") @inlinable public mutating func replaceSubrange( _ subrange: Range, newCount: Int, initializingWith body: (inout OutputSpan) -> Result ) -> Result { - // FIXME: Should we allow throwing (and a partially filled output span)? - // FIXME: Should we have a version of this with two closures, to allow custom-consuming the old items? - // replaceSubrange(5..<10, newCount: 3, consumingWith: {...}, initializingWith: {...}) - let target = _gapForReplacement(of: subrange, withNewCount: newCount) - var span = OutputSpan(buffer: target, initializedCount: 0) - defer { - let c = span.finalize(for: target) - precondition(c == newCount, "Inserted fewer items than promised") - span = OutputSpan() + var result: Result? = nil + self.replaceSubrange(subrange, addingCount: newCount) { target in + result = body(&target) } - return body(&span) + return result! } } +@available(SwiftStdlib 5.0, *) +extension RigidArray where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified range of elements by a given count of new items, + /// using callbacks to consume old items, and to then insert new ones. + /// + /// The number of new items need not match the number of elements being + /// removed. + /// + /// This method has the same overall effect as calling + /// + /// try array.consume(subrange, consumingWith: consumer) + /// try array.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 array isn't sufficient to accommodate the specified + /// number of new elements, then this method triggers a runtime error. + /// + /// 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 array before insertions begin. + /// + /// The `initializer` callback is not required to fully populate its + /// output span, and it is allowed to throw an error. In such cases, the + /// deque keeps all items that were successfully initialized before the + /// callback terminated. + /// + /// Partial insertions create a gap in array 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. + /// - consumer: A callback that gets called at most once to consume + /// the elements to be removed directly from the deque's storage. The + /// function is always called with a non-empty input span. + /// - 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. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the + /// complexity of the callback invocations. + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + addingCount newItemCount: Int, + consumingWith consumer: (inout InputSpan) -> Void, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + 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") + try _uncheckedReplaceSubrange( + subrange, + addingCount: newItemCount, + consumingWith: consumer, + initializingWith: initializer) + } + + @_alwaysEmitIntoClient + internal mutating func _uncheckedReplaceSubrange( + _ subrange: Range, + addingCount newItemCount: Int, + consumingWith consumer: (inout InputSpan) -> Void, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + do { + // Consume items to be removed + let buffer = unsafe _storage.extracting(subrange) + var span = InputSpan(buffer: buffer, initializedCount: buffer.count) + consumer(&span) + _ = consume span + } + do { + // Insert new items + let target = _resizeGap(in: subrange, to: newItemCount) + var span = OutputSpan(buffer: target, initializedCount: 0) + defer { + let c = span.finalize(for: target) + if c < newItemCount { + self._closeGap( + at: subrange.lowerBound &+ c, + count: capacity &- c) + } + span = OutputSpan() + } + try initializer(&span) + } + } +#endif +} + + @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { /// Replaces the specified range of elements by moving the elements of a @@ -103,7 +284,7 @@ extension RigidArray where Element: ~Copyable { _ subrange: Range, moving newElements: UnsafeMutableBufferPointer, ) { - replaceSubrange(subrange, newCount: newElements.count) { target in + replaceSubrange(subrange, addingCount: newElements.count) { target in target._withUnsafeMutableBufferPointer { buffer, count in count = unsafe buffer._moveInitializePrefix(from: newElements) } @@ -303,7 +484,7 @@ extension RigidArray { _ subrange: Range, copying newElements: UnsafeBufferPointer ) { - replaceSubrange(subrange, newCount: newElements.count) { target in + replaceSubrange(subrange, addingCount: newElements.count) { target in target._withUnsafeMutableBufferPointer { buffer, count in count = unsafe buffer._initializePrefix(copying: newElements) } @@ -392,7 +573,7 @@ extension RigidArray { copyingContainer newElements: borrowing C, newCount: Int ) { - self.replaceSubrange(subrange, newCount: newCount) { target in + self.replaceSubrange(subrange, addingCapacity: newCount) { target in target.withUnsafeMutableBufferPointer { buffer, count in count = newElements._copyContents(intoPrefixOf: buffer) precondition( @@ -410,7 +591,7 @@ extension RigidArray { copyingCollection newElements: __owned some Collection, newCount: Int ) { - self.replaceSubrange(subrange, newCount: newCount) { target in + 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) diff --git a/Sources/BasicContainers/RigidArray/RigidArray.swift b/Sources/BasicContainers/RigidArray/RigidArray.swift index b785b573..9fadb604 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray.swift @@ -445,6 +445,32 @@ extension RigidArray where Element: ~Copyable { Range(uncheckedBounds: (index, index + count))) } + /// Resize the gap in the given subrange to have the specified count. + /// This operation moves elements following the gap to be at their expected + /// new location, and it adjusts the container's count to reflect the change. + /// + /// - Returns: A buffer pointer addressing the newly opened gap, to be + /// initialized by the caller. + @inlinable + @unsafe + internal mutating func _resizeGap( + in subrange: Range, to newItemCount: Int + ) -> UnsafeMutableBufferPointer { + assert(subrange.lowerBound >= 0 && subrange.upperBound <= _count) + assert(newItemCount >= 0 && newItemCount - subrange.count <= freeCapacity) + if newItemCount > subrange.count { + _ = unsafe _openGap( + at: subrange.upperBound, count: newItemCount - subrange.count) + } else if newItemCount < subrange.count { + _closeGap( + at: subrange.lowerBound + newItemCount, count: subrange.count - newItemCount) + } + _count += newItemCount - subrange.count + let gapRange = unsafe Range( + uncheckedBounds: (subrange.lowerBound, subrange.lowerBound + newItemCount)) + return unsafe _storage.extracting(gapRange) + } + /// 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 @@ -452,30 +478,21 @@ extension RigidArray where Element: ~Copyable { /// /// - Returns: A buffer pointer addressing the newly opened gap, to be /// initialized by the caller. - @inlinable + @available(*, deprecated) // FIXME: Obsolete, remove this + @usableFromInline @unsafe internal mutating func _gapForReplacement( - of subrange: Range, withNewCount newCount: Int + of subrange: Range, newItemCount: Int ) -> UnsafeMutableBufferPointer { precondition( subrange.lowerBound >= 0 && subrange.upperBound <= _count, "Index range out of bounds") - precondition(newCount >= 0, "Cannot add a negative number of items") + precondition(newItemCount >= 0, "Cannot add a negative number of items") precondition( - newCount - subrange.count <= freeCapacity, + newItemCount - subrange.count <= freeCapacity, "RigidArray capacity overflow") unsafe _items.extracting(subrange).deinitialize() - if newCount > subrange.count { - _ = unsafe _openGap( - at: subrange.upperBound, count: newCount - subrange.count) - } else if newCount < subrange.count { - _closeGap( - at: subrange.lowerBound + newCount, count: subrange.count - newCount) - } - _count += newCount - subrange.count - let gapRange = unsafe Range( - uncheckedBounds: (subrange.lowerBound, subrange.lowerBound + newCount)) - return unsafe _storage.extracting(gapRange) + return _resizeGap(in: subrange, to: newItemCount) } } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift index 999c7384..cdb73ed9 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift @@ -36,6 +36,37 @@ extension UniqueArray where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { + /// Append a given number of items to the end of this array by populating + /// an output span. + /// + /// If the array does not have sufficient capacity to hold the requested + /// number of new elements, then this reallocates the array's storage to + /// grow its capacity, using a geometric growth rate. + /// + /// If the callback fails to fully populate its output span or if + /// it throws an error, then the array keeps all items that were + /// successfully initialized before the callback terminated the insertion. + /// + /// - Parameters: + /// - newItemCount: The number of items to append to the array. + /// - initializer: A callback that gets called at most once to directly + /// populate newly reserved storage within the array. The function + /// 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). + /// + /// - Complexity: O(`uninitializedCount`) + @_alwaysEmitIntoClient + public mutating func append( + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + _ensureFreeCapacity(newItemCount) + return try _storage.append( + addingCount: newItemCount, + initializingWith: initializer) + } + /// Append a given number of items to the end of this array by populating /// an output span. /// @@ -45,20 +76,25 @@ extension UniqueArray where Element: ~Copyable { /// /// - Parameters /// - count: The number of items to append to the array. - /// - body: A callback that gets called at most once to directly + /// - initializer: A callback that gets called exactly once to directly /// populate newly reserved storage within the array. The function /// is allowed to initialize fewer than `count` items. The array is /// appended however many items the callback adds to the output span /// before it returns (or before it throws an error). /// /// - Complexity: O(`count`) + @available(*, deprecated, renamed: "append(addingCount:initializingWith:)") @_alwaysEmitIntoClient + @inline(__always) public mutating func append( count: Int, - initializingWith body: (inout OutputSpan) throws(E) -> Result + initializingWith initializer: (inout OutputSpan) throws(E) -> Result ) throws(E) -> Result { - _ensureFreeCapacity(count) - return try _storage.append(count: count, initializingWith: body) + var result: Result? = nil + try append(addingCount: count) { target throws(E) in + result = try initializer(&target) + } + return result.take()! } } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift index c5cd3475..90dd25d4 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift @@ -51,12 +51,23 @@ extension UniqueArray where Element: ~Copyable { /// position, using a callback to directly initialize array storage by /// populating an output span. /// - /// All existing elements at or following the specified position are moved to - /// make room for the new items. + /// Existing elements in the array's storage are moved towards the back as + /// needed to make room for the new items. /// /// If the array does not have sufficient capacity to hold the new elements, - /// then this reallocates storage to extend its capacity, using a geometric - /// growth rate. + /// then this operation reallocates storage to extend its capacity, using a + /// geometric growth rate. + /// + /// var buffer = UniqueArray() + /// buffer.append([-999, 999]) + /// var i = 0 + /// buffer.insert(capacity: 3, at: 1) { target in + /// while !target.isFull { + /// target.append(i) + /// i += 1 + /// } + /// } + /// // `buffer` now contains [-999, 0, 1, 2, 999] /// /// - Parameters: /// - count: The number of items to insert into the array. @@ -68,15 +79,53 @@ extension UniqueArray where Element: ~Copyable { /// supplied count, and it must fully populate it before returning. /// /// - Complexity: O(`self.count` + `count`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert( + addingCount newItemCount: Int, + at index: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + _ensureFreeCapacity(newItemCount) + try _storage.insert( + addingCount: newItemCount, + at: index, + initializingWith: initializer) + } + + /// Inserts a given number of new items into this array at the specified + /// position, using a callback to directly initialize array storage by + /// populating an output span. + /// + /// All existing elements at or following the specified position are moved to + /// make room for the new items. + /// + /// If the array does not have sufficient capacity to hold the new elements, + /// then this reallocates storage to extend its capacity, using a geometric + /// growth rate. + /// + /// - Parameters: + /// - count: The number of items to insert into the array. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the array. + /// - 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 matching the + /// supplied count, and it must fully populate it before returning. + /// + /// - Complexity: O(`self.count` + `count`) + @available(*, deprecated, renamed: "insert(addingCount:at:initializingWith:)") @inlinable public mutating func insert( count: Int, at index: Int, initializingWith body: (inout OutputSpan) -> Result ) -> Result { - // FIXME: This does not allow `body` to throw, to prevent having to move the tail twice. Is that okay? - _ensureFreeCapacity(count) - return _storage.insert(count: count, at: index, initializingWith: body) + var result: Result? = nil + self.insert(addingCount: count, at: index) { target in + result = body(&target) + } + return result! } } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift index 376cf430..619c72f4 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift @@ -157,7 +157,7 @@ extension UniqueArray where Element: ~Copyable { /// passing an input span to the given function to consume them in place. /// /// - Parameter bounds: The subrange of items to consume from this array. - /// - Parameter body: A function taking an input span of the removed items, + /// - 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 not required to consume all items in the span; /// however, the span's remaining items will still be removed from @@ -167,9 +167,9 @@ extension UniqueArray where Element: ~Copyable { @_alwaysEmitIntoClient public mutating func consumeSubrange( _ bounds: Range, - consumingWith body: (inout InputSpan) throws(E) -> Result + consumingWith consumer: (inout InputSpan) throws(E) -> Result ) throws(E) -> Result { - try _storage.consumeSubrange(bounds, consumingWith: body) + try _storage.consumeSubrange(bounds, consumingWith: consumer) } } #endif diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift index 3eac8b2b..8c7c0e2a 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift @@ -18,6 +18,65 @@ import ContainersPreview @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { + /// 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. + /// + /// The number of new items need not match the number of elements being + /// removed. + /// + /// This method has the same overall effect as calling + /// + /// try array.removeSubrange(subrange) + /// try array.insert( + /// addingCount: newItemCount, + /// at: subrange.lowerBound, + /// initializingWith: initializer) + /// + /// Except it performs faster (by a constant factor), by avoiding moving + /// some items in the array twice. + /// + /// 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 the callback fails to fully populate its output span or if + /// it throws an error, then the array keeps all items that were + /// successfully initialized before the callback terminated the prepend. + /// + /// Partial insertions create a gap in array 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 array to replace. The bounds of + /// the range must be valid indices in the array. + /// - newItemCount: the maximum number of items to replace the old subrange. + /// - 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. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations. + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + precondition( + subrange.lowerBound >= 0 && subrange.upperBound <= self.count, + "Index range out of bounds") + 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._uncheckedReplaceSubrange( + subrange, + addingCount: newItemCount, + initializingWith: initializer) + } + /// 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. @@ -43,28 +102,99 @@ 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. /// - newCount: the number of items to replace the old subrange. - /// - body: A callback that gets called at most once to directly + /// - 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: "replaceSubrange(_:addingCapacity:initializingWith:)") @inlinable public mutating func replaceSubrange( _ subrange: Range, newCount: Int, initializingWith body: (inout OutputSpan) -> Result ) -> Result { - // FIXME: Should we allow throwing (and a partially filled output span)? - // FIXME: Should we have a version of this with two closures, to allow custom-consuming the old items? - // replaceSubrange(5..<10, newCount: 3, consumingWith: {...}, initializingWith: {...}) - // FIXME: Avoid moving the subsequent elements twice. - _ensureFreeCapacity(newCount - subrange.count) - return _storage.replaceSubrange( - subrange, newCount: newCount, initializingWith: body) + var result: Result? = nil + self.replaceSubrange(subrange, addingCount: newCount) { target in + result = body(&target) + } + return result! } } +@available(SwiftStdlib 5.0, *) +extension UniqueArray where Element: ~Copyable { +#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Replaces the specified range of elements by a given count of new items, + /// using callbacks to consume old items, and to then insert new ones. + /// + /// The number of new items need not match the number of elements being + /// removed. + /// + /// This method has the same overall effect as calling + /// + /// try array.consume(subrange, consumingWith: consumer) + /// try array.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 array does not have sufficient capacity to perform the replacement, + /// then this reallocates storage to extend its capacity, using a geometric + /// growth rate. + /// + /// 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 array before insertions begin. + /// + /// The `initializer` callback is not required to fully populate its + /// output span, and it is allowed to throw an error. In such cases, the + /// deque keeps all items that were successfully initialized before the + /// callback terminated. + /// + /// Partial insertions create a gap in array 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. + /// - consumer: A callback that gets called at most once to consume + /// the elements to be removed directly from the deque's storage. The + /// function is always called with a non-empty input span. + /// - 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. + /// + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the + /// complexity of the callback invocations. + @inlinable + public mutating func replaceSubrange( + _ subrange: Range, + addingCount newItemCount: Int, + consumingWith consumer: (inout InputSpan) -> Void, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) -> Void { + precondition( + subrange.lowerBound >= 0 && subrange.upperBound <= self.count, + "Index range out of bounds") + precondition(newItemCount >= 0, "Cannot add a negative number of items") + _ensureFreeCapacity(newItemCount - subrange.count) + try _storage._uncheckedReplaceSubrange( + subrange, + addingCount: newItemCount, + consumingWith: consumer, + initializingWith: initializer) + } +#endif +} + @available(SwiftStdlib 5.0, *) extension UniqueArray where Element: ~Copyable { /// Replaces the specified range of elements by moving the elements of a diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift index 06f0e70b..05bc0695 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift @@ -19,12 +19,32 @@ import ContainersPreview @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: ~Copyable { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW + /// Remove the specified subrange of items from this deque, + /// passing a series of input spans to a given callback function to consume + /// them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - 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. + /// The function is called at most once. + /// + /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient @inline(__always) public mutating func consume( _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void ) { + precondition( + subrange.lowerBound >= 0 && subrange.upperBound <= self.count, + "Subrange out of bounds") let segments = self._handle.mutableSegments(forOffsets: subrange) var span = InputSpan(buffer: segments.first, initializedCount: segments.first.count) @@ -37,6 +57,23 @@ extension RigidDeque where Element: ~Copyable { } } + /// Remove the specified subrange of items from this deque, + /// passing a series of input spans to a given callback function to consume + /// them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - 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. + /// The function is called at most once. + /// + /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient @inline(__always) public mutating func consume>( @@ -46,6 +83,20 @@ extension RigidDeque where Element: ~Copyable { consume(subrange.relative(to: indices), consumingWith: consumer) } + /// Remove all items currently in this deque, passing a series of input + /// spans to a given callback function to consume them in place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter consumer: A function taking an input span of the removed items, + /// allowing them to be consumed straight out of the deque's storage. + /// The function is called at most once. + /// - Complexity: O(`self.count`) @_alwaysEmitIntoClient @inline(__always) public mutating func consumeAll( @@ -53,6 +104,64 @@ extension RigidDeque where Element: ~Copyable { ) { consume(indices, consumingWith: consumer) } + + /// Remove the specified number of items from the end of this deque, + /// passing an input span to a given callback function to consume them in + /// place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter n: The number of items to consume from the end of the deque. + /// `n` must be greater than or equal to zero and must not exceed + /// the count of the 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. + /// - Complexity: O(`n`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consumeLast( + _ n: Int, + consumingWith consumer: (inout InputSpan) -> Void + ) { + precondition( + n >= 0 && n <= self.count, + "Count of elements to consume is out of bounds") + consume(self.count &- n ..< self.count, consumingWith: consumer) + } + + /// Remove the specified number of items from the front of this deque, + /// passing an input span to a given callback function to consume them in + /// place. + /// + /// The callback is not required to fully consume the contents of its + /// argument; any items it leaves in the input span get automatically + /// consumed. The underlying storage isn't necessarily contiguous, so + /// the callback may be called more than once, whether or not it fully + /// consumes its input. If the specified range is empty, the callback + /// may not be called at all. + /// + /// - Parameter n: The number of items to consume from the front of the deque. + /// `n` must be greater than or equal to zero and must not exceed + /// the count of the 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. + /// - Complexity: O(`n`) + @_alwaysEmitIntoClient + @inline(__always) + public mutating func consumeFirst( + _ n: Int, + consumingWith consumer: (inout InputSpan) -> Void + ) { + precondition( + n >= 0 && n <= self.count, + "Count of elements to consume is out of bounds") + consume(0 ..< n, consumingWith: consumer) + } #endif } @@ -81,6 +190,26 @@ extension RigidDeque where Element: ~Copyable { public mutating func consumeAll() -> SubrangeConsumer { consume(indices) } + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consumeLast(_ n: Int) -> SubrangeConsumer { + precondition( + n >= 0 && n <= self.count, + "Count of elements to consume is out of bounds") + return consume(self.count - n ..< self.count) + } + + @_alwaysEmitIntoClient + @inline(__always) + @_lifetime(&self) + public mutating func consumeFirst(_ n: Int) -> SubrangeConsumer { + precondition( + n >= 0 && n <= self.count, + "Count of elements to consume is out of bounds") + return consume(0 ..< n) + } } @available(SwiftStdlib 5.0, *) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift index a402fe96..aa7f72a2 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift @@ -61,7 +61,7 @@ extension RigidDeque where Element: ~Copyable { /// var buffer = RigidDeque(capacity: 20) /// buffer.append([-999, 999]) /// var i = 0 - /// buffer.insert(capacity: 3, at: 1) { target in + /// buffer.insert(addingCount: 3, at: 1) { target in /// while !target.isFull { /// target.append(i) /// i += 1 @@ -82,27 +82,27 @@ extension RigidDeque where Element: ~Copyable { /// many items as promised. /// /// - Parameters: - /// - maximumCount: The maximum number of items to insert into the deque. + /// - 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. - /// - body: A callback that gets called at most twice to directly + /// - 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` + `maximumCount`) in addition to the complexity + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity /// of the callback invocations. @_alwaysEmitIntoClient @inline(__always) public mutating func insert( - maximumCount: Int, + addingCount newItemCount: Int, at index: Int, - initializingWith body: (inout OutputSpan) throws(E) -> Void + initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) { precondition(index >= 0 && index <= self.count, "Index out of bounds") - precondition(maximumCount >= 0, "Cannot add a negative number of items") - precondition(maximumCount <= freeCapacity, "RigidDeque capacity overflow") + precondition(newItemCount >= 0, "Cannot add a negative number of items") + precondition(newItemCount <= freeCapacity, "RigidDeque capacity overflow") try _handle.uncheckedInsert( - maximumCount: maximumCount, at: index, initializingWith: body) + addingCount: newItemCount, at: index, initializingWith: initializer) } } @@ -133,7 +133,7 @@ extension RigidDeque where Element: ~Copyable { ) { guard !items.isEmpty else { return } var remainder = items - insert(maximumCount: items.count, at: index) { target in + insert(addingCount: items.count, at: index) { target in target._withUnsafeMutableBufferPointer { buffer, count in buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) @@ -207,7 +207,7 @@ extension RigidDeque where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: ~Copyable { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - /// Inserts at most `maximumCount` items generated by a producer into this + /// 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 @@ -218,32 +218,32 @@ extension RigidDeque where Element: ~Copyable { /// 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 `maximumCount`, or the producer hitting its end, or - /// throwing an error. If the producer has more than `maximumCount` items + /// 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 `maximumCount` items, then it results + /// 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: - /// - maximumCount: The maximum number of items to insert into the deque. + /// - 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` + `maximumCount`) + /// - Complexity: O(`self.count` + `newItemCount`) @_alwaysEmitIntoClient public mutating func insert< P: Producer & ~Copyable & ~Escapable >( - maximumCount: Int, + addingCount newItemCount: Int, from producer: inout P, at index: Int ) throws(P.ProducerError) { - try insert(maximumCount: maximumCount, at: index) { target throws(P.ProducerError) in + try insert(addingCount: newItemCount, at: index) { target throws(P.ProducerError) in while !target.isFull, try producer.generate(into: &target) { // Do nothing } @@ -274,14 +274,14 @@ extension RigidDeque /* where Element: Copyable */ { /// - index: The position at which to insert the new elements. It must be /// a valid index of `self`. /// - /// - Complexity: O(`count` + `newElements.count`) + /// - Complexity: O(`count` + `items.count`) @inlinable public mutating func insert( copying items: UnsafeBufferPointer, at index: Int ) { guard items.count > 0 else { return } var remainder = items - insert(maximumCount: remainder.count, at: index) { target in + insert(addingCount: remainder.count, at: index) { target in target._withUnsafeMutableBufferPointer { buffer, count in buffer.initializeAll( fromContentsOf: remainder._extracting(first: buffer.count)) @@ -312,7 +312,7 @@ extension RigidDeque /* where Element: Copyable */ { /// - index: The position at which to insert the new elements. It must be /// a valid index of `self`. /// - /// - Complexity: O(`count` + `newElements.count`) + /// - Complexity: O(`count` + `items.count`) @inlinable public mutating func insert( copying items: UnsafeMutableBufferPointer, @@ -360,11 +360,11 @@ extension RigidDeque /* where Element: Copyable */ { ) { let expectedCount = self.count + newCount var it = items.makeBorrowingIterator() - insert(maximumCount: newCount, at: index) { target in + insert(addingCount: newCount, at: index) { target in it.copyContents(into: &target) } precondition( - it.nextSpan().isEmpty && count == expectedCount, + it.nextSpan().isEmpty && self.count == expectedCount, "Broken Container: count doesn't match contents") } #endif @@ -381,7 +381,7 @@ extension RigidDeque /* where Element: Copyable */ { if done != nil { return } var i = items.startIndex - self.insert(maximumCount: newCount, at: index) { target in + self.insert(addingCount: newCount, at: index) { target in while !target.isFull { target.append(items[i]) items.formIndex(after: &i) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift index 1fbb3c6f..402a51f5 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift @@ -97,20 +97,20 @@ extension RigidDeque where Element: ~Copyable { /// // `buffer` now contains [0, 1, 2, 3, 999] /// /// - Parameters - /// - maximumCount: The maximum number of items to prepend to the deque. + /// - 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. /// - /// - Complexity: O(`maximumCount`) in addition to the complexity of the callback + /// - Complexity: O(`newItemCount`) in addition to the complexity of the callback /// invocations. @_alwaysEmitIntoClient public mutating func prepend( - maximumCount: Int, + addingCount newItemCount: Int, initializingWith body: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Void { - precondition(maximumCount >= 0, "Cannot prepend a negative number of items") - precondition(freeCapacity >= maximumCount, "RigidDeque capacity overflow") - try _handle.uncheckedPrepend(maximumCount: maximumCount, initializingWith: body) + precondition(newItemCount >= 0, "Cannot prepend a negative number of items") + precondition(freeCapacity >= newItemCount, "RigidDeque capacity overflow") + try _handle.uncheckedPrepend(addingCount: newItemCount, initializingWith: body) } } @@ -214,7 +214,7 @@ extension RigidDeque where Element: ~Copyable { from producer: inout P ) throws(P.ProducerError) { try self.prepend( - maximumCount: maximumCount ?? freeCapacity + addingCount: maximumCount ?? freeCapacity ) { target throws(P.ProducerError) in try producer.generate(into: &target) } @@ -307,7 +307,7 @@ extension RigidDeque /*where Element: Copyable*/ { exactCount: Int ) { var it = items.makeBorrowingIterator() - self.prepend(maximumCount: exactCount) { target in + self.prepend(addingCount: exactCount) { target in let span = it.nextSpan(maximumCount: target.freeCapacity) target._append(copying: span) } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift index 174903d1..137a92f2 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift @@ -22,23 +22,21 @@ extension RigidDeque where Element: ~Copyable { /// using a callback to directly initialize deque storage by populating /// a series of output spans. /// - /// This method has the effect of removing the specified range of elements - /// from the deque 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. + /// 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. /// - /// If you pass a zero-length range as the `subrange` parameter, then - /// this method is equivalent to calling - /// `insert(maximumCount: 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)`. - /// - /// The newly prepended items are not guaranteed to form a single contiguous + /// 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 @@ -53,28 +51,29 @@ extension RigidDeque where Element: ~Copyable { /// - Parameters /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. - /// - maximumCount: the maximum number of items to replace the old subrange. + /// - 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`) + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity + /// of the callback invocations. @inlinable public mutating func replaceSubrange( _ subrange: Range, - maximumCount: Int, + addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Void { precondition( subrange.lowerBound >= 0 && subrange.upperBound <= count, "Subrange out of bounds") - precondition(maximumCount >= 0, "Can't insert a negative number of items") + precondition(newItemCount >= 0, "Cannot add a negative number of items") precondition( - count - subrange.count + maximumCount <= capacity, + count - subrange.count + newItemCount <= capacity, "RigidDeque capacity overflow") try _handle.uncheckedReplaceSubrange( subrange, - newCount: capacity, + addingCount: newItemCount, initializingWith: initializer) } @@ -88,25 +87,34 @@ extension RigidDeque where Element: ~Copyable { /// This method has the same overall effect as calling /// /// try deque.consume(subrange, consumingWith: consumer) - /// try deque.insert(maximumCount: maximumCount, at: subrange.lowerBound, initializingWith: initializer) + /// 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 specified + /// If the deque doesn't have sufficient capacity to accommodate the specified /// number of new elements, then this method triggers a runtime error. /// - /// The removed and newly inserted items are not guaranteed to form a single - /// contiguous storage region. Therefore, the supplied callbacks may be + /// 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 - /// consumed. + /// 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 - /// deque keeps all items that were successfully initialized before the - /// callback terminated. + /// 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 @@ -116,7 +124,7 @@ extension RigidDeque where Element: ~Copyable { /// - Parameters /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. - /// - maximumCount: the maximum number of items to replace the old subrange. + /// - newItemCount: the maximum number of items to replace the old subrange. /// - consumer: A callback that gets called at most twice to consume /// the elements to be removed directly from the deque's storage. The /// function is always called with a non-empty input span. @@ -124,25 +132,25 @@ extension RigidDeque where Element: ~Copyable { /// populate newly reserved storage within the deque. The function /// is always called with an empty output span. /// - /// - Complexity: O(`self.count` + `maximumCount`) in addition to the complexity - /// of the callback invocations. + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the + /// complexity of the callback invocations. @inlinable public mutating func replaceSubrange( _ subrange: Range, - maximumCount: Int, + addingCount newItemCount: Int, consumingWith consumer: (inout InputSpan) -> Void, initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Void { precondition( subrange.lowerBound >= 0 && subrange.upperBound <= count, "Subrange out of bounds") - precondition(maximumCount >= 0, "Cannot add a negative number of items") + precondition(newItemCount >= 0, "Cannot add a negative number of items") precondition( - count - subrange.count + maximumCount <= capacity, + count - subrange.count + newItemCount <= capacity, "RigidDeque capacity overflow") try _handle.uncheckedReplaceSubrange( subrange, - newCount: capacity, + addingCount: newItemCount, consumingWith: consumer, initializingWith: initializer) } @@ -185,7 +193,7 @@ extension RigidDeque where Element: ~Copyable { moving items: UnsafeMutableBufferPointer, ) { var remainder = items - replaceSubrange(subrange, maximumCount: remainder.count) { target in + replaceSubrange(subrange, addingCount: remainder.count) { target in target._withUnsafeMutableBufferPointer { buffer, count in buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) @@ -274,7 +282,7 @@ extension RigidDeque where Element: ~Copyable { } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - /// Replaces the specified range of elements by at most `maximumCount` items + /// 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 @@ -294,12 +302,12 @@ extension RigidDeque where Element: ~Copyable { /// directly expressed by calling `removeSubrange`. /// /// This operation inserts as many items as the producer can generate before - /// either reaching `maximumCount`, or the producer hitting its end, or - /// throwing an error. If the producer has more than `maximumCount` items left in + /// 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 `maximumCount` items, then it results in + /// 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. @@ -307,7 +315,7 @@ extension RigidDeque where Element: ~Copyable { /// - Parameters /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. - /// - maximumCount: The maximum number of items to insert into 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` + `maximumCount`) @@ -316,10 +324,10 @@ extension RigidDeque where Element: ~Copyable { P: Producer & ~Copyable & ~Escapable >( _ subrange: Range, - maximumCount: Int, + addingCount newItemCount: Int, from producer: inout P ) throws(P.ProducerError) { - try replaceSubrange(subrange, maximumCount: maximumCount) { target throws(P.ProducerError) in + try replaceSubrange(subrange, addingCount: newItemCount) { target throws(P.ProducerError) in try producer.generate(into: &target) } } @@ -360,7 +368,7 @@ extension RigidDeque /* where Element: Copyable */ { copying items: UnsafeBufferPointer ) { var remainder = items - replaceSubrange(subrange, maximumCount: remainder.count) { target in + replaceSubrange(subrange, addingCount: remainder.count) { target in target._withUnsafeMutableBufferPointer { dst, dstCount in dst.initializeAll(fromContentsOf: remainder._trim(first: dst.count)) dstCount += dst.count @@ -453,7 +461,7 @@ extension RigidDeque /* where Element: Copyable */ { let expectedCount = self.count - subrange.count + newCount var it = items.makeBorrowingIterator() - self.replaceSubrange(subrange, maximumCount: newCount) { target in + self.replaceSubrange(subrange, addingCount: newCount) { target in it.copyContents(into: &target) } precondition( @@ -477,7 +485,7 @@ extension RigidDeque /* where Element: Copyable */ { if done != nil { return } var i = items.startIndex - self.replaceSubrange(subrange, maximumCount: newCount) { target in + self.replaceSubrange(subrange, addingCount: newCount) { target in while !target.isFull { target.append(items[i]) items.formIndex(after: &i) diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift index 1c981db0..bfbc626f 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift @@ -2,7 +2,7 @@ // // This source file is part of the Swift Collections open source project // -// Copyright (c) 2025 Apple Inc. and the Swift project authors +// Copyright (c) 2025 - 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 @@ -64,7 +64,7 @@ extension UniqueDeque where Element: ~Copyable { /// var buffer = UniqueDeque(capacity: 20) /// buffer.append([-999, 999]) /// var i = 0 - /// buffer.insert(capacity: 3, at: 1) { target in + /// buffer.insert(addingCount: 3, at: 1) { target in /// while !target.isFull { /// target.append(i) /// i += 1 @@ -85,28 +85,28 @@ extension UniqueDeque where Element: ~Copyable { /// many items as promised. /// /// - Parameters: - /// - maximumCount: The maximum number of items to insert into the deque. + /// - 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. - /// - body: A callback that gets called at most twice to directly + /// - 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` + `maximumCount`) in addition to the complexity + /// - 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) public mutating func insert( - maximumCount: Int, + addingCount newItemCount: Int, at index: Int, - initializingWith body: (inout OutputSpan) throws(E) -> Void + initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) { precondition(index >= 0 && index <= self.count, "Index out of bounds") - precondition(maximumCount >= 0, "Cannot add a negative number of items") - _ensureFreeCapacity(maximumCount) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + _ensureFreeCapacity(newItemCount) try _storage._handle.uncheckedInsert( - maximumCount: maximumCount, at: index, initializingWith: body) + addingCount: newItemCount, at: index, initializingWith: initializer) } } @@ -139,7 +139,7 @@ extension UniqueDeque where Element: ~Copyable { ) { guard !items.isEmpty else { return } var remainder = items - insert(maximumCount: items.count, at: index) { target in + insert(addingCount: items.count, at: index) { target in target._withUnsafeMutableBufferPointer { buffer, count in buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) @@ -217,7 +217,7 @@ extension UniqueDeque where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension UniqueDeque where Element: ~Copyable { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW - /// Inserts at most `maximumCount` items generated by a producer into this + /// 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 @@ -229,33 +229,33 @@ extension UniqueDeque where Element: ~Copyable { /// geometric growth rate. /// /// This operation inserts as many items as the producer can generate before - /// either reaching `maximumCount`, or the producer hitting its end, or - /// throwing an error. If the producer has more than `maximumCount` items + /// 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 `maximumCount` items, then it results + /// 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: - /// - maximumCount: The maximum number of items to insert into the deque. + /// - 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` + `maximumCount`) when amortized over many + /// - Complexity: O(`self.count` + `newItemCount`) when amortized over many /// similar invocations on the same deque. @_alwaysEmitIntoClient public mutating func insert< P: Producer & ~Copyable & ~Escapable >( - maximumCount: Int, + addingCount newItemCount: Int, from producer: inout P, at index: Int ) throws(P.ProducerError) { - try insert(maximumCount: maximumCount, at: index) { target throws(P.ProducerError) in + try insert(addingCount: newItemCount, at: index) { target throws(P.ProducerError) in while !target.isFull, try producer.generate(into: &target) { // Do nothing } @@ -295,7 +295,7 @@ extension UniqueDeque /* where Element: Copyable */ { ) { guard items.count > 0 else { return } var remainder = items - insert(maximumCount: remainder.count, at: index) { target in + insert(addingCount: remainder.count, at: index) { target in target._withUnsafeMutableBufferPointer { buffer, count in buffer.initializeAll( fromContentsOf: remainder._extracting(first: buffer.count)) @@ -378,7 +378,7 @@ extension UniqueDeque /* where Element: Copyable */ { ) { let expectedCount = self.count + newCount var it = items.makeBorrowingIterator() - insert(maximumCount: newCount, at: index) { target in + insert(addingCount: newCount, at: index) { target in it.copyContents(into: &target) } precondition( @@ -399,7 +399,7 @@ extension UniqueDeque /* where Element: Copyable */ { if done != nil { return } var i = items.startIndex - self.insert(maximumCount: newCount, at: index) { target in + self.insert(addingCount: newCount, at: index) { target in while !target.isFull { target.append(items[i]) items.formIndex(after: &i) diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift index 3920cb5d..6ed91d33 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift @@ -95,7 +95,7 @@ extension UniqueDeque where Element: ~Copyable { guard maximumCount > 0 else { return } _ensureFreeCapacity(maximumCount) try _storage._handle.uncheckedPrepend( - maximumCount: maximumCount, initializingWith: body) + addingCount: maximumCount, initializingWith: body) } } @@ -209,7 +209,7 @@ extension UniqueDeque where Element: ~Copyable { if let maximumCount { _ensureFreeCapacity(maximumCount) try _storage._handle.uncheckedPrepend( - maximumCount: maximumCount + addingCount: maximumCount ) { target throws(P.ProducerError) in while !target.isFull, try producer.generate(into: &target) { // Do nothing diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift index bacfd983..ac319b09 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift @@ -22,29 +22,41 @@ extension UniqueDeque where Element: ~Copyable { /// using a callback to directly initialize deque storage by populating /// a series of output spans. /// - /// This method has the effect of removing the specified range of elements - /// from the deque 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. + /// 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. /// - /// If you pass a zero-length range as the `subrange` parameter, then - /// this method is equivalent to calling - /// `insert(maximumCount: newCount, at: subrange.lowerBound, initializingWith: body)`. + /// 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. /// - /// 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)`. + /// 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 newly prepended 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 prepend. + /// 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 @@ -54,7 +66,7 @@ extension UniqueDeque where Element: ~Copyable { /// - Parameters /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. - /// - maximumCount: the maximum number of items to replace the old subrange. + /// - 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. @@ -63,17 +75,17 @@ extension UniqueDeque where Element: ~Copyable { @inlinable public mutating func replaceSubrange( _ subrange: Range, - maximumCount: Int, + addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Void { precondition( subrange.lowerBound >= 0 && subrange.upperBound <= count, "Subrange out of bounds") - precondition(maximumCount >= 0, "Cannot add a negative number of items") - _ensureFreeCapacity(maximumCount - subrange.count) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + _ensureFreeCapacity(newItemCount - subrange.count) try _storage._handle.uncheckedReplaceSubrange( subrange, - newCount: capacity, + addingCount: capacity, initializingWith: initializer) } @@ -87,7 +99,10 @@ extension UniqueDeque where Element: ~Copyable { /// This method has the same overall effect as calling /// /// try deque.consume(subrange, consumingWith: consumer) - /// try deque.insert(maximumCount: maximumCount, at: subrange.lowerBound, initializingWith: initializer) + /// 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. @@ -116,7 +131,7 @@ extension UniqueDeque where Element: ~Copyable { /// - Parameters /// - subrange: The subrange of the deque to replace. The bounds of /// the range must be valid indices in the deque. - /// - maximumCount: the maximum number of items to replace the old subrange. + /// - newItemCount: the maximum number of items to replace the old subrange. /// - consumer: A callback that gets called at most twice to consume /// the elements to be removed directly from the deque's storage. The /// function is always called with a non-empty input span. @@ -124,23 +139,23 @@ extension UniqueDeque where Element: ~Copyable { /// populate newly reserved storage within the deque. The function /// is always called with an empty output span. /// - /// - Complexity: O(`self.count` + `maximumCount`) in addition to the complexity + /// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity /// of the callback invocations. @inlinable public mutating func replaceSubrange( _ subrange: Range, - maximumCount: Int, + addingCount newItemCount: Int, consumingWith consumer: (inout InputSpan) -> Void, initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Void { precondition( subrange.lowerBound >= 0 && subrange.upperBound <= count, "Subrange out of bounds") - precondition(maximumCount >= 0, "Cannot add a negative number of items") - _ensureFreeCapacity(maximumCount - subrange.count) + precondition(newItemCount >= 0, "Cannot add a negative number of items") + _ensureFreeCapacity(newItemCount - subrange.count) try _storage._handle.uncheckedReplaceSubrange( subrange, - newCount: capacity, + addingCount: newItemCount, consumingWith: consumer, initializingWith: initializer) } @@ -184,7 +199,7 @@ extension UniqueDeque where Element: ~Copyable { moving items: UnsafeMutableBufferPointer, ) { var remainder = items - replaceSubrange(subrange, maximumCount: remainder.count) { target in + replaceSubrange(subrange, addingCount: remainder.count) { target in target._withUnsafeMutableBufferPointer { buffer, count in buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) @@ -318,10 +333,10 @@ extension UniqueDeque where Element: ~Copyable { P: Producer & ~Copyable & ~Escapable >( _ subrange: Range, - maximumCount: Int, + addingCount newItemCount: Int, from producer: inout P ) throws(P.ProducerError) { - try replaceSubrange(subrange, maximumCount: maximumCount) { target throws(P.ProducerError) in + try replaceSubrange(subrange, addingCount: newItemCount) { target throws(P.ProducerError) in while !target.isFull, try producer.generate(into: &target) { // Do nothing } @@ -365,7 +380,7 @@ extension UniqueDeque /* where Element: Copyable */ { copying items: UnsafeBufferPointer ) { var remainder = items - replaceSubrange(subrange, maximumCount: remainder.count) { target in + replaceSubrange(subrange, addingCount: remainder.count) { target in target._withUnsafeMutableBufferPointer { dst, dstCount in dst.initializeAll(fromContentsOf: remainder._trim(first: dst.count)) dstCount += dst.count @@ -460,7 +475,7 @@ extension UniqueDeque /* where Element: Copyable */ { let expectedCount = self.count - subrange.count + newCount var it = items.makeBorrowingIterator() - self.replaceSubrange(subrange, maximumCount: newCount) { target in + self.replaceSubrange(subrange, addingCount: newCount) { target in it.copyContents(into: &target) } precondition( @@ -484,7 +499,7 @@ extension UniqueDeque /* where Element: Copyable */ { if done != nil { return } var i = items.startIndex - self.replaceSubrange(subrange, maximumCount: newCount) { target in + self.replaceSubrange(subrange, addingCount: newCount) { target in while !target.isFull { target.append(items[i]) items.formIndex(after: &i) diff --git a/Sources/DequeModule/_UnsafeDequeHandle.swift b/Sources/DequeModule/_UnsafeDequeHandle.swift index 89416880..4eb6bf20 100644 --- a/Sources/DequeModule/_UnsafeDequeHandle.swift +++ b/Sources/DequeModule/_UnsafeDequeHandle.swift @@ -740,15 +740,15 @@ extension _UnsafeDequeHandle where Element: ~Copyable { /// - Complexity: O(`count`) @_alwaysEmitIntoClient internal mutating func uncheckedPrepend( - maximumCount: Int, + addingCount newItemCount: Int, initializingWith body: (inout OutputSpan) throws(E) -> Void ) throws(E) { - guard let gap = self._prepend(count: maximumCount) else { return } + guard let gap = self._prepend(count: newItemCount) else { return } var c = 0 defer { - if c < maximumCount { - closeGap(offsets: c ..< maximumCount) + if c < newItemCount { + closeGap(offsets: c ..< newItemCount) } } try gap.first._initialize(initializedCount: &c, initializingWith: body) @@ -1208,17 +1208,17 @@ extension _UnsafeDequeHandle where Element: ~Copyable { extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient internal mutating func uncheckedInsert( - maximumCount: Int, + addingCount newItemCount: Int, at offset: Int, initializingWith body: (inout OutputSpan) throws(E) -> Void ) throws(E) { - guard maximumCount > 0 else { return } - let gap = self.openGap(ofSize: maximumCount, atOffset: offset) + guard newItemCount > 0 else { return } + let gap = self.openGap(ofSize: newItemCount, atOffset: offset) var c = 0 defer { - if c < maximumCount { - closeGap(offsets: offset + c ..< offset + maximumCount) + if c < newItemCount { + closeGap(offsets: offset + c ..< offset + newItemCount) } } try gap.first._initialize(initializedCount: &c, initializingWith: body) @@ -1346,12 +1346,12 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient internal mutating func _insertAfterReplace( _ subrange: Range, - newCount: Int, + addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Void { // 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 = newCount - subrange.count + let delta = newItemCount - subrange.count let left = isLeftLeaning(subrange) if delta > 0 { _ = self.openGap( @@ -1361,12 +1361,12 @@ extension _UnsafeDequeHandle where Element: ~Copyable { self.closeGap( offsets: (left ? subrange.prefix(-delta) : subrange.suffix(-delta))) } - let newRange = Range(uncheckedBounds: (subrange.lowerBound, newCount)) + let newRange = Range(uncheckedBounds: (subrange.lowerBound, newItemCount)) let gap = self.mutableSegments(forOffsets: newRange) var c = 0 defer { - if c < newCount { + if c < newItemCount { closeGap(offsets: newRange.dropFirst(c)) } } @@ -1379,31 +1379,34 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient internal mutating func uncheckedReplaceSubrange( _ subrange: Range, - newCount: Int, + addingCount newItemCount: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Void { assert( subrange.lowerBound >= 0 && subrange.upperBound <= count, "Subrange out of bounds") - assert(newCount >= 0, "Cannot add a negative number of items") - assert(count + newCount - subrange.count <= capacity, "RigidDeque capacity overflow") + 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(subrange, newCount: newCount, initializingWith: initializer) + try _insertAfterReplace( + subrange, + addingCount: newItemCount, + initializingWith: initializer) } #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW @_alwaysEmitIntoClient internal mutating func uncheckedReplaceSubrange( _ subrange: Range, - newCount: Int, + addingCount newItemCount: Int, consumingWith consumer: (inout InputSpan) -> Void, initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Void { assert( subrange.lowerBound >= 0 && subrange.upperBound <= count, "Subrange out of bounds") - assert(newCount >= 0, "Cannot add a negative number of items") - assert(count + newCount - subrange.count <= capacity, "RigidDeque capacity overflow") + assert(newItemCount >= 0, "Cannot add a negative number of items") + assert(count + newItemCount - subrange.count <= capacity, "RigidDeque capacity overflow") do { let removed = self.mutableSegments(forOffsets: subrange) var span = InputSpan( @@ -1415,7 +1418,10 @@ extension _UnsafeDequeHandle where Element: ~Copyable { consumer(&span) } } - try _insertAfterReplace(subrange, newCount: newCount, initializingWith: initializer) + try _insertAfterReplace( + subrange, + addingCount: newItemCount, + initializingWith: initializer) } #endif } diff --git a/Tests/DequeTests/RigidDequeTests.swift b/Tests/DequeTests/RigidDequeTests.swift index 5116dc19..a915b31f 100644 --- a/Tests/DequeTests/RigidDequeTests.swift +++ b/Tests/DequeTests/RigidDequeTests.swift @@ -612,7 +612,7 @@ final class RigidDequeTests: CollectionTestCase { data.contents.insert(contentsOf: extras, at: 0) var i = 0 - data.deque.prepend(maximumCount: prependCount) { target in + data.deque.prepend(addingCount: prependCount) { target in while !target.isFull { target.append(extras[i]) i += 1 @@ -660,7 +660,7 @@ final class RigidDequeTests: CollectionTestCase { data.contents.insert(contentsOf: extras, at: 0) var i = 0 - data.deque.prepend(maximumCount: layout.freeCapacity) { target in + data.deque.prepend(addingCount: layout.freeCapacity) { target in while !target.isFull, i < prependCount { target.append(extras[i]) i += 1 @@ -711,7 +711,7 @@ final class RigidDequeTests: CollectionTestCase { expectThrows { () throws(TestError) in var i = 0 try data.deque.prepend( - maximumCount: layout.freeCapacity + addingCount: layout.freeCapacity ) { target throws(TestError) in while !target.isFull, i < prependCount { target.append(extras[i]) @@ -1093,7 +1093,7 @@ final class RigidDequeTests: CollectionTestCase { data.contents.insert(contentsOf: extras, at: i) var j = 0 - data.deque.insert(maximumCount: c, at: i) { target in + data.deque.insert(addingCount: c, at: i) { target in expectLessThanOrEqual(target.count, extras.count - j) while !target.isFull { target.append(extras[j]) @@ -1122,7 +1122,7 @@ final class RigidDequeTests: CollectionTestCase { data.contents.insert(contentsOf: extras, at: i) var j = 0 - data.deque.insert(maximumCount: layout.freeCapacity, at: i) { target in + data.deque.insert(addingCount: layout.freeCapacity, at: i) { target in while !target.isFull, j < c { target.append(extras[j]) j += 1 @@ -1151,7 +1151,7 @@ final class RigidDequeTests: CollectionTestCase { expectThrows { () throws(TestError) in var j = 0 try data.deque.insert( - maximumCount: layout.freeCapacity, + addingCount: layout.freeCapacity, at: i ) { target throws(TestError) in while !target.isFull, j < c { @@ -1193,7 +1193,7 @@ final class RigidDequeTests: CollectionTestCase { } data.deque.insert( - maximumCount: layout.freeCapacity, + addingCount: layout.freeCapacity, from: &producer, at: i) expectEqual(extras.count, max(0, c - layout.freeCapacity)) @@ -1225,7 +1225,7 @@ final class RigidDequeTests: CollectionTestCase { expectThrows { () throws(TestError) in try data.deque.insert( - maximumCount: layout.freeCapacity, + addingCount: layout.freeCapacity, from: &producer, at: i) }