Refactor DrainableContainer/RangeReplaceableContainer/DynamicContainer

Range replacement operations generally need to invalidate all indices, and that means that we lose our position in the container after each insertion/removal, unless we happen to be using a container with looser index invalidation (such as arrays or deques).

A linked list is an example for a container type where insertions/removals need to invalidate all indices — as we need to track index validation using a single version counter that is stored in the list’s head. However, it would not be acceptable to lose our place whenever we insert a new item to the list; therefore, to mitigate the validation issue, this commit changes all range-replacement operations to return a valid index range to the affected items in the container.

This is a radical break from `RangeReplaceableCollection`. It fixes a long-standing defect with it, but it also makes it tricky to conform the same type to both protocol families, as the two require the “same” methods to return different types (`Void` vs `Range<Index>`).

Given that the LSG has intentionally diverged `UniqueArray.removeAll()` from RangeReplaceableCollection semantics, I expect this isn’t going to be an issue. For example, types with existing collection conformances can expose container views, mitigating such semantic differences.

To allow SubrangeConsumers to work without losing position, add a new protocol, `ContainerDrain` with a consuming `finalize` operation that returns a valid index in the resulting container state.

While we’re here, apply the API tweaks from SE-0527:
- Revert the `replace(removing:…:)` names, rolling back to `replaceSubrange(_:…:)` .
- Similarly, rename `consume(_:)` → `consumeSubrange(_:)`
- Rename `reallocate(capacity:)` → `setCapacity(_:)`.
This commit is contained in:
Karoy Lorentey committed 2026-09-14 20:37:12 -07:00
1 parent 1f94ac8f54
commit 5cebba6f29
48 files changed
+2502 -2397

No files matched your search

@@ -56,13 +56,14 @@ extension UniqueArray where Element: ~Copyable {
/// is allowed to initialize fewer than `uninitializedCount` items.
/// The array is appended however many items the callback adds to the
/// output span before it returns (or before it throws an error).
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`uninitializedCount`)
@_alwaysEmitIntoClient
@discardableResult
public mutating func append<E: Error>(
addingCount newItemCount: Int,
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) {
) throws(E) -> Range<Int> {
_ensureFreeCapacity(newItemCount)
return try _storage.append(
addingCount: newItemCount,
@@ -82,14 +83,15 @@ extension UniqueArray where Element: ~Copyable {
/// - Parameters:
/// - items: A fully initialized buffer whose contents to move into
/// the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`count` + `items.count`)
@_alwaysEmitIntoClient
@discardableResult
public mutating func append(
moving items: UnsafeMutableBufferPointer<Element>
) {
) -> Range<Int> {
_ensureFreeCapacity(items.count)
_storage._appendUnchecked(moving: items)
return _storage._appendUnchecked(moving: items)
}
#if UnstableContainersPreview
@@ -102,14 +104,15 @@ extension UniqueArray where Element: ~Copyable {
///
/// - Parameters:
/// - items: An input span whose contents need to be appended to this array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`items.count`)
@_alwaysEmitIntoClient
@discardableResult
public mutating func append(
moving items: inout InputSpan<Element>
) {
) -> Range<Int> {
_ensureFreeCapacity(items.count)
_storage.append(moving: &items)
return _storage.append(moving: &items)
}
#endif
@@ -122,17 +125,18 @@ extension UniqueArray where Element: ~Copyable {
///
/// - Parameters:
/// - items: An output span whose contents need to be appended to this array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`items.count`)
@_alwaysEmitIntoClient
@discardableResult
public mutating func append(
moving items: inout OutputSpan<Element>
) {
) -> Range<Int> {
_ensureFreeCapacity(items.count)
items.withUnsafeMutableBufferPointer { buffer, count in
return items.withUnsafeMutableBufferPointer { buffer, count in
let source = buffer._extracting(first: count)
unsafe _storage._appendUnchecked(moving: source)
count = 0
return unsafe _storage._appendUnchecked(moving: source)
}
}
@@ -146,19 +150,20 @@ extension UniqueArray where Element: ~Copyable {
///
/// - Parameters:
/// - items: An array whose items to move to the end of this array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`items.count`) when amortized over many invocations on
/// the same array
@_alwaysEmitIntoClient
@discardableResult
public mutating func append(
moving items: inout RigidArray<Element>
) {
) -> Range<Int> {
// FIXME: Remove in favor of the generic RRC algorithm
_ensureFreeCapacity(items.count)
items.edit { source in
return items.edit { source in
source.withUnsafeMutableBufferPointer { buffer, count in
_storage.append(moving: buffer._extracting(first: count))
count = 0
return _storage.append(moving: buffer._extracting(first: count))
}
}
}
@@ -175,15 +180,16 @@ extension UniqueArray {
/// - Parameters:
/// - newElements: A fully initialized buffer whose contents to copy into
/// the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`newElements.count`) when amortized over many
/// invocations on the same array.
@_alwaysEmitIntoClient
@discardableResult
public mutating func append(
copying newElements: UnsafeBufferPointer<Element>
) {
) -> Range<Int> {
_ensureFreeCapacity(newElements.count)
unsafe _storage._appendUnchecked(copying: newElements)
return unsafe _storage._appendUnchecked(copying: newElements)
}
/// Copies the elements of a buffer to the end of this array.
@@ -195,13 +201,14 @@ extension UniqueArray {
/// - Parameters:
/// - newElements: A fully initialized buffer whose contents to copy into
/// the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`newElements.count`) when amortized over many
/// invocations on the same array.
@_alwaysEmitIntoClient
@discardableResult
public mutating func append(
copying newElements: UnsafeMutableBufferPointer<Element>
) {
) -> Range<Int> {
unsafe self.append(copying: UnsafeBufferPointer(newElements))
}
@@ -213,13 +220,14 @@ extension UniqueArray {
///
/// - Parameters:
/// - newElements: A span whose contents to copy into the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`newElements.count`) when amortized over many
/// invocations on the same array.
@_alwaysEmitIntoClient
public mutating func append(copying newElements: Span<Element>) {
@discardableResult
public mutating func append(copying newElements: Span<Element>) -> Range<Int> {
_ensureFreeCapacity(newElements.count)
newElements.withUnsafeBufferPointer { source in
return newElements.withUnsafeBufferPointer { source in
unsafe _storage._appendUnchecked(copying: source)
}
}
@@ -240,7 +248,7 @@ extension UniqueArray {
if span.isEmpty { break }
_ensureFreeCapacity(span.count)
span.withUnsafeBufferPointer { source in
unsafe _storage._appendUnchecked(copying: source)
_ = unsafe _storage._appendUnchecked(copying: source)
}
}
}
@@ -258,7 +266,6 @@ extension UniqueArray {
///
/// - Parameters:
/// - newElements: A container whose contents to copy into the array.
///
/// - Complexity: O(`newElements.count`), when amortized over many invocations
/// over the same array.
@available(SwiftStdlib 6.4, *)
@@ -285,14 +292,13 @@ extension UniqueArray {
///
/// - Parameters:
/// - newElements: The new elements to copy into the array.
///
/// - Complexity: O(*m*), where *m* is the length of `newElements`, when
/// amortized over many invocations over the same array.
@_alwaysEmitIntoClient
public mutating func append(copying newElements: some Sequence<Element>) {
let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in
_ensureFreeCapacity(buffer.count)
unsafe _storage._appendUnchecked(copying: buffer)
_ = unsafe _storage._appendUnchecked(copying: buffer)
return
}
if done != nil { return }
@@ -313,7 +319,6 @@ extension UniqueArray {
///
/// - Parameters:
/// - newElements: A container whose contents to copy into the array.
///
/// - Complexity: O(`newElements.count`), when amortized over many invocations
/// over the same array.
@available(SwiftStdlib 6.4, *)
@@ -21,11 +21,6 @@ import SpanPreview
#if UnstableContainersPreview
@available(SwiftStdlib 5.0, *)
extension UniqueArray where Element: ~Copyable {
@_lifetime(&self)
public mutating func _consumeAll() -> InputSpan<Element> {
_storage._consumeAll()
}
/// Remove the specified subrange of items from this array,
/// passing an input span to the given function to consume them in place.
///
@@ -35,14 +30,16 @@ extension UniqueArray where Element: ~Copyable {
/// The function is not required to consume all items in the span;
/// however, the span's remaining items will still be removed from
/// the array.
///
/// - Returns: A valid index addressing the position following the consumed
/// range in the resulting array.
/// - Complexity: O(`self.count`)
@_alwaysEmitIntoClient
public mutating func consume(
@discardableResult
public mutating func consumeSubrange(
_ subrange: Range<Int>,
consumingWith consumer: (inout InputSpan<Element>) -> Void
) {
_storage.consume(subrange, consumingWith: consumer)
) -> Index {
_storage.consumeSubrange(subrange, consumingWith: consumer)
}
/// Remove the specified subrange of items from this deque,
@@ -60,15 +57,18 @@ extension UniqueArray where Element: ~Copyable {
/// - Parameter consumer: A function taking an input span of the removed items,
/// allowing them to be consumed straight out of the array's storage.
/// The function is called at most once.
///
/// - Returns: A valid index addressing the position following the consumed
/// range in the resulting array.
/// - Complexity: O(`self.count`)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func consume<R: RangeExpression<Index>>(
@discardableResult
public mutating func consumeSubrange<R: RangeExpression<Index>>(
_ subrange: R,
consumingWith consumer: (inout InputSpan<Element>) -> Void
) {
_storage.consume(subrange.relative(to: indices), consumingWith: consumer)
) -> Index {
_storage.consumeSubrange(
subrange.relative(to: indices), consumingWith: consumer)
}
/// Remove all items currently in this array, passing an input
@@ -81,13 +81,12 @@ extension UniqueArray where Element: ~Copyable {
/// - Parameter consumer: A function taking an input span of the removed items,
/// allowing them to be consumed straight out of the array's storage.
/// The function is called at most once.
///
/// - Complexity: O(`self.count`)
@_alwaysEmitIntoClient
public mutating func consumeAll(
consumingWith consumer: (inout InputSpan<Element>) -> Void
) {
_storage.consume(indices, consumingWith: consumer)
_storage.consumeSubrange(indices, consumingWith: consumer)
}
/// Remove the specified number of items from the end of this array,
@@ -124,7 +123,7 @@ extension UniqueArray where Element: ~Copyable {
@_alwaysEmitIntoClient
@inline(__always)
@_lifetime(&self)
public mutating func consume(_ subrange: Range<Index>) -> SubrangeConsumer {
public mutating func consumeSubrange(_ subrange: Range<Index>) -> SubrangeConsumer {
SubrangeConsumer(_base: &self._storage, offsetRange: subrange)
}
}
@@ -11,6 +11,10 @@
//
//===----------------------------------------------------------------------===//
#if !COLLECTIONS_SINGLE_MODULE
import SpanPreview
#endif
#if compiler(>=6.2)
@available(SwiftStdlib 5.0, *)
@@ -55,6 +59,17 @@ extension UniqueArray where Element: ~Copyable {
self.init(minimumCapacity: capacity)
}
@available(*, deprecated)
@inlinable
@inline(__always)
public mutating func removeAll(keepingCapacity keepCapacity: Bool) {
if keepCapacity {
_storage.removeAll()
} else {
_storage = RigidArray(capacity: 0)
}
}
/// Append a given number of items to the end of this array by populating
/// an output span.
///
@@ -137,198 +152,81 @@ extension UniqueArray where Element: ~Copyable {
_storage.reallocate(capacity: capacity)
}
/// Replaces the specified range of elements by a given count of new items,
/// using a callback to directly initialize array storage by populating
/// an output span.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting room for the new elements starting at the
/// same location. The number of new elements need not match the number
/// of elements being removed.
///
/// If the array does not have sufficient capacity to perform the replacement,
/// then this reallocates storage to extend its capacity, using a geometric
/// growth rate.
///
/// If you pass a zero-length range as the `subrange` parameter, then
/// this method is equivalent to calling
/// `insert(count: newCount, initializingWith: body)`.
///
/// Likewise, if you pass a zero for `newCount`, then this method
/// removes the elements in the given subrange without any replacement.
/// Calling `removeSubrange(subrange)` is preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newCount: the number of items to replace the old subrange.
/// - body: A callback that gets called exactly once to directly
/// populate newly reserved storage within the array. The function
/// is called with an empty output span of capacity `newCount`,
/// and it must fully populate it before returning.
///
/// - Complexity: O(`self.count` + `newCount`)
@available(*, deprecated, renamed: "replace(removing:addingCount:initializingWith:)")
@available(*, deprecated, renamed: "replaceSubrange(_:addingCount:initializingWith:)")
@inlinable
public mutating func replaceSubrange<Result: ~Copyable>(
_ subrange: Range<Int>,
newCount: Int,
initializingWith body: (inout OutputSpan<Element>) -> Result
) -> Result {
var result: Result? = nil
self.replace(removing: subrange, addingCount: newCount) { target in
result = body(&target)
}
return result!
public mutating func replace<E: Error>(
removing subrange: Range<Int>,
addingCount newItemCount: Int,
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) -> Void {
try replaceSubrange(
subrange, addingCount: newItemCount, initializingWith: initializer)
}
/// Replaces the specified range of elements by moving the elements of a
/// fully initialized buffer into their place. On return, the buffer is left
/// in an uninitialized state.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same
/// location. The number of new elements need not match the number of elements
/// being removed.
///
/// If the array does not have sufficient capacity to perform the replacement,
/// then this reallocates the array's storage to extend its capacity, using a
/// geometric growth rate.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.lowerBound`. Calling
/// the `insert(copying:at:)` method instead is preferred in this case.
///
/// Likewise, if you pass a zero-length buffer as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: A fully initialized buffer whose contents to move into
/// the array.
///
/// - Complexity: O(`self.count` + `newElements.count`)
@available(*, deprecated, renamed: "replace(removing:moving:)")
#if UnstableContainersPreview
@available(*, deprecated, renamed: "replaceSubrange(_:consumingWith:addingCount:initializingWith:)")
@inlinable
public mutating func replace<E: Error>(
removing subrange: Range<Int>,
consumingWith consumer: (inout InputSpan<Element>) -> Void,
addingCount newItemCount: Int,
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) -> Void {
try replaceSubrange(
subrange,
consumingWith: consumer,
addingCount: newItemCount,
initializingWith: initializer)
}
#endif
@available(*, deprecated, renamed: "replaceSubrange(_:moving:)")
@_alwaysEmitIntoClient
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
moving newElements: UnsafeMutableBufferPointer<Element>,
) {
self.replace(removing: subrange, moving: newElements)
replaceSubrange(subrange, moving: newElements)
}
/// Replaces the specified range of elements by moving the contents of an
/// output span into their place. On return, the span is left empty.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same
/// location. The number of new elements need not match the number of elements
/// being removed.
///
/// If the array does not have sufficient capacity to perform the replacement,
/// then this reallocates the array's storage to extend its capacity, using a
/// geometric growth rate.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.lowerBound`. Calling
/// the `insert(moving:at:)` method instead is preferred in this case.
///
/// Likewise, if you pass a zero-length buffer as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - items: An output span whose contents are to be moved into the array.
///
/// - Complexity: O(`self.count` + `items.count`)
@available(*, deprecated, renamed: "replace(removing:moving:)")
#if UnstableContainersPreview
@available(*, deprecated, renamed: "replaceSubrange(_:moving:)")
@_alwaysEmitIntoClient
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
moving items: inout InputSpan<Element>
) {
replaceSubrange(subrange, moving: &items)
}
#endif
@available(*, deprecated, renamed: "replaceSubrange(_:moving:)")
@_alwaysEmitIntoClient
public mutating func replace(
removing subrange: Range<Int>,
moving items: inout OutputSpan<Element>
) {
self.replace(removing: subrange, moving: &items)
replaceSubrange(subrange, moving: &items)
}
/// Replaces the specified range of elements by moving the elements of a
/// another array into their place. On return, the source array
/// becomes empty, but it is not destroyed, and it preserves its original
/// storage capacity.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same
/// location. The number of new elements need not match the number of elements
/// being removed.
///
/// If the array does not have sufficient capacity to hold enough elements,
/// then this reallocates the array's storage to extend its capacity, using a
/// geometric growth rate.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.lowerBound`. Calling
/// the `insert(copying:at:)` method instead is preferred in this case.
///
/// Likewise, if you pass a zero-length buffer as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: An array whose contents to move into `self`.
///
/// - Complexity: O(`self.count` + `newElements.count`)
@available(*, deprecated, renamed: "replace(removing:moving:)")
@available(*, deprecated, renamed: "replaceSubrange(_:moving:)")
@_alwaysEmitIntoClient
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
moving newElements: inout RigidArray<Element>,
) {
self.replace(removing: subrange, moving: &newElements)
replaceSubrange(subrange, moving: &newElements)
}
/// Replaces the specified range of elements by moving the elements of a
/// given array into their place, consuming it in the process.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same
/// location. The number of new elements need not match the number of elements
/// being removed.
///
/// If the array does not have sufficient capacity to perform the replacement,
/// then this reallocates the array's storage to extend its capacity, using a
/// geometric growth rate.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.lowerBound`. Calling
/// the `insert(copying:at:)` method instead is preferred in this case.
///
/// Likewise, if you pass a zero-length buffer as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: An array whose contents to move into `self`.
///
/// - Complexity: O(`self.count` + `newElements.count`)
@available(*, deprecated, renamed: "replace(removing:consuming:)")
@available(*, deprecated, renamed: "replaceSubrange(_:consuming:)")
@_alwaysEmitIntoClient
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
consuming newElements: consuming RigidArray<Element>,
) {
self.replace(removing: subrange, consuming: newElements)
replaceSubrange(subrange, consuming: newElements)
}
}
@available(SwiftStdlib 5.0, *)
@@ -356,155 +254,40 @@ extension UniqueArray {
clone(capacity: capacity)
}
/// Replaces the specified subrange of elements by copying the elements of
/// the given buffer pointer, which must be fully initialized.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// If the capacity of the array isn't sufficient to perform the replacement,
/// then this reallocates the array's storage to extend its capacity, using a
/// geometric growth rate.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.lowerBound`. Calling
/// the `insert(copying:at:)` method instead is preferred in this case.
///
/// Likewise, if you pass a zero-length buffer as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: The new elements to copy into the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@available(*, deprecated, renamed: "replace(removing:copying:)")
@available(*, deprecated, renamed: "replace(_:copying:)")
@inlinable
@inline(__always)
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
copying newElements: UnsafeBufferPointer<Element>
) {
self.replace(removing: subrange, copying: newElements)
replaceSubrange(subrange, copying: newElements)
}
/// Replaces the specified subrange of elements by copying the elements of
/// the given buffer pointer, which must be fully initialized.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// If the capacity of the array isn't sufficient to perform the replacement,
/// then this reallocates the array's storage to extend its capacity, using a
/// geometric growth rate.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.lowerBound`. Calling
/// the `insert(copying:at:)` method instead is preferred in this case.
///
/// Likewise, if you pass a zero-length buffer as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: The new elements to copy into the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@available(*, deprecated, renamed: "replace(removing:copying:)")
@available(*, deprecated, renamed: "replace(_:copying:)")
@inlinable
@inline(__always)
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
copying newElements: UnsafeMutableBufferPointer<Element>
) {
self.replace(removing: subrange, copying: newElements)
self.replaceSubrange(subrange, copying: newElements)
}
/// Replaces the specified subrange of elements by copying the elements of
/// the given span.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// If the capacity of the array isn't sufficient to perform the replacement,
/// then this reallocates the array's storage to extend its capacity, using a
/// geometric growth rate.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.lowerBound`. Calling
/// the `insert(copying:at:)` method instead is preferred in this case.
///
/// Likewise, if you pass a zero-length span as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: The new elements to copy into the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@available(*, deprecated, renamed: "replace(removing:copying:)")
@available(*, deprecated, renamed: "replace(_:copying:)")
@inlinable
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
copying newElements: Span<Element>
) {
self.replace(removing: subrange, copying: newElements)
replaceSubrange(subrange, copying: newElements)
}
/// Replaces the specified subrange of elements by copying the elements of
/// the given collection.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same location.
/// The number of new elements need not match the number of elements being
/// removed.
///
/// If the capacity of the array isn't sufficient to perform the replacement,
/// then this reallocates the array's storage to extend its capacity, using a
/// geometric growth rate.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the elements of `newElements` at `subrange.lowerBound`. Calling
/// the `insert(copying:at:)` method instead is preferred in this case.
///
/// Likewise, if you pass a zero-length collection as the `newElements`
/// parameter, this method removes the elements in the given subrange
/// without replacement. Calling the `removeSubrange(_:)` method instead is
/// preferred in this case.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: The new elements to copy into the collection.
///
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@available(*, deprecated, renamed: "replace(removing:copying:)")
@available(*, deprecated, renamed: "replace(_:copying:)")
@inlinable
@inline(__always)
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
copying newElements: __owned some Collection<Element>
) {
self.replace(removing: subrange, copying: newElements)
replaceSubrange(subrange, copying: newElements)
}
}
@@ -36,14 +36,15 @@ extension UniqueArray where Element: ~Copyable {
/// - Parameter item: The new element to insert into the array.
/// - Parameter index: The position at which to insert the new element.
/// `index` must be a valid index in the array.
///
/// - Returns: A valid index to the newly inserted item.
/// - Complexity: O(`self.count`)
@inlinable
public mutating func insert(_ item: consuming Element, at index: Int) {
@discardableResult
public mutating func insert(_ item: consuming Element, at index: Int) -> Int {
precondition(index >= 0 && index <= count)
// FIXME: Avoid moving the subsequent elements twice.
_ensureFreeCapacity(1)
_storage.insert(item, at: index)
return _storage.insert(item, at: index)
}
}
@@ -79,17 +80,18 @@ extension UniqueArray where Element: ~Copyable {
/// populate newly reserved storage within the array. The function
/// is called with an empty output span of capacity matching the
/// supplied count, and it must fully populate it before returning.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `count`)
@_alwaysEmitIntoClient
@inline(__always)
@discardableResult
public mutating func insert<E: Error>(
addingCount newItemCount: Int,
at index: Int,
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) {
) throws(E) -> Range<Int> {
_ensureFreeCapacity(newItemCount)
try _storage.insert(
return try _storage.insert(
addingCount: newItemCount,
at: index,
initializingWith: initializer)
@@ -109,16 +111,17 @@ extension UniqueArray where Element: ~Copyable {
/// - Parameters:
/// - items: A fully initialized buffer whose contents to move into
/// the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `items.count`)
@_alwaysEmitIntoClient
@discardableResult
public mutating func insert(
moving items: UnsafeMutableBufferPointer<Element>,
at index: Int
) {
) -> Range<Int> {
// FIXME: Avoid moving the subsequent elements twice.
_ensureFreeCapacity(items.count)
_storage.insert(moving: items, at: index)
return _storage.insert(moving: items, at: index)
}
#if UnstableContainersPreview
@@ -137,16 +140,17 @@ extension UniqueArray where Element: ~Copyable {
/// the array.
/// - index: The position at which to insert the new items.
/// `index` must be a valid index in the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `items.count`)
@_alwaysEmitIntoClient
@discardableResult
public mutating func insert(
moving items: inout InputSpan<Element>,
at index: Int
) {
) -> Range<Int> {
// FIXME: Remove when InputSpan starts conforming to RangeReplaceableContainer
_ensureFreeCapacity(items.count)
_storage.insert(moving: &items, at: index)
return _storage.insert(moving: &items, at: index)
}
#endif
@@ -165,16 +169,17 @@ extension UniqueArray where Element: ~Copyable {
/// the array.
/// - index: The position at which to insert the new items.
/// `index` must be a valid index in the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `items.count`)
@_alwaysEmitIntoClient
@discardableResult
public mutating func insert(
moving items: inout OutputSpan<Element>,
at index: Int
) {
) -> Range<Int> {
// FIXME: Remove when OutputSpan starts conforming to RangeReplaceableContainer
_ensureFreeCapacity(items.count)
_storage.insert(moving: &items, at: index)
return _storage.insert(moving: &items, at: index)
}
/// Inserts the elements of a given array into the given position in this
@@ -189,16 +194,17 @@ extension UniqueArray where Element: ~Copyable {
/// - Parameters:
/// - items: An array whose contents to move into `self`.
/// - index: The position in `self` at which to insert the new items.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `items.count`)
@_alwaysEmitIntoClient
@discardableResult
public mutating func insert(
moving items: inout RigidArray<Element>,
at index: Int
) {
) -> Range<Int> {
// FIXME: Avoid moving the subsequent elements twice.
_ensureFreeCapacity(items.count)
_storage.insert(moving: &items, at: index)
return _storage.insert(moving: &items, at: index)
}
}
@@ -223,15 +229,16 @@ extension UniqueArray {
/// must be fully initialized.
/// - index: The position at which to insert the new elements. It must be
/// a valid index of the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `newElements.count`)
@inlinable
@discardableResult
public mutating func insert(
copying newElements: UnsafeBufferPointer<Element>, at index: Int
) {
) -> Range<Int> {
// FIXME: Avoid moving the subsequent elements twice.
_ensureFreeCapacity(newElements.count)
unsafe _storage.insert(copying: newElements, at: index)
return unsafe _storage.insert(copying: newElements, at: index)
}
/// Copies the elements of a fully initialized buffer pointer into this
@@ -253,13 +260,14 @@ extension UniqueArray {
/// must be fully initialized.
/// - index: The position at which to insert the new elements. It must be
/// a valid index of the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `newElements.count`)
@inlinable
@discardableResult
public mutating func insert(
copying newElements: UnsafeMutableBufferPointer<Element>,
at index: Int
) {
) -> Range<Int> {
unsafe self.insert(copying: UnsafeBufferPointer(newElements), at: index)
}
@@ -280,15 +288,16 @@ extension UniqueArray {
/// - newElements: The new elements to insert into the array.
/// - index: The position at which to insert the new elements. It must be
/// a valid index of the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `newElements.count`)
@inlinable
@discardableResult
public mutating func insert(
copying newElements: Span<Element>, at index: Int
) {
) -> Range<Int> {
// FIXME: Avoid moving the subsequent elements twice.
_ensureFreeCapacity(newElements.count)
_storage.insert(copying: newElements, at: index)
return _storage.insert(copying: newElements, at: index)
}
/// Copies the elements of a collection into this array at the specified
@@ -309,19 +318,20 @@ extension UniqueArray {
/// - newElements: The new elements to insert into the array.
/// - index: The position at which to insert the new elements. It must be
/// a valid index of the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `newElements.count`)
@inlinable
@discardableResult
public mutating func insert(
copying newElements: some Collection<Element>, at index: Int
) {
) -> Range<Int> {
// FIXME: Remove this -- RangeReplaceContainer already has this algorithm.
// (Note that this would be source breaking while RRC lives in the separate
// ContainersPreview module.)
// FIXME: Avoid moving the subsequent elements twice.
let newCount = newElements.count
_ensureFreeCapacity(newCount)
_storage._insertCollection(
return _storage._insertCollection(
addingCount: newCount, copying: newElements, at: index)
}
}
@@ -19,20 +19,52 @@ import InternalCollectionsUtilities
@available(SwiftStdlib 5.0, *)
extension UniqueArray where Element: ~Copyable {
/// Removes all elements from the array, optionally preserving its
/// Removes all elements from the array, preserving its
/// allocated capacity.
///
/// - Complexity: O(*n*), where *n* is the original count of the array.
@inlinable
@inline(__always)
public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) {
if keepCapacity {
_storage.removeAll()
} else {
_storage = RigidArray(capacity: 0)
}
public mutating func removeAll() {
_storage.removeAll()
}
/// Removes and returns the element at the specified position.
///
/// All the elements following the specified position are moved to close the
/// gap.
///
/// - Parameter index: The position of the element to remove. `index` must be
/// a valid index of the array that is not equal to the end index.
/// On return, `index` is updated to address the position following the
/// removed element.
/// - Returns: The removed element.
///
/// - Complexity: O(`self.count`)
@inlinable
@inline(__always)
@discardableResult
public mutating func remove(at index: inout Int) -> Element {
_storage.remove(at: &index)
}
/// Removes and returns the element at the specified position.
///
/// All the elements following the specified position are moved to close the
/// gap.
///
/// - Parameter index: The position of the element to remove. `index` must be
/// a valid index of the array that is not equal to the end index.
/// - Returns: The removed element.
///
/// - Complexity: O(`count`)
@inlinable
@discardableResult
public mutating func remove(at index: Int) -> Element {
_storage.remove(at: index)
}
/// Removes and returns the last element of the array.
///
/// The array must not be empty.
@@ -63,23 +95,6 @@ extension UniqueArray where Element: ~Copyable {
_storage.removeLast(k)
}
/// Removes and returns the element at the specified position.
///
/// All the elements following the specified position are moved to close the
/// gap.
///
/// - Parameter index: The position of the element to remove. `index` must be
/// a valid index of the array that is not equal to the end index.
/// - Returns: The removed element.
///
/// - Complexity: O(`self.count`)
@inlinable
@inline(__always)
@discardableResult
public mutating func remove(at index: Int) -> Element {
_storage.remove(at: index)
}
/// Removes the specified subrange of elements from the array.
///
/// All the elements following the specified subrange are moved to close the
@@ -90,7 +105,8 @@ extension UniqueArray where Element: ~Copyable {
///
/// - Complexity: O(`self.count`)
@inlinable
public mutating func removeSubrange(_ bounds: Range<Int>) {
@discardableResult
public mutating func removeSubrange(_ bounds: Range<Int>) -> Int {
_storage.removeSubrange(bounds)
}
@@ -101,8 +117,11 @@ extension UniqueArray where Element: ~Copyable {
///
/// - Complexity: O(`self.count`)
@_alwaysEmitIntoClient
public mutating func removeSubrange(_ bounds: some RangeExpression<Int>) {
// FIXME: Remove this in favor of the RangeReplaceableContainer algorithm.
@discardableResult
public mutating func removeSubrange(
_ bounds: some RangeExpression<Int>
) -> Int {
// FIXME: Remove this in favor of the DrainableContainer algorithm.
removeSubrange(bounds.relative(to: indices))
}
}
@@ -117,7 +136,7 @@ extension UniqueArray where Element: ~Copyable {
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public mutating func popLast() -> Element? {
// FIXME: Remove this in favor of the RangeReplaceableContainer algorithm.
// FIXME: Remove this in favor of the DrainableContainer algorithm.
if isEmpty { return nil }
return removeLast()
}
@@ -58,21 +58,22 @@ extension UniqueArray where Element: ~Copyable {
/// - initializer: A callback that gets called at most once to directly
/// populate newly reserved storage within the array. The function
/// is always called with an empty output span.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity
/// of the callback invocations.
@inlinable
public mutating func replace<E: Error>(
removing subrange: Range<Int>,
@_alwaysEmitIntoClient
@discardableResult
public mutating func replaceSubrange<E: Error>(
_ subrange: Range<Int>,
addingCount newItemCount: Int,
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) -> Void {
) throws(E) -> Range<Int> {
_storage._checkValidBounds(subrange)
precondition(newItemCount >= 0, "Cannot add a negative number of items")
// FIXME: Avoid moving the subsequent elements twice on resize.
_ensureFreeCapacity(newItemCount - subrange.count)
try _storage._uncheckedReplace(
removing: subrange,
return try _storage._uncheckedReplaceSubrange(
subrange,
addingCount: newItemCount,
initializingWith: initializer)
}
@@ -126,21 +127,22 @@ extension UniqueArray where Element: ~Copyable {
/// - initializer: A callback that gets called at most once to directly
/// populate newly reserved storage within the deque. The function
/// is always called with an empty output span.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `newItemCount`) in addition to the
/// complexity of the callback invocations.
@inlinable
public mutating func replace<E: Error>(
removing subrange: Range<Int>,
@_alwaysEmitIntoClient
@discardableResult
public mutating func replaceSubrange<E: Error>(
_ subrange: Range<Int>,
consumingWith consumer: (inout InputSpan<Element>) -> Void,
addingCount newItemCount: Int,
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) -> Void {
) throws(E) -> Range<Int> {
_storage._checkValidBounds(subrange)
precondition(newItemCount >= 0, "Cannot add a negative number of items")
_ensureFreeCapacity(newItemCount - subrange.count)
try _storage._uncheckedReplace(
removing: subrange,
return try _storage._uncheckedReplaceSubrange(
subrange,
consumingWith: consumer,
addingCount: newItemCount,
initializingWith: initializer)
@@ -177,16 +179,17 @@ extension UniqueArray where Element: ~Copyable {
/// the range must be valid indices in the array.
/// - newElements: A fully initialized buffer whose contents to move into
/// the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `newElements.count`)
@_alwaysEmitIntoClient
public mutating func replace(
removing subrange: Range<Int>,
@discardableResult
public mutating func replaceSubrange(
_ subrange: Range<Int>,
moving newElements: UnsafeMutableBufferPointer<Element>,
) {
) -> Range<Int> {
// FIXME: Avoid moving the subsequent elements twice.
_ensureFreeCapacity(newElements.count - subrange.count)
_storage.replace(removing: subrange, moving: newElements)
return _storage.replaceSubrange(subrange, moving: newElements)
}
#if UnstableContainersPreview
@@ -215,16 +218,17 @@ extension UniqueArray where Element: ~Copyable {
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - items: An input span whose contents are to be moved into the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `items.count`)
@_alwaysEmitIntoClient
public mutating func replace(
removing subrange: Range<Int>,
@discardableResult
public mutating func replaceSubrange(
_ subrange: Range<Int>,
moving items: inout InputSpan<Element>
) {
) -> Range<Int> {
// FIXME: Avoid moving the subsequent elements twice.
_ensureFreeCapacity(items.count - subrange.count)
_storage.replace(removing: subrange, moving: &items)
return _storage.replaceSubrange(subrange, moving: &items)
}
#endif
@@ -253,16 +257,17 @@ extension UniqueArray where Element: ~Copyable {
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - items: An output span whose contents are to be moved into the array.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `items.count`)
@_alwaysEmitIntoClient
public mutating func replace(
removing subrange: Range<Int>,
@discardableResult
public mutating func replaceSubrange(
_ subrange: Range<Int>,
moving items: inout OutputSpan<Element>
) {
) -> Range<Int> {
// FIXME: Avoid moving the subsequent elements twice.
_ensureFreeCapacity(items.count - subrange.count)
_storage.replace(removing: subrange, moving: &items)
return _storage.replaceSubrange(subrange, moving: &items)
}
/// Replaces the specified range of elements by moving the elements of a
@@ -292,16 +297,17 @@ extension UniqueArray where Element: ~Copyable {
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: An array whose contents to move into `self`.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `newElements.count`)
@_alwaysEmitIntoClient
public mutating func replace(
removing subrange: Range<Int>,
@discardableResult
public mutating func replaceSubrange(
_ subrange: Range<Int>,
moving newElements: inout RigidArray<Element>,
) {
) -> Range<Int> {
// FIXME: Avoid moving the subsequent elements twice.
_ensureFreeCapacity(newElements.count - subrange.count)
_storage.replace(removing: subrange, moving: &newElements)
return _storage.replaceSubrange(subrange, moving: &newElements)
}
}
@@ -332,14 +338,15 @@ extension UniqueArray where Element: ~Copyable {
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: An array whose contents to move into `self`.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(`self.count` + `newElements.count`)
@_alwaysEmitIntoClient
public mutating func replace(
removing subrange: Range<Int>,
@discardableResult
public mutating func replaceSubrange(
_ subrange: Range<Int>,
consuming newElements: consuming RigidArray<Element>,
) {
replace(removing: subrange, moving: &newElements)
) -> Range<Int> {
replaceSubrange(subrange, moving: &newElements)
}
}
@@ -370,18 +377,19 @@ extension UniqueArray {
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: The new elements to copy into the collection.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@inlinable
@_alwaysEmitIntoClient
@inline(__always)
public mutating func replace(
removing subrange: Range<Int>,
@discardableResult
public mutating func replaceSubrange(
_ subrange: Range<Int>,
copying newElements: UnsafeBufferPointer<Element>
) {
) -> Range<Int> {
// FIXME: Avoid moving the subsequent elements twice.
_ensureFreeCapacity(newElements.count - subrange.count)
unsafe _storage.replace(removing: subrange, copying: newElements)
return unsafe _storage.replaceSubrange(subrange, copying: newElements)
}
/// Replaces the specified subrange of elements by copying the elements of
@@ -409,18 +417,17 @@ extension UniqueArray {
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: The new elements to copy into the collection.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@inlinable
@_alwaysEmitIntoClient
@inline(__always)
public mutating func replace(
removing subrange: Range<Int>,
public mutating func replaceSubrange(
_ subrange: Range<Int>,
copying newElements: UnsafeMutableBufferPointer<Element>
) {
unsafe self.replace(
removing: subrange,
copying: UnsafeBufferPointer(newElements))
unsafe self.replaceSubrange(
subrange, copying: UnsafeBufferPointer(newElements))
}
/// Replaces the specified subrange of elements by copying the elements of
@@ -448,17 +455,18 @@ extension UniqueArray {
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: The new elements to copy into the collection.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@inlinable
public mutating func replace(
removing subrange: Range<Int>,
@_alwaysEmitIntoClient
@discardableResult
public mutating func replaceSubrange(
_ subrange: Range<Int>,
copying newElements: Span<Element>
) {
) -> Range<Int> {
// FIXME: Avoid moving the subsequent elements twice.
_ensureFreeCapacity(newElements.count - subrange.count)
_storage.replace(removing: subrange, copying: newElements)
return _storage.replaceSubrange(subrange, copying: newElements)
}
/// Replaces the specified subrange of elements by copying the elements of
@@ -486,20 +494,21 @@ extension UniqueArray {
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newElements: The new elements to copy into the collection.
///
/// - Returns: A valid index range addressing the newly inserted items.
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
@inlinable
@_alwaysEmitIntoClient
@inline(__always)
public mutating func replace(
removing subrange: Range<Int>,
@discardableResult
public mutating func replaceSubrange(
_ subrange: Range<Int>,
copying newElements: __owned some Collection<Element>
) {
) -> Range<Int> {
// FIXME: Avoid moving the subsequent elements twice.
let c = newElements.count
_ensureFreeCapacity(c - subrange.count)
_storage._replace(
removing: subrange,
return _storage._replaceSubrange(
subrange,
copyingCollection: newElements,
newCount: c)
}