Files
swift-collections/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift
T
Karoy Lorentey 5cebba6f29 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(_:)`.
2026-09-14 20:37:12 -07:00

201 lines
6.4 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
//
//===----------------------------------------------------------------------===//
#if !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
#if compiler(>=6.2)
@available(SwiftStdlib 5.0, *)
extension RigidArray where Element: ~Copyable {
/// Initializes a new rigid array with zero capacity and no elements.
///
/// - Complexity: O(1)
@inlinable
public init() {
unsafe _ptr = ._dangling()
_capacity = 0
_count = 0
}
/// Initializes a new rigid array with the specified capacity and no elements.
@inlinable
public init(capacity: Int) {
precondition(capacity >= 0, "Array capacity must be nonnegative")
if capacity > 0 {
unsafe _ptr = .allocate(capacity: capacity)
_capacity = capacity
} else {
unsafe _ptr = ._dangling()
_capacity = 0
}
_count = 0
}
}
@available(SwiftStdlib 5.0, *)
extension RigidArray where Element: ~Copyable {
/// Creates a new array with the specified capacity, directly initializing
/// its storage using an output span.
///
/// - Parameters:
/// - capacity: The storage capacity of the new array.
/// - initializer: A callback that gets called at most once to directly
/// populate newly reserved storage within the array. The function
/// is allowed to add fewer than `capacity` items. The array is
/// initialized with however many items the callback adds to the
/// output span before it returns (or before it throws an error).
@inlinable
public init<E: Error>(
capacity: Int,
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) {
self.init(capacity: capacity)
try edit(initializer)
}
}
@available(SwiftStdlib 5.0, *)
extension RigidArray /*where Element: Copyable*/ {
/// Creates a new array containing the specified number of a single,
/// repeated value.
///
/// - Parameters:
/// - repeatedValue: The element to repeat.
/// - count: The number of times to repeat the value passed in the
/// `repeating` parameter. `count` must be zero or greater.
///
/// - Complexity: O(`count`)
public init(repeating repeatedValue: Element, count: Int) {
self.init(capacity: count)
unsafe _freeSpace.initialize(repeating: repeatedValue)
_count = count
}
}
@available(SwiftStdlib 5.0, *)
extension RigidArray where Element: ~Copyable {
/// Creates a new rigid array taking over the storage of the specified
/// unique array instance, consuming it in the process.
///
/// - Complexity: O(1)
@inlinable
public init(consuming array: consuming UniqueArray<Element>) {
self = array._storage
}
}
@available(SwiftStdlib 5.0, *)
extension RigidArray /*where Element: Copyable*/ {
/// Creates a new array with the specified capacity, holding a copy
/// of the contents of a given sequence.
///
/// - Parameters:
/// - capacity: The storage capacity of the new array.
/// - contents: The sequence whose contents to copy into the new array.
/// The sequence must not contain more than `capacity` elements.
@_alwaysEmitIntoClient
@inline(__always)
public init(
capacity: Int,
copying contents: some Sequence<Element>
) {
self.init(capacity: capacity)
self.append(copying: contents)
}
#if compiler(>=6.4)
/// Creates a new array with the specified capacity, holding a copy
/// of the contents of a given container.
///
/// - Parameters:
/// - capacity: The storage capacity of the new array, or nil to allocate
/// just enough capacity to store the contents.
/// - contents: The container whose contents to copy into the new array.
/// The container must not contain more than `capacity` elements.
@available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public init<Source: Iterable & ~Copyable & ~Escapable>(
capacity: Int,
copying contents: borrowing Source
) throws(Source.Failure)
where Source.Element == Element {
self.init(capacity: capacity)
try self.append(copying: contents)
}
#endif
#if compiler(>=6.4)
/// Creates a new array with the specified capacity, holding a copy
/// of the contents of a given container.
///
/// - Parameters:
/// - capacity: The storage capacity of the new array, or nil to allocate
/// just enough capacity to store the contents.
/// - contents: The container whose contents to copy into the new array.
/// The container must not contain more than `capacity` elements.
@available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public init<Source: Iterable & Sequence<Element>>(
capacity: Int,
copying contents: Source
) throws(Source.Failure)
where Source.Element == Element {
self.init(capacity: capacity)
try self.append(copying: contents)
}
#endif
/// Creates a new array with the specified capacity, holding a copy
/// of the contents of a given collection.
///
/// - Parameters:
/// - capacity: The storage capacity of the new array, or nil to allocate
/// just enough capacity to store the contents.
/// - contents: The collection whose contents to copy into the new array.
/// The collection must not contain more than `capacity` elements.
@_alwaysEmitIntoClient
@inline(__always)
public init(
capacity: Int? = nil,
copying contents: some Collection<Element>
) {
self.init(capacity: capacity ?? contents.count)
self.append(copying: contents)
}
/// Creates a new array with the specified capacity, holding a copy
/// of the contents of the given span.
///
/// - Parameters:
/// - capacity: The storage capacity of the new array, or nil to allocate
/// just enough capacity to store the contents of the span.
/// - span: The span whose contents to copy into the new array.
/// The span must not contain more than `capacity` elements.
@_alwaysEmitIntoClient
@inline(__always)
public init(
capacity: Int? = nil,
copying span: Span<Element>
) {
self.init(capacity: capacity ?? span.count)
self.append(copying: span)
}
}
#endif