Files
swift-collections/Sources/ContainersPreview/Protocols/Producer+Collect.swift
T

61 lines
2.1 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 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 compiler(>=6.4) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@available(SwiftStdlib 5.0, *)
extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable {
@inlinable
public consuming func collect<
R: DynamicContainer<Element> & ~Copyable
>(
into container: R.Type = R.self
) throws(ProducerError) -> R {
try R(from: self)
}
/// Collect all items generated by this producer into the provided
/// range-replaceable container instance, which must be able to accommodate
/// every new element.
@inlinable
public consuming func collect(
into container: inout some RangeReplaceableContainer<Element> & ~Copyable & ~Escapable
) throws(ProducerError) {
// Note: this is the same algorithm as `append(from:)` on `DynamicContainer`,
// except it applies to RRCs.
while true {
let c = Swift.max(self.underestimatedCount, container.freeCapacity)
if c > 0 {
try container.append(addingCount: c, from: &self)
}
guard let next = try self.next() else { break }
// If `container` is of a fixed-capacity type, then this will likely
// trap (as expected). On the other hand, if it is a dynamically resizing
// type, then this will reallocate its storage, setting up the bulk
// append in the next iteration.
container.append(next)
}
}
/// Collect all items generated by this producer into the provided
/// dynamic container instance, resizing it if necessary.
@inlinable
public consuming func collect(
into container: inout some DynamicContainer<Element> & ~Copyable
) throws(ProducerError) {
try container.append(from: self)
}
}
#endif