[BasicContainers] Add Producer-based array operations

This commit is contained in:
Karoy Lorentey committed 2026-02-27 17:58:21 -08:00
1 parent 50978111dc
commit bc7b0ff73d
6 files changed
+352

No files matched your search

@@ -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, *)