Merge pull request #581 from lorentey/small-fixups

[Prerelease] Check API for consistency, fill holes, patch incoherencies
This commit is contained in:
Karoy Lorentey authored and GitHub committed 2026-03-02 13:53:03 -08:00
commit aa337b4caf
27 files changed
+934 -179

No files matched your search

+1
View File
@@ -72,6 +72,7 @@ set(availability_defs
"SwiftStdlib 6.0: macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0"
"SwiftStdlib 6.1: macOS 15.4, iOS 18.4, watchOS 11.4, tvOS 18.4, visionOS 2.4"
"SwiftStdlib 6.2: macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0"
"SwiftStdlib 6.3: macOS 26.4, iOS 26.4, watchOS 26.4, tvOS 26.4, visionOS 26.4"
)
foreach(def ${availability_defs})
add_compile_options("$<$<COMPILE_LANGUAGE:Swift>:SHELL:-enable-experimental-feature \"AvailabilityMacro=${def}\">")
+1
View File
@@ -107,6 +107,7 @@ let availabilityMacros: KeyValuePairs<String, String> = [
"SwiftStdlib 6.0": "macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0",
"SwiftStdlib 6.1": "macOS 15.4, iOS 18.4, watchOS 11.4, tvOS 18.4, visionOS 2.4",
"SwiftStdlib 6.2": "macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0",
"SwiftStdlib 6.3": "macOS 26.4, iOS 26.4, watchOS 26.4, tvOS 26.4, visionOS 26.4",
// Note: if you touch these, please make sure to also update the similar lists in
// CMakeLists.txt and Xcode/Shared.xcconfig.
]
+1
View File
@@ -65,6 +65,7 @@ let availabilityMacros: KeyValuePairs<String, String> = [
"SwiftStdlib 6.0": "macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0",
"SwiftStdlib 6.1": "macOS 15.4, iOS 18.4, watchOS 11.4, tvOS 18.4, visionOS 2.4",
"SwiftStdlib 6.2": "macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0",
"SwiftStdlib 6.3": "macOS 26.4, iOS 26.4, watchOS 26.4, tvOS 26.4, visionOS 26.4",
// Note: if you touch these, please make sure to also update the similar lists in
// CMakeLists.txt and Xcode/Shared.xcconfig.
]
@@ -203,6 +203,75 @@ extension RigidArray where Element: ~Copyable {
#endif
}
@available(SwiftStdlib 5.0, *)
extension RigidArray where Element: ~Copyable {
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Appends at most `newItemCount` items generated by a producer to the end of
/// this array.
///
/// If the array doesn't have sufficient capacity to accommodate the specified
/// number of new elements, then this method reallocates the array's storage
/// to grow it, using a geometric growth rate.
///
/// This operation appends as many items as the producer can generate before
/// either reaching its end (or throwing an error), or filling the specified
/// capacity. This operation only consumes the first `newItemCount` items in the
/// producer; if the producer has more, then they remain available after this
/// method returns.
///
/// - Parameters:
/// - newItemCount: The maximum number of items to append to the array.
/// - producer: A producer that generates the items to append.
///
/// - Complexity: O(*n*) where *n* is the number of new items, when
/// amortized over many similar invocations on the same array.
@_alwaysEmitIntoClient
public mutating func append<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
addingCount newItemCount: Int,
from producer: inout P
) throws(E) {
try self.append(addingCount: newItemCount) { target throws(E) in
while !target.isFull {
guard try producer.generate(into: &target) else { break }
}
}
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Appends all the items generated by a producer to the end of this deque.
///
/// If the deque doesn't have sufficient capacity to accommodate all the
/// elements, then this method reallocates the deque's storage
/// to grow it, using a geometric growth rate.
///
/// - Parameters:
/// - producer: A producer that generates the items to append.
///
/// - Complexity: O(*n*) where *n* is the number of new items, when
/// amortized over many similarly-sized invocations on the same deque.
@_alwaysEmitIntoClient
public mutating func append<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
from producer: inout P
) throws(E) {
var done = false
while !done {
try self.append(addingCount: freeCapacity) { target throws(E) in
while !target.isFull, !done {
done = try !producer.generate(into: &target)
}
}
}
}
#endif
}
@available(SwiftStdlib 5.0, *)
extension RigidArray {
/// Copies the elements of a buffer to the end of this array.
@@ -19,6 +19,16 @@ import ContainersPreview
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@available(SwiftStdlib 5.0, *)
extension RigidArray where Element: ~Copyable {
@_lifetime(&self)
public mutating func _consumeAll() -> InputSpan<Element> {
let buffer = _items
self._count = 0
let result = InputSpan(
buffer: buffer,
initializedCount: buffer.count)
return _overrideLifetime(result, mutating: &self)
}
/// Remove the specified subrange of items from this array,
/// passing an input span to the given function to consume them in place.
///
@@ -125,4 +135,107 @@ extension RigidArray where Element: ~Copyable {
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@available(SwiftStdlib 5.0, *)
extension RigidArray where Element: ~Copyable {
@_alwaysEmitIntoClient
@inline(__always)
@_lifetime(&self)
public mutating func consume(_ subrange: Range<Index>) -> SubrangeConsumer {
SubrangeConsumer(_base: &self, offsetRange: subrange)
}
@_alwaysEmitIntoClient
@inline(__always)
@_lifetime(&self)
public mutating func consume<R: RangeExpression<Index>>(
_ subrange: R
) -> SubrangeConsumer {
consume(subrange.relative(to: indices))
}
@_alwaysEmitIntoClient
@inline(__always)
@_lifetime(&self)
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, *)
extension RigidArray where Element: ~Copyable {
@frozen
public struct SubrangeConsumer: ~Copyable, ~Escapable {
@usableFromInline
internal var _base: Inout<RigidArray>
@usableFromInline
internal var _offsetRange: Range<Int>
@usableFromInline
internal var _remainder: UnsafeMutableBufferPointer<Element>
@_alwaysEmitIntoClient
@inline(__always)
@_lifetime(&_base)
internal init(_base: inout RigidArray, offsetRange: Range<Int>) {
self._remainder = _base._storage._extracting(unchecked: offsetRange)
self._base = Inout(&_base)
self._offsetRange = offsetRange
}
@inlinable
deinit {
self._remainder.deinitialize()
// FIXME: This needs to be written as
// self._base.value.closeGap(offsets: self._offsetRange)
// but unfortunately we cannot mutate self in deinit yet.
// Inout's dereferencing operation is necessarily declared mutating
// to avoid exclusivity violations.
self._base._pointer.pointee
._closeGap(at: _offsetRange.lowerBound, count: _offsetRange.count)
}
}
}
@available(SwiftStdlib 5.0, *)
extension RigidArray.SubrangeConsumer: Drain {
@inlinable
@_lifetime(&self)
@_lifetime(self: copy self)
public mutating func drainNext(maximumCount: Int) -> InputSpan<Element> {
if _remainder.isEmpty {
return .init()
}
let buffer = _remainder._trim(first: maximumCount)
return _overrideLifetime(
InputSpan(buffer: buffer, initializedCount: buffer.count),
mutating: &self)
}
}
#endif
#endif
@@ -264,6 +264,54 @@ extension RigidArray where Element: ~Copyable {
#endif
}
@available(SwiftStdlib 5.0, *)
extension RigidArray where Element: ~Copyable {
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Inserts at most `newItemCount` items generated by a producer into this
/// array, starting at the given index.
///
/// Existing elements in the array's storage are moved as needed to make room
/// for the new items.
///
/// If the target array does not have sufficient capacity to hold the
/// specified number of new items, then this triggers a runtime error.
///
/// This operation inserts as many items as the producer can generate before
/// either reaching `newItemCount`, or the producer hitting its end, or
/// throwing an error. If the producer has more than `newItemCount` items
/// left in its underlying sequence, then extra items remain available after
/// this method returns.
///
/// If the operation inserts fewer than `newItemCount` items, then it results
/// in a gap in ring buffer storage that needs to be closed by moving some
/// items to their correct positions given the adjusted count. This adds some
/// overhead compared to adding exactly as many items as promised.
///
/// - 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.
/// - producer: A producer that generates the items to append.
///
/// - Complexity: O(`self.count` + `newItemCount`)
@_alwaysEmitIntoClient
public mutating func insert<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
addingCount newItemCount: Int,
from producer: inout P,
at index: Int
) throws(E) {
try insert(addingCount: newItemCount, at: index) { target throws(E) in
while !target.isFull, try producer.generate(into: &target) {
// Do nothing
}
}
}
#endif
}
@available(SwiftStdlib 5.0, *)
extension RigidArray {
/// Copies the elements of a fully initialized buffer pointer into this
@@ -404,6 +404,67 @@ extension RigidArray where Element: ~Copyable {
#endif
}
@available(SwiftStdlib 5.0, *)
extension RigidArray where Element: ~Copyable {
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Replaces the specified range of elements by at most `newItemCount` items
/// generated by a producer.
///
/// This method has the effect of removing the specified range of elements
/// from the array and inserting the new elements starting at the same
/// location. The number of new elements need not match the number of elements
/// being removed.
///
/// If the capacity of the array isn't sufficient to accommodate the new
/// elements, then this method triggers a runtime error.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the items generated by `producer` at `subrange.lowerBound`. This
/// case is more directly expressed by calling `insert(moving:at:)`.
///
/// Likewise, if the given producer is empty, then this method removes the
/// elements in the given subrange without replacement. This case is more
/// directly expressed by calling `removeSubrange`.
///
/// This operation inserts as many items as the producer can generate before
/// either reaching `newItemCount`, or the producer hitting its end, or
/// throwing an error. If the producer has more than `newItemCount` items left in
/// its underlying sequence, then extra items remain available after this
/// method returns.
///
/// If the operation inserts fewer than `newItemCount` items, then it results in
/// a gap in array storage that needs to be closed by moving some
/// items to their correct positions given the adjusted count. This adds some
/// overhead compared to adding exactly as many items as promised.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newItemCount: The maximum number of items to insert into the array.
/// - producer: A producer that generates the items to append.
///
/// - Complexity: O(`self.count` + `maximumCount`)
@_alwaysEmitIntoClient
public mutating func replace<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
removing subrange: Range<Int>,
addingCount newItemCount: Int,
from producer: inout P
) throws(E) {
try replace(
removing: subrange,
addingCount: newItemCount
) { target throws(E) in
while !target.isFull {
guard try producer.generate(into: &target) else { break }
}
}
}
#endif
}
@available(SwiftStdlib 5.0, *)
extension RigidArray {
/// Replaces the specified subrange of elements by copying the elements of
@@ -176,6 +176,71 @@ extension UniqueArray where Element: ~Copyable {
self.append(moving: &items)
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Appends at most `newItemCount` items generated by a producer to the end of
/// this array.
///
/// If the array doesn't have sufficient capacity to accommodate the specified
/// number of new elements, then this method reallocates the array's storage
/// to grow it, using a geometric growth rate.
///
/// This operation appends as many items as the producer can generate before
/// either reaching its end (or throwing an error), or filling the specified
/// capacity. This operation only consumes the first `newItemCount` items in the
/// producer; if the producer has more, then they remain available after this
/// method returns.
///
/// - Parameters:
/// - newItemCount: The maximum number of items to append to the array.
/// - producer: A producer that generates the items to append.
///
/// - Complexity: O(*n*) where *n* is the number of new items, when
/// amortized over many similar invocations on the same array.
@_alwaysEmitIntoClient
public mutating func append<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
addingCount newItemCount: Int,
from producer: inout P
) throws(E) {
_ensureFreeCapacity(newItemCount)
try _storage.append(addingCount: newItemCount, from: &producer)
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Appends all the items generated by a producer to the end of this deque.
///
/// If the deque doesn't have sufficient capacity to accommodate all the
/// elements, then this method reallocates the deque's storage
/// to grow it, using a geometric growth rate.
///
/// - Parameters:
/// - producer: A producer that generates the items to append.
///
/// - Complexity: O(*n*) where *n* is the number of new items, when
/// amortized over many similarly-sized invocations on the same deque.
@_alwaysEmitIntoClient
public mutating func append<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
from producer: inout P
) throws(E) {
var done = false
while !done {
let c = Swift.max(producer.underestimatedCount, 1)
_ensureFreeCapacity(c)
try self.append(addingCount: freeCapacity) { target throws(E) in
while !target.isFull, !done {
done = try !producer.generate(into: &target)
}
}
}
}
#endif
}
@available(SwiftStdlib 5.0, *)
@@ -19,6 +19,11 @@ import ContainersPreview
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@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.
///
@@ -109,4 +114,54 @@ extension UniqueArray where Element: ~Copyable {
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@available(SwiftStdlib 5.0, *)
extension UniqueArray where Element: ~Copyable {
public typealias SubrangeConsumer = RigidArray<Element>.SubrangeConsumer
@_alwaysEmitIntoClient
@inline(__always)
@_lifetime(&self)
public mutating func consume(_ subrange: Range<Index>) -> SubrangeConsumer {
SubrangeConsumer(_base: &self._storage, offsetRange: subrange)
}
@_alwaysEmitIntoClient
@inline(__always)
@_lifetime(&self)
public mutating func consume<R: RangeExpression<Index>>(
_ subrange: R
) -> SubrangeConsumer {
consume(subrange.relative(to: indices))
}
@_alwaysEmitIntoClient
@inline(__always)
@_lifetime(&self)
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)
}
}
#endif
#endif
@@ -225,6 +225,56 @@ extension UniqueArray where Element: ~Copyable {
#endif
}
@available(SwiftStdlib 5.0, *)
extension UniqueArray where Element: ~Copyable {
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Inserts at most `newItemCount` items generated by a producer into this
/// array, starting at the given index.
///
/// Existing elements in the array's storage are moved as needed to make room
/// for the new items.
///
/// If the array does not have sufficient capacity to hold enough items,
/// then this reallocates the array's storage to grow its capacity, using a
/// geometric growth rate.
///
/// This operation inserts as many items as the producer can generate before
/// either reaching `newItemCount`, or the producer hitting its end, or
/// throwing an error. If the producer has more than `newItemCount` items
/// left in its underlying sequence, then extra items remain available after
/// this method returns.
///
/// If the operation inserts fewer than `newItemCount` items, then it results
/// in a gap in array storage that needs to be closed by moving some
/// items to their correct positions given the adjusted count. This adds some
/// overhead compared to adding exactly as many items as promised.
///
/// - Parameters:
/// - newItemCount: The maximum number of items to insert into the array.
/// - index: The position at which to insert the new items.
/// `index` must be a valid index in the array.
/// - producer: A producer that generates the items to append.
///
/// - Complexity: O(`self.count` + `newItemCount`) when amortized over many
/// similar invocations on the same array.
@_alwaysEmitIntoClient
public mutating func insert<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
addingCount newItemCount: Int,
from producer: inout P,
at index: Int
) throws(E) {
try insert(addingCount: newItemCount, at: index) { target throws(E) in
while !target.isFull, try producer.generate(into: &target) {
// Do nothing
}
}
}
#endif
}
@available(SwiftStdlib 5.0, *)
extension UniqueArray {
/// Copyies the elements of a fully initialized buffer pointer into this
@@ -341,6 +341,65 @@ extension UniqueArray where Element: ~Copyable {
}
}
@available(SwiftStdlib 5.0, *)
extension UniqueArray where Element: ~Copyable {
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Replaces the specified range of elements by at most `maximumCount` items
/// generated by a producer.
///
/// 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 doesn't have sufficient capacity to accommodate the new
/// elements, then this method reallocates the array's storage to grow it,
/// using a geometric growth rate.
///
/// If you pass a zero-length range as the `subrange` parameter, this method
/// inserts the items generated by `producer` at `subrange.lowerBound`. This
/// case is more directly expressed by calling `insert(moving:at:)`.
///
/// Likewise, if the given producer is empty, then this method removes the
/// elements in the given subrange without replacement. This case is more
/// directly expressed by calling `removeSubrange`.
///
/// This operation inserts as many items as the producer can generate before
/// either reaching `maximumCount`, or the producer hitting its end, or
/// throwing an error. If the producer has more than `maximumCount` items left in
/// its underlying sequence, then extra items remain available after this
/// method returns.
///
/// If the operation inserts fewer than `newItemCount` items, then it results in
/// a gap in array storage that needs to be closed by moving some
/// items to their correct positions given the adjusted count. This adds some
/// overhead compared to adding exactly as many items as promised.
///
/// - Parameters:
/// - subrange: The subrange of the array to replace. The bounds of
/// the range must be valid indices in the array.
/// - newItemCount: The maximum number of items to insert into the deque.
/// - producer: A producer that generates the items to append.
///
/// - Complexity: O(`self.count` + `newItemCount`)
@_alwaysEmitIntoClient
public mutating func replace<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
removing subrange: Range<Int>,
addingCount newItemCount: Int,
from producer: inout P
) throws(E) {
try replace(removing: subrange, addingCount: newItemCount) { target throws(E) in
while !target.isFull, try producer.generate(into: &target) {
// Do nothing
}
}
}
#endif
}
@available(SwiftStdlib 5.0, *)
extension UniqueArray {
/// Replaces the specified subrange of elements by copying the elements of
@@ -580,10 +639,10 @@ extension UniqueArray {
/// *m* is the count of `newElements`.
@inlinable
@inline(__always)
public mutating func replaceSubrange<
public mutating func replace<
C: Container<Element> & Collection<Element>
>(
_ subrange: Range<Int>,
removing subrange: Range<Int>,
copying newElements: borrowing C
) {
// FIXME: Avoid moving the subsequent elements twice.
@@ -65,7 +65,7 @@ extension RigidDeque where Element: ~Copyable {
/// var buffer = RigidDeque<Int>(capacity: 20)
/// buffer.append(999)
/// var i = 0
/// buffer.append(maximumCount: 6) { target in
/// buffer.append(addingCount: 6) { target in
/// while !target.isFull {
/// target.append(i)
/// i += 1
@@ -83,7 +83,7 @@ extension RigidDeque where Element: ~Copyable {
/// var buffer = RigidDeque<Int>(capacity: 20)
/// buffer.append(999)
/// var i = 0
/// buffer.append(maximumCount: 6) { target in
/// buffer.append(addingCount: 6) { target in
/// while !target.isFull, i <= 3 {
/// target.append(i)
/// i += 1
@@ -92,22 +92,22 @@ extension RigidDeque where Element: ~Copyable {
/// // `buffer` now contains [999, 0, 1, 2, 3]
///
/// - Parameters:
/// - maximumCount: The maximum number of items to append to the deque.
/// - newItemCount: The maximum number of items to append to the deque.
/// - body: A callback that gets called at most twice to directly
/// populate newly reserved storage within the deque.
///
/// - Complexity: O(`maximumCount`) in addition to the complexity of the callback
/// - Complexity: O(`newItemCount`) in addition to the complexity of the callback
/// invocations.
@_alwaysEmitIntoClient
@inline(__always)
public mutating func append<E: Error>(
maximumCount: Int,
addingCount newItemCount: Int,
initializingWith body: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) -> Void {
precondition(maximumCount >= 0, "Cannot append a negative number of items")
guard maximumCount > 0 else { return }
precondition(freeCapacity >= maximumCount, "RigidDeque capacity overflow")
try _handle.uncheckedAppend(maximumCount: maximumCount, initializingWith: body)
precondition(newItemCount >= 0, "Cannot append a negative number of items")
guard newItemCount > 0 else { return }
precondition(freeCapacity >= newItemCount, "RigidDeque capacity overflow")
try _handle.uncheckedAppend(addingCount: newItemCount, initializingWith: body)
}
}
@@ -177,7 +177,7 @@ extension RigidDeque where Element: ~Copyable {
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Appends at most `maximumCount` items generated by a producer to the end of
/// Appends at most `newItemCount` items generated by a producer to the end of
/// this deque.
///
/// If the target deque does not have sufficient capacity to hold the
@@ -185,12 +185,12 @@ extension RigidDeque where Element: ~Copyable {
///
/// This operation appends as many items as the producer can generate before
/// either reaching its end (or throwing an error), or filling the specified
/// capacity. This operation only consumes the first `maximumCount` items in the
/// capacity. This operation only consumes the first `newItemCount` items in the
/// producer; if the producer has more, then they remain available after this
/// method returns.
///
/// - Parameters:
/// - maximumCount: The maximum number of items to append to the deque, or
/// - newItemCount: The maximum number of items to append to the deque, or
/// nil to use all available capacity.
/// - producer: A producer that generates the items to append.
///
@@ -200,16 +200,51 @@ extension RigidDeque where Element: ~Copyable {
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
maximumCount: Int? = nil,
addingCount newItemCount: Int,
from producer: inout P
) throws(E) {
try self.append(
maximumCount: maximumCount ?? self.freeCapacity
) { target throws(E) in
try producer.generate(into: &target)
try self.append(addingCount: newItemCount) { target throws(E) in
while !target.isFull {
guard try producer.generate(into: &target) else { break }
}
}
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Appends all the items generated by a producer to the end of this deque.
///
/// If the target deque does not have sufficient capacity to hold all the
/// new items, then this triggers a runtime error.
///
/// - Parameters:
/// - producer: A producer that generates the items to append.
///
/// - Complexity: O(*n*), where *n* is the number of items produced.
@_alwaysEmitIntoClient
public mutating func append<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
from producer: inout P
) throws(E) {
var done = false
try self.append(
addingCount: freeCapacity
) { target throws(E) in
while !target.isFull {
guard try producer.generate(into: &target) else {
done = true
break
}
}
}
if !done {
done = (try producer.generateNext() == nil)
}
precondition(done, "RigidDeque capacity overflow")
}
#endif
}
@available(SwiftStdlib 5.0, *)
@@ -230,7 +230,7 @@ extension RigidDeque where Element: ~Copyable {
@inline(__always)
@_lifetime(&_base)
internal init(_base: inout RigidDeque, offsetRange: Range<Int>) {
_base._checkValidBounds(subrange)
_base._checkValidBounds(offsetRange)
let segments = _base._handle.mutableSegments(forOffsets: offsetRange)
self._buffer1 = segments.first
self._buffer2 = segments.second ?? .init(start: nil, count: 0)
@@ -47,7 +47,7 @@ extension RigidDeque where Element: ~Copyable {
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) {
self.init(_handle: .allocate(capacity: capacity))
try self.append(maximumCount: capacity, initializingWith: initializer)
try self.append(addingCount: capacity, initializingWith: initializer)
}
}
@@ -68,11 +68,10 @@ extension RigidDeque where Element: ~Copyable {
extension RigidDeque where Element: ~Copyable {
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Creates a new rigid deque of the specified capacity, populating it with
/// items generated by a given producer.
/// all items generated by a given producer.
///
/// The deque is appended as many items as possible before the producer
/// reaches its end. No more than `capacity` elements are retrieved from the
/// producer.
/// If the capacity is exhausted before the producer reaches its end, then
/// this triggers a runtime error.
///
/// If the producer throws an error during this initializer, then all
/// previously produced items are discarded and the initializer rethrows the
@@ -87,7 +86,8 @@ extension RigidDeque where Element: ~Copyable {
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
capacity: Int, from producer: inout P
capacity: Int,
from producer: inout P
) throws(E) {
self.init(capacity: capacity)
try self.append(from: &producer)
@@ -88,7 +88,7 @@ extension RigidDeque where Element: ~Copyable {
/// var buffer = RigidDeque<Int>(capacity: 20)
/// buffer.append(999)
/// var i = 0
/// buffer.prepend(count: 6) { target in
/// buffer.prepend(addingCount: 6) { target in
/// while !target.isFull, i <= 3 {
/// target.append(i)
/// i += 1
@@ -181,17 +181,17 @@ extension RigidDeque where Element: ~Copyable {
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Prepends at most `maximumCount` items generated by a producer to the front of
/// this deque.
/// Prepends at most `newItemCount` items generated by a producer to the
/// front of this deque.
///
/// If the target deque does not have sufficient capacity to hold the
/// specified number of new items, then this triggers a runtime error.
///
/// This operation prepends as many items as the producer can generate before
/// either reaching its end (or throwing an error), or filling the specified
/// capacity. This operation only consumes the first `maximumCount` items in the
/// producer; if the producer has more, then they remain available after this
/// method returns.
/// capacity. This operation only consumes the first `newItemCount` items in
/// the producer; if the producer has more, then they remain available after
/// this method returns.
///
/// Note: Partial prepends create a gap in ring buffer storage that needs to
/// be closed by moving newly prepended items to their correct positions given
@@ -204,18 +204,18 @@ extension RigidDeque where Element: ~Copyable {
/// - producer: A producer that generates the items to prepend.
///
/// - Complexity: O(`maximumCount ?? self.freeCapacity`)
/// - Complexity: O(`newItemCount ?? self.freeCapacity`)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func prepend<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
maximumCount: Int? = nil,
addingCount newItemCount: Int? = nil,
from producer: inout P
) throws(E) {
try self.prepend(
addingCount: maximumCount ?? freeCapacity
addingCount: newItemCount ?? freeCapacity
) { target throws(E) in
try producer.generate(into: &target)
}
@@ -328,7 +328,9 @@ extension RigidDeque where Element: ~Copyable {
removing: subrange,
addingCount: newItemCount
) { target throws(E) in
try producer.generate(into: &target)
while !target.isFull {
guard try producer.generate(into: &target) else { break }
}
}
}
#endif
@@ -48,7 +48,7 @@ extension UniqueDeque where Element: ~Copyable {
/// var buffer = UniqueDeque<Int>()
/// buffer.append(999)
/// var i = 0
/// buffer.append(maximumCount: 6) { target in
/// buffer.append(addingCount: 6) { target in
/// while !target.isFull {
/// target.append(i)
/// i += 1
@@ -66,7 +66,7 @@ extension UniqueDeque where Element: ~Copyable {
/// var buffer = UniqueDeque<Int>()
/// buffer.append(999)
/// var i = 0
/// buffer.append(maximumCount: 6) { target in
/// buffer.append(addingCount: 6) { target in
/// while !target.isFull, i <= 3 {
/// target.append(i)
/// i += 1
@@ -75,23 +75,23 @@ extension UniqueDeque where Element: ~Copyable {
/// // `buffer` now contains [999, 0, 1, 2, 3]
///
/// - Parameters:
/// - maximumCount: The maximum number of items to append to the deque.
/// - newItemCount: The maximum number of items to append to the deque.
/// - body: A callback that gets called at most twice to directly
/// populate newly reserved storage within the deque.
///
/// - Complexity: O(`maximumCount`) in addition to the complexity of the callback
/// - Complexity: O(`newItemCount`) in addition to the complexity of the callback
/// invocations, when amortized over many similar invocations on the same
/// deque.
@_alwaysEmitIntoClient
@inline(__always)
public mutating func append<E: Error>(
maximumCount: Int,
addingCount newItemCount: Int,
initializingWith body: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) -> Void {
guard maximumCount > 0 else { return }
_ensureFreeCapacity(maximumCount)
guard newItemCount > 0 else { return }
_ensureFreeCapacity(newItemCount)
try _storage._handle.uncheckedAppend(
maximumCount: maximumCount, initializingWith: body)
addingCount: newItemCount, initializingWith: body)
}
}
@@ -167,9 +167,8 @@ extension UniqueDeque where Element: ~Copyable {
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Appends at most `maximumCount` items generated by a producer to the end of
/// this deque. If `maximumCount` is nil, this appends every item the producer
/// can generate.
/// Appends at most `newItemCount` items generated by a producer to the end of
/// this deque.
///
/// If the deque doesn't have sufficient capacity to accommodate the specified
/// number of new elements, then this method reallocates the deque's storage
@@ -177,13 +176,12 @@ extension UniqueDeque where Element: ~Copyable {
///
/// This operation appends as many items as the producer can generate before
/// either reaching its end (or throwing an error), or filling the specified
/// capacity. This operation only consumes the first `maximumCount` items in the
/// capacity. This operation only consumes the first `newItemCount` items in the
/// producer; if the producer has more, then they remain available after this
/// method returns.
///
/// - Parameters:
/// - maximumCount: The maximum number of items to append to the deque, or
/// nil to append every item the producer generates.
/// - newItemCount: The maximum number of items to append to the deque.
/// - producer: A producer that generates the items to append.
///
/// - Complexity: O(*n*) where *n* is the number of new items, when
@@ -193,28 +191,39 @@ extension UniqueDeque where Element: ~Copyable {
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
maximumCount: Int? = nil,
addingCount newItemCount: Int,
from producer: inout P
) throws(E) {
if let maximumCount {
_ensureFreeCapacity(maximumCount)
try _storage._handle.uncheckedAppend(
maximumCount: maximumCount
) { target throws(E) in
while !target.isFull, try producer.generate(into: &target) {
// Do nothing
}
}
return
}
while true {
_ensureFreeCapacity(1)
try _storage._handle.uncheckedAppend(
maximumCount: freeCapacity
) { target throws(E) in
while !target.isFull, try producer.generate(into: &target) {
// Do nothing
_ensureFreeCapacity(newItemCount)
try _storage.append(addingCount: newItemCount, from: &producer)
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Appends all the items generated by a producer to the end of this deque.
///
/// If the deque doesn't have sufficient capacity to accommodate all the
/// elements, then this method reallocates the deque's storage
/// to grow it, using a geometric growth rate.
///
/// - Parameters:
/// - producer: A producer that generates the items to append.
///
/// - Complexity: O(*n*) where *n* is the number of new items, when
/// amortized over many similarly-sized invocations on the same deque.
@_alwaysEmitIntoClient
public mutating func append<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
from producer: inout P
) throws(E) {
var done = false
while !done {
let c = Swift.max(producer.underestimatedCount, 1)
try self.append(addingCount: c) { target throws(E) in
while !target.isFull, !done {
done = try !producer.generate(into: &target)
}
}
}
@@ -80,9 +80,30 @@ extension UniqueDeque where Element: ~Copyable {
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
capacity: Int, from producer: inout P
capacity: Int,
from producer: inout P
) throws(E) {
self.init(capacity: capacity)
try self.append(addingCount: capacity, from: &producer)
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Creates a new unique deque, populating it with
/// all items generated by a given producer.
///
/// - Parameters:
/// - producer: A producer that generates the items to append to the new
/// deque.
///
/// - Complexity: O(`capacity`)
public init<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
from producer: inout P
) throws(E) {
self.init(capacity: producer.underestimatedCount)
try self.append(from: &producer)
}
#endif
@@ -48,7 +48,7 @@ extension UniqueDeque where Element: ~Copyable {
/// var buffer = RigidDeque<Int>()
/// buffer.append(999)
/// var i = 0
/// buffer.prepend(count: 6) { target in
/// buffer.prepend(addingCount: 6) { target in
/// while !target.isFull {
/// target.append(i)
/// i += 1
@@ -71,7 +71,7 @@ extension UniqueDeque where Element: ~Copyable {
/// var buffer = RigidDeque<Int>()
/// buffer.append(999)
/// var i = 0
/// buffer.prepend(count: 6) { target in
/// buffer.prepend(addingCount: 6) { target in
/// while !target.isFull, i <= 3 {
/// target.append(i)
/// i += 1
@@ -80,22 +80,22 @@ extension UniqueDeque 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, when amortized over many similar invocations on the same
/// deque.
@_alwaysEmitIntoClient
public mutating func prepend<E: Error>(
maximumCount: Int,
addingCount newItemCount: Int,
initializingWith body: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) -> Void {
guard maximumCount > 0 else { return }
_ensureFreeCapacity(maximumCount)
guard newItemCount > 0 else { return }
_ensureFreeCapacity(newItemCount)
try _storage._handle.uncheckedPrepend(
addingCount: maximumCount, initializingWith: body)
addingCount: newItemCount, initializingWith: body)
}
}
@@ -172,9 +172,8 @@ extension UniqueDeque where Element: ~Copyable {
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Prepends at most `maximumCount` items generated by a producer to the front of
/// this deque. If `maximumCount` is nil, this appends every item the producer
/// can generate.
/// Prepends at most `newItemCount` items generated by a producer to the front
/// of this deque.
///
/// If the deque doesn't have sufficient capacity to accommodate the specified
/// number of new elements, then this method reallocates the deque's storage
@@ -182,9 +181,9 @@ extension UniqueDeque where Element: ~Copyable {
///
/// This operation prepends as many items as the producer can generate before
/// either reaching its end (or throwing an error), or filling the specified
/// capacity. This operation only consumes the first `maximumCount` items in the
/// producer; if the producer has more, then they remain available after this
/// method returns.
/// capacity. This operation only consumes the first `newItemCount` items in
/// the producer; if the producer has more, then they remain available after
/// this method returns.
///
/// Note: Partial prepends create a gap in ring buffer storage that needs to
/// be closed by moving newly prepended items to their correct positions given
@@ -192,8 +191,7 @@ extension UniqueDeque where Element: ~Copyable {
/// many items as promised.
///
/// - Parameters:
/// - maximumCount: The maximum number of items to prepend to the deque, or
/// nil to use all available capacity.
/// - newItemCount: The maximum number of items to prepend to the deque.
/// - producer: A producer that generates the items to prepend.
///
/// - Complexity: O(*n*) where *n* is the number of new items, when
@@ -204,28 +202,47 @@ extension UniqueDeque where Element: ~Copyable {
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
maximumCount: Int? = nil,
addingCount newItemCount: Int,
from producer: inout P
) throws(E) {
if let maximumCount {
_ensureFreeCapacity(maximumCount)
try _storage._handle.uncheckedPrepend(
addingCount: maximumCount
) { target throws(E) in
while !target.isFull, try producer.generate(into: &target) {
// Do nothing
}
_ensureFreeCapacity(newItemCount)
try _storage._handle.uncheckedPrepend(
addingCount: newItemCount
) { target throws(E) in
while !target.isFull, try producer.generate(into: &target) {
// Do nothing
}
return
}
while true {
_ensureFreeCapacity(1)
try _storage._handle.uncheckedAppend(
maximumCount: freeCapacity
) { target throws(E) in
while !target.isFull, try producer.generate(into: &target) {
// Do nothing
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// Prepends all items generated by a producer to the front of this deque.
///
/// If the deque doesn't have sufficient capacity to accommodate all the
/// items, then this method reallocates the deque's storage to grow it,
/// using a geometric growth rate.
///
/// - Parameters:
/// - producer: A producer that generates the items to prepend.
///
/// - Complexity: O(*n*) where *n* is the number of new items, when
/// amortized over many similarly-sized invocations on the same deque.
@_alwaysEmitIntoClient
@inline(__always)
public mutating func prepend<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
from producer: inout P
) throws(E) {
var done = false
while !done {
let c = Swift.max(producer.underestimatedCount, 1)
_ensureFreeCapacity(c)
try self.prepend(addingCount: freeCapacity) { target throws(E) in
while !target.isFull, !done {
done = try !producer.generate(into: &target)
}
}
}
@@ -321,7 +338,7 @@ extension UniqueDeque /*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)
}
@@ -343,7 +360,9 @@ extension UniqueDeque /*where Element: Copyable*/ {
/// - Complexity: O(*m*), where *m* is the length of `items`, as amortized
/// over many similar invocations on the same deque.
@_alwaysEmitIntoClient
public mutating func prepend<S: BorrowingSequence<Element> & ~Copyable & ~Escapable>(
public mutating func prepend<
S: BorrowingSequence<Element> & ~Copyable & ~Escapable
>(
copying items: borrowing S
) {
self._prepend(copying: items)
@@ -451,7 +470,9 @@ extension UniqueDeque /*where Element: Copyable*/ {
/// - Complexity: O(*m*), where *m* is the length of `items`, as amortized
/// over many similar invocations on the same deque.
@_alwaysEmitIntoClient
public mutating func prepend<S: BorrowingSequence<Element> & Sequence<Element>>(
public mutating func prepend<
S: BorrowingSequence<Element> & Sequence<Element>
>(
copying items: borrowing S
) {
self._prepend(copying: items)
@@ -468,7 +489,9 @@ extension UniqueDeque /*where Element: Copyable*/ {
/// - Complexity: O(*m*), where *m* is the length of `items` when amortized
/// over many similar invocations on the same deque.
@_alwaysEmitIntoClient
public mutating func prepend<S: BorrowingSequence<Element> & Collection<Element>>(
public mutating func prepend<
S: BorrowingSequence<Element> & Collection<Element>
>(
copying items: borrowing S
) {
self._prepend(copying: items, exactCount: items.count)
@@ -73,8 +73,8 @@ extension UniqueDeque where Element: ~Copyable {
///
/// - Complexity: O(`self.count` + `newCount`)
@inlinable
public mutating func replaceSubrange<E: Error>(
_ subrange: Range<Int>,
public mutating func replace<E: Error>(
removing subrange: Range<Int>,
addingCount newItemCount: Int,
initializingWith initializer: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) -> Void {
@@ -140,8 +140,8 @@ extension UniqueDeque where Element: ~Copyable {
/// - Complexity: O(`self.count` + `newItemCount`) in addition to the complexity
/// of the callback invocations.
@inlinable
public mutating func replaceSubrange<E: Error>(
_ subrange: Range<Int>,
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
@@ -190,12 +190,12 @@ extension UniqueDeque where Element: ~Copyable {
///
/// - Complexity: O(`self.count` + `items.count`)
@_alwaysEmitIntoClient
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
moving items: UnsafeMutableBufferPointer<Element>,
) {
var remainder = items
replaceSubrange(subrange, addingCount: remainder.count) { target in
replace(removing: subrange, addingCount: remainder.count) { target in
target.withUnsafeMutableBufferPointer { buffer, count in
buffer.moveInitializeAll(
fromContentsOf: remainder._trim(first: buffer.count))
@@ -234,13 +234,13 @@ extension UniqueDeque where Element: ~Copyable {
///
/// - Complexity: O(`self.count` + `items.count`)
@_alwaysEmitIntoClient
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
moving items: inout InputSpan<Element>
) {
items.withUnsafeMutableBufferPointer { buffer, count in
let source = buffer._extracting(last: count)
unsafe self.replaceSubrange(subrange, moving: source)
unsafe self.replace(removing: subrange, moving: source)
count = 0
}
}
@@ -274,19 +274,19 @@ extension UniqueDeque where Element: ~Copyable {
///
/// - Complexity: O(`self.count` + `items.count`)
@_alwaysEmitIntoClient
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
moving items: inout OutputSpan<Element>
) {
items.withUnsafeMutableBufferPointer { buffer, count in
let source = buffer._extracting(first: count)
unsafe self.replaceSubrange(subrange, moving: source)
unsafe self.replace(removing: subrange, moving: source)
count = 0
}
}
#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
@@ -307,12 +307,12 @@ extension UniqueDeque 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.
@@ -320,20 +320,20 @@ 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 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`)
/// - Complexity: O(`self.count` + `newItemCount`)
@_alwaysEmitIntoClient
public mutating func replaceSubrange<
public mutating func replace<
E: Error,
P: Producer<Element, E> & ~Copyable & ~Escapable
>(
_ subrange: Range<Int>,
removing subrange: Range<Int>,
addingCount newItemCount: Int,
from producer: inout P
) throws(E) {
try replaceSubrange(subrange, addingCount: newItemCount) { target throws(E) in
try replace(removing: subrange, addingCount: newItemCount) { target throws(E) in
while !target.isFull, try producer.generate(into: &target) {
// Do nothing
}
@@ -372,12 +372,12 @@ extension UniqueDeque /* where Element: Copyable */ {
///
/// - Complexity: O(`self.count` + `items.count`)
@inlinable
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
copying items: UnsafeBufferPointer<Element>
) {
var remainder = items
replaceSubrange(subrange, addingCount: remainder.count) { target in
replace(removing: subrange, addingCount: remainder.count) { target in
target.withUnsafeMutableBufferPointer { dst, dstCount in
dst.initializeAll(fromContentsOf: remainder._trim(first: dst.count))
dstCount += dst.count
@@ -414,12 +414,12 @@ extension UniqueDeque /* where Element: Copyable */ {
///
/// - Complexity: O(`self.count` + `items.count`)
@inlinable
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
copying items: UnsafeMutableBufferPointer<Element>
) {
unsafe self.replaceSubrange(
subrange,
unsafe self.replace(
removing: subrange,
copying: UnsafeBufferPointer(items))
}
@@ -451,28 +451,28 @@ extension UniqueDeque /* where Element: Copyable */ {
///
/// - Complexity: O(`self.count` + `items.count`)
@inlinable
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
copying items: Span<Element>
) {
unsafe items.withUnsafeBufferPointer { buffer in
unsafe self.replaceSubrange(subrange, copying: buffer)
unsafe self.replace(removing: subrange, copying: buffer)
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@inlinable
internal mutating func _replaceSubrange<
internal mutating func _replace<
C: Container<Element> & ~Copyable & ~Escapable
>(
_ subrange: Range<Int>,
removing subrange: Range<Int>,
copyingContainer items: borrowing C,
newCount: Int
) {
let expectedCount = self.count - subrange.count + newCount
var it = items.makeBorrowingIterator()
self.replaceSubrange(subrange, addingCount: newCount) { target in
self.replace(removing: subrange, addingCount: newCount) { target in
it.copyContents(into: &target)
}
precondition(
@@ -482,8 +482,8 @@ extension UniqueDeque /* where Element: Copyable */ {
#endif
@inlinable
internal mutating func _replaceSubrange(
_ subrange: Range<Int>,
internal mutating func _replace(
removing subrange: Range<Int>,
copyingCollection items: __owned some Collection<Element>,
newCount: Int
) {
@@ -491,12 +491,12 @@ extension UniqueDeque /* where Element: Copyable */ {
precondition(
src.count == newCount,
"Broken Collection: count doesn't match contents")
self.replaceSubrange(subrange, copying: src)
self.replace(removing: subrange, copying: src)
}
if done != nil { return }
var i = items.startIndex
self.replaceSubrange(subrange, addingCount: newCount) { target in
self.replace(removing: subrange, addingCount: newCount) { target in
while !target.isFull {
target.append(items[i])
items.formIndex(after: &i)
@@ -534,14 +534,14 @@ extension UniqueDeque /* where Element: Copyable */ {
/// - Complexity: O(`self.count` + `items.count`)
@inlinable
@inline(__always)
public mutating func replaceSubrange<
public mutating func replace<
C: Container<Element> & ~Copyable & ~Escapable
>(
_ subrange: Range<Int>,
removing subrange: Range<Int>,
copying items: borrowing C
) {
_replaceSubrange(
subrange, copyingContainer: items, newCount: items.count)
_replace(
removing: subrange, copyingContainer: items, newCount: items.count)
}
#endif
@@ -574,12 +574,12 @@ extension UniqueDeque /* where Element: Copyable */ {
/// - Complexity: O(`self.count` + `items.count`)
@inlinable
@inline(__always)
public mutating func replaceSubrange(
_ subrange: Range<Int>,
public mutating func replace(
removing subrange: Range<Int>,
copying items: __owned some Collection<Element>
) {
_replaceSubrange(
subrange, copyingCollection: items, newCount: items.count)
_replace(
removing: subrange, copyingCollection: items, newCount: items.count)
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@@ -613,14 +613,14 @@ extension UniqueDeque /* where Element: Copyable */ {
/// *m* is the count of `items`.
@inlinable
@inline(__always)
public mutating func replaceSubrange<
public mutating func replace<
C: Container<Element> & Collection<Element>
>(
_ subrange: Range<Int>,
removing subrange: Range<Int>,
copying items: C
) {
_replaceSubrange(
subrange, copyingContainer: items, newCount: items.count)
_replace(
removing: subrange, copyingContainer: items, newCount: items.count)
}
#endif
}
+2 -2
View File
@@ -690,10 +690,10 @@ extension _UnsafeDequeHandle where Element: ~Copyable {
/// - Complexity: O(`capacity`)
@_alwaysEmitIntoClient
internal mutating func uncheckedAppend<E: Error>(
maximumCount: Int,
addingCount newItemCount: Int,
initializingWith body: (inout OutputSpan<Element>) throws(E) -> Void
) throws(E) {
let gap = self.mutableSegments(forOffsets: count ..< count + maximumCount)
let gap = self.mutableSegments(forOffsets: count ..< count + newItemCount)
let c = self.count &+ gap.first.count
try gap.first._initialize(
initializedCount: &self.count, initializingWith: body)
@@ -246,6 +246,78 @@ class RigidSetTests: CollectionTestCase {
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_insert_producer() {
withEvery("capacity", in: [0, 1, 2, 4, 10, 100, 200]) { capacity in
withEvery("count", in: 0 ..< capacity) { count in
withEvery("chunkSize", in: [1, 2, 10, 100, Int.max]) { chunkSize in
withLifetimeTracking { tracker in
var s = RigidSet<LifetimeTracked<Int>>(capacity: capacity)
var i = 0
var p = CustomProducer<LifetimeTracked<Int>, Never>(
underestimatedCount: 0,
chunkSize: chunkSize
) {
guard i < count else { return nil }
defer { i += 1 }
return tracker.instance(for: i)
}
s.insert(from: &p)
expectEqual(s.capacity, capacity)
expectEqual(s.count, count)
var seen: Set<Int> = []
var index = s.startIndex
while index != s.endIndex {
let payload = s[index].payload
expectTrue(seen.insert(payload).inserted, "Duplicate item \(payload)")
index = s.index(after: index)
}
}
}
}
}
}
#endif
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_insert_drain() {
withEvery("capacity", in: [0, 1, 2, 4, 10, 100, 200]) { capacity in
withEvery("count", in: 0 ..< capacity) { count in
withEvery("chunkSize", in: [1, 2, 10, 100, 1000]) { chunkSize in
withLifetimeTracking { tracker in
var s = RigidSet<LifetimeTracked<Int>>(capacity: capacity)
var i = 0
var drain = CustomDrain<LifetimeTracked<Int>>(
underestimatedCount: 0,
chunkSize: chunkSize
) {
guard i < count else { return nil }
defer { i += 1 }
return tracker.instance(for: i)
}
s.insert(from: &drain)
expectEqual(s.capacity, capacity)
expectEqual(s.count, count)
var seen: Set<Int> = []
var index = s.startIndex
while index != s.endIndex {
let payload = s[index].payload
expectTrue(seen.insert(payload).inserted, "Duplicate item \(payload)")
index = s.index(after: index)
}
}
}
}
}
}
#endif
func test_remove_one() {
withEvery("count", in: [0, 1, 2, 4, 10, 100, 500]) { count in
withEvery("item", in: 0 ..< count) { item in
+11 -12
View File
@@ -346,7 +346,7 @@ final class RigidDequeTests: CollectionTestCase {
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_initFromProducer() {
withEvery("count", in: 0 ..< 10) { count in
withEvery("capacity", in: [count / 2, count, 2 * count] as Set) { capacity in
withEvery("capacity", in: [count, count + 1, 2 * count] as Set) { capacity in
withLifetimeTracking { tracker in
var invocations = 0
var producer = CustomProducer<LifetimeTrackedStruct<Int>, Never> {
@@ -357,14 +357,13 @@ final class RigidDequeTests: CollectionTestCase {
return tracker.structInstance(for: invocations)
}
let c = min(count, capacity)
let deque = RigidDeque(capacity: capacity, from: &producer)
expectEqual(invocations, c)
expectEqual(deque.count, c)
expectEqual(tracker.instances, c)
expectEqual(invocations, c)
expectEqual(invocations, count)
expectEqual(deque.count, count)
expectEqual(tracker.instances, count)
expectEqual(invocations, count)
for i in 0 ..< c {
for i in 0 ..< count {
expectEqual(deque[i].payload, i)
}
}
@@ -636,7 +635,7 @@ final class RigidDequeTests: CollectionTestCase {
data.contents.append(contentsOf: extras)
var i = 0
data.deque.append(maximumCount: prependCount) { target in
data.deque.append(addingCount: prependCount) { target in
while !target.isFull {
target.append(extras[i])
i += 1
@@ -684,7 +683,7 @@ final class RigidDequeTests: CollectionTestCase {
data.contents.append(contentsOf: extras)
var i = 0
data.deque.append(maximumCount: layout.freeCapacity) { target in
data.deque.append(addingCount: layout.freeCapacity) { target in
while !target.isFull, i < prependCount {
target.append(extras[i])
i += 1
@@ -746,7 +745,7 @@ final class RigidDequeTests: CollectionTestCase {
expectThrows { () throws(TestError) in
var i = 0
try data.deque.append(
maximumCount: layout.freeCapacity
addingCount: layout.freeCapacity
) { target throws(TestError) in
while !target.isFull, i < prependCount {
target.append(extras[i])
@@ -794,13 +793,13 @@ final class RigidDequeTests: CollectionTestCase {
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
func test_append_Producer() {
withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in
withEvery("producerSize", in: 0 ..< 6) { producerSize in
withEvery("producerSize", in: 0 ..< layout.freeCapacity) { producerSize in
withLifetimeTracking { tracker in
var data = tracker.rigidDeque(with: layout)
var extras = tracker.instances(for: 0 ..< producerSize)
data.contents.append(contentsOf: extras.prefix(layout.freeCapacity))
data.contents.append(contentsOf: extras)
var producer = CustomProducer<LifetimeTracked<Int>, Never> {
guard !extras.isEmpty else { return nil }
@@ -0,0 +1,61 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// 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
//
//===----------------------------------------------------------------------===//
#if COLLECTIONS_SINGLE_MODULE
import Collections
#else
import InternalCollectionsUtilities
import BasicContainers
import ContainersPreview
#endif
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@available(SwiftStdlib 5.0, *)
package struct CustomDrain<Element: ~Copyable>: ~Copyable {
package let underestimatedCount: Int
package let _chunkSize: Int
package let _generator: () -> Element?
package var _buffer: RigidArray<Element>
package var _remainder: Int
package init(
underestimatedCount: Int = 0,
chunkSize: Int,
generatingWith generator: @escaping () -> Element?
) {
self.underestimatedCount = underestimatedCount
self._chunkSize = chunkSize
self._generator = generator
self._buffer = .init(capacity: _chunkSize)
self._remainder = _chunkSize
}
}
@available(SwiftStdlib 5.0, *)
extension CustomDrain: Drain where Element: ~Copyable {
@_lifetime(&self)
package mutating func drainNext(maximumCount: Int) -> InputSpan<Element> {
assert(_buffer.isEmpty)
if _remainder == 0 {
_remainder = _chunkSize
}
let c = Swift.min(maximumCount, _remainder)
_remainder -= c
for _ in 0 ..< c {
guard let next = _generator() else { break }
_buffer.append(next)
}
return _buffer._consumeAll()
}
}
#endif
@@ -21,14 +21,17 @@ import ContainersPreview
@available(SwiftStdlib 5.0, *)
package struct CustomProducer<Element: ~Copyable, ProducerError: Error>: ~Copyable {
package let underestimatedCount: Int
package let generator: () throws(ProducerError) -> Element?
package let _chunkSize: Int
package let _generator: () throws(ProducerError) -> Element?
package init(
underestimatedCount: Int = 0,
chunkSize: Int = Int.max,
generatingWith generator: borrowing @escaping () throws(ProducerError) -> Element?
) {
self.underestimatedCount = underestimatedCount
self.generator = copy generator
self._chunkSize = chunkSize
self._generator = copy generator
}
}
@@ -37,9 +40,11 @@ extension CustomProducer: Producer where Element: ~Copyable {
package mutating func generate(
into target: inout OutputSpan<Element>
) throws(ProducerError) -> Bool {
while !target.isFull {
guard let next = try generator() else { return false }
var i = 0
while !target.isFull, i < _chunkSize {
guard let next = try _generator() else { return false }
target.append(next)
i += 1
}
return true
}
@@ -517,6 +517,7 @@
7DEB31682F52271900F9AF28 /* RigidDictionary+Index.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEB31672F52271300F9AF28 /* RigidDictionary+Index.swift */; };
7DEB316A2F52284200F9AF28 /* UniqueDictionary+Index.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEB31692F52283C00F9AF28 /* UniqueDictionary+Index.swift */; };
7DEB316C2F522EAB00F9AF28 /* UniqueDictionary+Indices.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEB316B2F522EA300F9AF28 /* UniqueDictionary+Indices.swift */; };
7DEB316E2F5281FC00F9AF28 /* CustomDrain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEB316D2F5281FC00F9AF28 /* CustomDrain.swift */; };
7DEBDB6E29CCE44A00ADC226 /* SortedCollectionAPIChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3029CCE43600ADC226 /* SortedCollectionAPIChecker.swift */; };
7DEBDB6F29CCE44A00ADC226 /* MinimalMutableRangeReplaceableRandomAccessCollection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB3F29CCE43600ADC226 /* MinimalMutableRangeReplaceableRandomAccessCollection.swift */; };
7DEBDB7029CCE44A00ADC226 /* ResettableValue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DEBDB4229CCE43600ADC226 /* ResettableValue.swift */; };
@@ -1120,6 +1121,7 @@
7DEB31672F52271300F9AF28 /* RigidDictionary+Index.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidDictionary+Index.swift"; sourceTree = "<group>"; };
7DEB31692F52283C00F9AF28 /* UniqueDictionary+Index.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDictionary+Index.swift"; sourceTree = "<group>"; };
7DEB316B2F522EA300F9AF28 /* UniqueDictionary+Indices.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDictionary+Indices.swift"; sourceTree = "<group>"; };
7DEB316D2F5281FC00F9AF28 /* CustomDrain.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CustomDrain.swift; sourceTree = "<group>"; };
7DEBDB2129CCE43600ADC226 /* Combinatorics.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Combinatorics.swift; sourceTree = "<group>"; };
7DEBDB2229CCE43600ADC226 /* TestContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestContext.swift; sourceTree = "<group>"; };
7DEBDB2329CCE43600ADC226 /* Assertions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Assertions.swift; sourceTree = "<group>"; };
@@ -2274,6 +2276,7 @@
children = (
7DEBDB3B29CCE43600ADC226 /* _CollectionState.swift */,
7DEBDB4629CCE43600ADC226 /* _MinimalCollectionCore.swift */,
7DEB316D2F5281FC00F9AF28 /* CustomDrain.swift */,
7D2A77482F27F271005780C7 /* CustomProducer.swift */,
7DEBDB4029CCE43600ADC226 /* MinimalBidirectionalCollection.swift */,
7DEBDB4829CCE43600ADC226 /* MinimalCollection.swift */,
@@ -2946,6 +2949,7 @@
7DE9221B29CA8576004483EB /* DequeInternals.swift in Sources */,
7DEBDB6E29CCE44A00ADC226 /* SortedCollectionAPIChecker.swift in Sources */,
7DE9220929CA8576004483EB /* BitArrayTests.swift in Sources */,
7DEB316E2F5281FC00F9AF28 /* CustomDrain.swift in Sources */,
7DC85F8F2F43D065004A4E3D /* RigidDictionaryTests.swift in Sources */,
7D7246922F3D9E6800112FD0 /* RigidSetTests.swift in Sources */,
7DE9221629CA8576004483EB /* OrderedSet.UnorderedView Tests.swift in Sources */,
+2 -1
View File
@@ -31,7 +31,8 @@ OTHER_SWIFT_FLAGS = $(inherited) \
-enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.10: macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.1" \
-enable-experimental-feature "AvailabilityMacro=SwiftStdlib 6.0: macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0" \
-enable-experimental-feature "AvailabilityMacro=SwiftStdlib 6.1: macOS 15.4, iOS 18.4, watchOS 11.4, tvOS 18.4, visionOS 2.4" \
-enable-experimental-feature "AvailabilityMacro=SwiftStdlib 6.2: macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0"
-enable-experimental-feature "AvailabilityMacro=SwiftStdlib 6.2: macOS 26.0, iOS 26.0, watchOS 26.0, tvOS 26.0, visionOS 26.0" \
-enable-experimental-feature "AvailabilityMacro=SwiftStdlib 6.3: macOS 26.4, iOS 26.4, watchOS 26.4, tvOS 26.4, visionOS 26.4"
ONLY_ACTIVE_ARCH[config=Debug] = YES