Iterable → BorrowingSequence, BorrowIterator → BorrowingIterator

This commit is contained in:
Karoy Lorentey committed 2026-01-25 16:42:37 -08:00
1 parent fabe5d8c87
commit e4aba4c1c9
24 files changed
+287 -187

No files matched your search

@@ -0,0 +1,199 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
#if !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
@available(SwiftStdlib 5.0, *)
public protocol BorrowingIteratorProtocol<Element>: ~Copyable, ~Escapable {
associatedtype Element: ~Copyable
// FIXME: This ought to be a core requirement, but `Ref` is not a thing yet.
// @_lifetime(&self)
// @_lifetime(self: copy self)
// mutating func next() -> Ref<Element>?
/// Advance the iterator, returning an ephemeral span over the elements
/// that are ready to be visited.
///
/// If the underlying sequence is a container type, then the returned span
/// typically directly addresses one of its storage buffers. On the other
/// hand, if the underlying sequence materializes its elements on demand,
/// then the returned span addresses some temporary buffer associated with
/// the iterator itself. Consequently, the returned span is tied to this
/// particular invocation of `nextSpan`, and it cannot survive until the next
/// invocation of it.
///
/// If the iterator has not yet reached the end of the underlying sequence,
/// then this method returns a non-empty span of at most `maximumCount`
/// elements, and updates the iterator's current position to the element
/// following the last item in the returned span (or the end, if there is
/// none). The `maximumCount` argument allows callers to avoid getting more
/// items that they are able to process in one go, simplifying usage, and
/// avoiding materializing more elements than needed.
///
/// If the iterator's current position is at the end of the container, then
/// this method returns an empty span without updating the position.
///
/// This method can be used to efficiently process the items of a container
/// in bulk, by directly iterating over its piecewise contiguous pieces of
/// storage:
///
/// var it = items.makeBorrowingIterator()
/// while true {
/// let span = it.nextSpan(after: &index)
/// if span.isEmpty { break }
/// // Process items in `span`
/// }
///
/// Note: The spans returned by this method are not guaranteed to be disjunct.
/// Iterators that materialize elements on demand typically reuse the same
/// buffer over and over again; and even some proper containers may link to a
/// single storage chunk (or parts of a storage chunk) multiple times, for
/// example to repeat their contents.
///
/// Note: Repeatedly iterating over the same container is expected to return
/// the same items (collected in similarly sized span instances), but the
/// returned spans are not guaranteed to be identical. For example, this is
/// the case with containers that store some of their contents within their
/// direct representation. Such containers may not always have a unique
/// address in memory, and so the locations of the spans exposed by this
/// method may vary between different borrows of the same container.)
@_lifetime(&self)
@_lifetime(self: copy self)
mutating func nextSpan(maximumCount: Int) -> Span<Element>
/// Advance the position of this iterator by the specified offset, or until
/// the end of the underlying sequence.
///
/// Returns the number of items that were skipped. If this is less than
/// `maximumOffset`, then the sequence did not have enough elements left to
/// skip the requested number of items. In this case, the iterator's current
/// position is set to the end of the sequence.
///
/// `maximumOffset` must be nonnegative, unless this is a bidirectional
/// or random-access iterator.
@_lifetime(self: copy self)
mutating func skip(by maximumOffset: Int) -> Int
// FIXME: Add BidirectionalBorrowingIteratorProtocol and RandomAccessBorrowingIteratorProtocol.
// BidirectionalBorrowingIteratorProtocol would need to have a `previousSpan`
// method, which considerably complicates implementation.
// Perhaps these would be better left to as variants of protocol Container,
// which do not need a separate iterator concept.
}
@available(SwiftStdlib 5.0, *)
extension BorrowingIteratorProtocol where Self: ~Copyable & ~Escapable {
@_lifetime(&self)
@_lifetime(self: copy self)
@_transparent
public mutating func nextSpan() -> Span<Element> {
nextSpan(maximumCount: Int.max)
}
}
@available(SwiftStdlib 5.0, *)
extension BorrowingIteratorProtocol where Self: ~Copyable & ~Escapable {
@_lifetime(self: copy self)
@inlinable
public mutating func skip(by offset: Int) -> Int {
var remainder = offset
while remainder > 0 {
let span = nextSpan(maximumCount: remainder)
if span.isEmpty { break }
remainder &-= span.count
}
return offset &- remainder
}
}
@available(SwiftStdlib 5.0, *)
extension BorrowingIteratorProtocol where Self: ~Copyable & ~Escapable {
#if false // FIXME: This doesn't work, but it should?
@_lifetime(&self)
@_lifetime(self: copy self)
public mutating func next() -> Ref<Element>? {
let span = nextSpan(maximumCount: 1)
guard !span.isEmpty else { return nil }
return Ref(_borrowing: span[unchecked: 0])
}
#endif
// @_lifetime(&self)
// @_lifetime(self: copy self)
// public mutating func nextSpan(maximumCount: Int) -> Span<Element> {
// guard let ref = next() else { return Span() }
// return ref.span // FIXME
// }
}
@available(SwiftStdlib 5.0, *)
extension BorrowingIteratorProtocol
where Self: ~Copyable & ~Escapable, Element: Copyable
{
@_lifetime(self: copy self)
@_transparent
public mutating func copyContents(into target: inout OutputSpan<Element>) {
target.withUnsafeMutableBufferPointer { dst, dstCount in
var tail = dst._extracting(droppingFirst: dstCount)
while !tail.isEmpty {
let src = nextSpan(maximumCount: tail.count)
if src.isEmpty { break }
tail._initializeAndDropPrefix(copying: src)
dstCount += src.count
}
}
}
}
@available(SwiftStdlib 5.0, *)
extension Span: BorrowingIteratorProtocol where Element: ~Copyable {
@_lifetime(copy self)
@_lifetime(self: copy self)
@inlinable
public mutating func nextSpan(maximumCount: Int) -> Span<Element> {
let result = self.extracting(first: maximumCount)
self = self.extracting(droppingFirst: maximumCount)
return result
}
}
// FIXME: Decide if we want UnsafeBufferPointer types to be borrow iterators
#if false // FIXME: Implement this
@available(SwiftStdlib 5.0, *)
extension MutableSpan: BorrowingIteratorProtocol where Element: ~Copyable {
@_lifetime(copy self)
@_lifetime(self: copy self)
@inlinable
public mutating func nextSpan(maximumCount: Int) -> Span<Element> {
//???
}
}
#endif
#if false // FIXME: Implement this
@available(SwiftStdlib 5.0, *)
extension OutputSpan: BorrowingIteratorProtocol where Element: ~Copyable {
@_lifetime(copy self)
@_lifetime(self: copy self)
@inlinable
public mutating func nextSpan(maximumCount: Int) -> Span<Element> {
//???
}
}
#endif
#endif
@@ -0,0 +1,336 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@available(SwiftStdlib 5.0, *)
public protocol Container<Element>: BorrowingSequence, ~Copyable, ~Escapable {
associatedtype Index: Comparable
var count: Int { get }
var startIndex: Index { get }
var endIndex: Index { get }
func index(after index: Index) -> Index
func formIndex(after index: inout Index)
func index(_ index: Index, offsetBy n: Int) -> Index
func formIndex(
_ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index
)
func distance(from start: Index, to end: Index) -> Int
/// Return a span over the container's storage that begins with the element at the given index,
/// and extends to the end of the contiguous storage chunk that contains it. On return, the index
/// is updated to address the next item following the end of the returned span.
///
/// This method can be used to efficiently process the items of a container in bulk, by
/// directly iterating over its piecewise contiguous pieces of storage:
///
/// var index = items.startIndex
/// while true {
/// let span = items.nextSpan(after: &index)
/// if span.isEmpty { break }
/// // Process items in `span`
/// }
///
/// Note: The spans returned by this method are not guaranteed to be disjunct. Some containers
/// may use the same storage chunk (or parts of a storage chunk) multiple times, to repeat their
/// contents.
///
/// Note: Repeated invocations of `nextSpan` on the same container and index are not guaranteed
/// to return identical results. (This is particularly the case with containers that can store
/// contents in their "inline" representation. Such containers may not always have
/// a unique address in memory; the locations of the spans exposed by this method may vary
/// between different borrows of the same container.)
///
/// - Parameter index: A valid index in the container, including the end index. On return, this
/// index is advanced by the count of the resulting span, to simplify iteration.
/// - Returns: A span over contiguous storage that starts at the given index. If the input index
/// is the end index, then this returns an empty span. Otherwise the result is non-empty,
/// with its first element matching the element at the input index.
@_lifetime(borrow self)
func nextSpan(after index: inout Index, maximumCount: Int) -> Span<Element>
// subscript(index: Index) -> Element { borrow }
// FIXME: Do we want these as standard requirements this time?
func index(alignedDown index: Index) -> Index
func index(alignedUp index: Index) -> Index
}
@available(SwiftStdlib 5.0, *)
extension Container where Self: ~Copyable & ~Escapable {
@inlinable
@_lifetime(borrow self)
public func nextSpan(after index: inout Index) -> Span<Element> {
nextSpan(after: &index, maximumCount: Int.max)
}
// @inlinable
// @_lifetime(borrow self)
// public func nextSpan(after index: inout Index, maximumCount: Int) -> Span<Element> {
// let original = index
// var span = nextSpan(after: &index)
// if span.count > maximumCount {
// span = span.extracting(first: maximumCount)
// // Index remains within the same span, so offseting it is expected to be quick
// index = self.index(original, offsetBy: maximumCount)
// }
// return span
// }
}
@available(SwiftStdlib 5.0, *)
extension Container where Self: ~Copyable & ~Escapable {
@inlinable
public func formIndex(after index: inout Index) {
index = self.index(after: index)
}
@inlinable
public func index(_ index: Index, offsetBy n: Int) -> Index {
_defaultIndex(index, advancedBy: n)
}
@inlinable
public func formIndex(
_ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index
) {
_defaultFormIndex(&index, advancedBy: &n, limitedBy: limit)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
_defaultDistance(from: start, to: end)
}
@inlinable
public func index(alignedDown index: Index) -> Index { index }
@inlinable
public func index(alignedUp index: Index) -> Index { index }
}
@available(SwiftStdlib 5.0, *)
extension Container where Self: ~Copyable & ~Escapable {
@inlinable
public func _defaultDistance(from start: Index, to end: Index) -> Int {
// FIXME: Use binary search here (with nextSpan(after:maximumCount:))
var start = index(alignedDown: start)
let end = index(alignedDown: end)
if start > end {
return -_defaultDistance(from: end, to: start)
}
var count = 0
while start != end {
count = count + 1
formIndex(after: &start)
}
return count
}
@inlinable
public func _defaultIndex(_ i: Index, advancedBy distance: Int) -> Index {
precondition(
distance >= 0,
"Only BidirectionalContainers can be advanced by a negative amount")
var i = index(alignedDown: i)
var distance = distance
#if true // with nextSpan(after:maximumCount:)
while distance > 0 {
let span = self.nextSpan(after: &i, maximumCount: distance)
precondition(
!span.isEmpty,
"Can't advance index beyond the end of the container")
distance &-= span.count
}
return i
#else // without nextSpan(after:maximumCount:)
// FIXME: This implementation can be wasteful for contiguous containers,
// as iterating over spans will overshoot the target immediately.
// Reintroducing `nextSpan(after:maximumCount:)` would help avoid
// having to use a second loop to refine the result, but it would
// complicate conformances.
// Skip forward until we find the span that contains our target.
while distance > 0 {
var j = i
let span = self.nextSpan(after: &j)
precondition(
!span.isEmpty,
"Can't advance index beyond the end of the container")
guard span.count <= distance else { break }
i = j
distance &-= span.count
}
// Step through to find the precise target.
while distance > 0 {
self.formIndex(after: &i)
distance &-= 1
}
return i
#endif
}
@inlinable
public func _defaultFormIndex(
_ i: inout Index,
advancedBy distance: inout Int,
limitedBy limit: Index
) {
precondition(
distance >= 0,
"Only BidirectionalContainers can be advanced by a negative amount")
i = index(alignedDown: i)
let limit = index(alignedDown: limit)
if i > limit {
i = self.index(i, offsetBy: distance)
distance = 0
return
}
#if true // with nextSpan(after:maximumCount:)
// Skip forward until find our target or overshoot the limit.
while distance > 0, i < limit {
var j = i
let span = self.nextSpan(after: &j, maximumCount: distance)
precondition(
!span.isEmpty,
"Can't advance index beyond the end of the container")
if j > limit {
break
}
i = j
distance &-= span.count
}
// Step through to find the precise target.
// FIXME: Use binary search here
while distance != 0 {
if i == limit {
return
}
formIndex(after: &i)
distance &-= 1
}
#else // without nextSpan(after:maximumCount:)
// Skip forward until we find the span that contains our target.
while distance > 0 {
var j = i
let span = self.nextSpan(after: &j)
precondition(
!span.isEmpty,
"Can't advance index beyond the end of the container")
guard span.count <= distance, j < limit else {
break
}
i = j
distance &-= span.count
}
// Step through to find the precise target.
while distance != 0 {
if i == limit {
return
}
formIndex(after: &i)
distance &-= 1
}
#endif
}
}
@available(SwiftStdlib 5.0, *)
extension Container where Self: ~Copyable & ~Escapable {
@_transparent
public var estimatedCount: EstimatedCount { .exactly(count) }
}
@available(SwiftStdlib 5.0, *)
public struct ContainerIterator<
Base: Container & ~Copyable /*FIXME: & ~Escapable*/
>: ~Copyable, ~Escapable {
let _base: Borrow<Base> // FIXME: This doesn't support nonescapable Bases
var _position: Base.Index
@_lifetime(borrow base)
init(_borrowing base: borrowing @_addressable Base, from position: Base.Index) {
self._base = Borrow(_borrowing: base)
self._position = position
}
}
@available(SwiftStdlib 5.0, *)
extension ContainerIterator: BorrowingIteratorProtocol
where Base: ~Copyable /*FIXME: & ~Escapable*/
{
public typealias Element = Base.Element
@_unsafeNonescapableResult // FIXME: we cannot convert from a borrow to an inout dependence!
@_lifetime(&self)
public mutating func nextSpan(maximumCount: Int) -> Span<Base.Element> {
_base[].nextSpan(after: &self._position, maximumCount: maximumCount)
}
}
@available(SwiftStdlib 5.0, *)
extension Container
where
Self: ~Copyable /*FIXME: & ~Escapable*/,
BorrowingIterator == ContainerIterator<Self>
{
@_lifetime(borrow self)
public func makeBorrowingIterator() -> BorrowingIterator {
ContainerIterator(_borrowing: self, from: self.startIndex)
}
}
#endif
extension Strideable {
@inlinable
package mutating func _advance(
by distance: inout Stride, limitedBy limit: Self
) {
if distance >= 0 {
guard limit >= self else {
self = self.advanced(by: distance)
distance = 0
return
}
let d = Swift.min(distance, self.distance(to: limit))
self = self.advanced(by: d)
distance -= d
} else {
guard limit <= self else {
self = self.advanced(by: distance)
distance = 0
return
}
let d = Swift.max(distance, self.distance(to: limit))
self = self.advanced(by: d)
distance -= d
}
}
#if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@inlinable
public mutating func advance(
by distance: inout Stride, limitedBy limit: Self
) {
_advance(by: &distance, limitedBy: limit)
}
#endif
}
@@ -0,0 +1,215 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// A type that supplies the values of an in-place consumable sequence through
/// a series of `InputSpan` instances. This iterator-like construct allows
/// directly consuming elements from some container's storage, in bulk,
/// without requiring them to be moved into any temporary buffer.
///
/// Drains are inherently also producers -- they can produce items by simply
/// moving their consumable contents to the client-supplied series of
/// output spans.
@available(SwiftStdlib 5.0, *)
public protocol Drain<Element>: Producer, ~Copyable, ~Escapable
where ProducerError == Never
{
/// Returns the next span of consumable items in the sequence underlying this
/// drain, of at most the specified maximum count. A `maximumCount` of nil
/// indicates no limit, meaning that the client is able to process an
/// arbitrarily large number of elements.
///
/// Repeatedly calling this method returns, in order, all the elements of the
/// underlying consumable sequence. As soon as the sequence has run out of
/// elements, all subsequent calls return empty spans.
///
/// While the returned input spans exist, they continue to mutate the drain,
/// extending the exclusive access initiated by the call to
/// `drainNext(maximumCount:)`. To call this (or any other) method again, the
/// returned input span needs to be consumed or otherwise destroyed.
///
/// Once this method returns, the contents of the resulting input span are
/// already destined for consumption, either gradually by invoking explicit
/// methods such as `InputSpan.popFirst`, or all at once when
/// the input span is destroyed. There is no way to "put items back" into
/// the consumable sequence, other than by moving them into a
/// temporary location and later reinserting them into the underlying
/// construct through some type-specific operations.
///
/// - Parameter maximumCount: The maximum number of items that the client
/// is prepared to consume, or nil if the client is able to process an
/// arbitrary number of elements. If this is non-nil, then it must be a
/// positive integer.
/// - Returns: An input span of at most the specified maximum count (if any),
/// containing the next elements of the underlying consumable sequence.
/// This method returns an empty span to indicate that it has reached
/// the end of the sequence.
@_lifetime(&self)
@_lifetime(self: copy self)
mutating func drainNext(maximumCount: Int) -> InputSpan<Element>
// TODO: The primary use case does not need this to throw; do we need to allow that?
// Note: making this failable is not entirely straightforward, as there is no
// easy way to signal partial success -- conforming implementations
// would likely need to store errors they encounter midway through a
// chunk and report them at the beginning of the next iteration.
// I take this as an indication that we don't need to do that.
// (Contrast with this `Producer.generate(into:)`; the shape of that method
// allows it to partially populate its client-supplied target and still
// report an error.)
//
// Note: We can also express this with a higher-order shape:
//
// mutating func drainNext<E: Error, R: ~Copyable>(
// _ body: (inout InputSpan<Element>) throws(E) -> R
// ) throws(E) -> R
//
// This would allow partial consumption, eliminating the need for
// `maximumCount`, but at the cost of having to deal with closures --
// it can be tricky to elegantly flow data/control in & out higher-order
// functions. Allowing the function argument to throw also precludes
// the drain itself from throwing, unless they are both required
// to use the same error type, which would be impractical.
}
@available(SwiftStdlib 5.0, *)
extension Drain where Self: ~Copyable & ~Escapable {
/// Returns the next span of consumable items in the sequence underlying this
/// drain, of an arbitrarily large count.
///
/// Repeatedly calling this method returns, in order, all the elements of the
/// underlying consumable sequence. As soon as the sequence has run out of
/// elements, all subsequent calls return empty spans.
///
/// While the returned input spans exist, they continue to mutate the drain,
/// extending the exclusive access initiated by the call to
/// `drain(maximumCount:)`. To call this (or any other) method again, the
/// returned input span needs to be consumed or otherwise destroyed.
///
/// Once this method returns, the contents of the resulting input span are
/// already destined for consumption, either gradually by invoking explicit
/// methods such as `InputSpan.popFirst`, or all at once when
/// the input span is destroyed. There is no way to "put items back" into
/// the consumable sequence, other than by moving them into a
/// temporary location and later reinserting them into the underlying
/// construct through some type-specific operations.
///
/// - Returns: An input span containing the next elements of the underlying
/// consumable sequence. This method returns an empty span to indicate
/// that it has reached the end of the sequence.
@_lifetime(&self)
@_lifetime(self: copy self)
@_transparent
mutating func drainNext() -> InputSpan<Element> {
drainNext(maximumCount: Int.max)
}
/// Generate the next batch of items into the supplied output span instance,
/// which must have room for at least one new element.
///
/// Repeatedly calling this method produces, in order, all the elements of the
/// underlying generative sequence. As soon as the sequence has run out of
/// elements, all subsequent calls return false without appending any new
/// items to their target. This method is not guaranteed to fully populate the
/// given output span, but it always appends at least one item until the end
/// of the underlying generative sequence.
///
/// The ownership of all generated elements is transferred to the caller of
/// this method -- it can arbitrarily store, mutate, consume or discard them
/// as needed, even across invocations of this method, or after the producer
/// is destroyed.
///
/// The returned Boolean value can be used to easily determine if the
/// method was able to make progress towards filling `target` without hitting
/// the end of the underlying sequence.
///
/// ### Error handling
///
/// This method throws an error to indicate a failure while trying to generate
/// the upcoming next item in the sequence. Failure may happen midway through
/// populating `target`, in which case the output span will still gain
/// new items despite the error. (Those items are successfully
/// generated, and do not necessarilly need to be discarded.)
///
/// This protocol does not specify the meaning of a failure, or the
/// precise state of the iterator after an error is thrown; however, the
/// error must not trigger runtime traps in subsequent attempts at iteration.
/// (After a failure, conforming types may choose to produce new items, or
/// signal the end of the iteration, or throw another error, which may or may
/// not match the first.)
///
/// Absent of more specific information, generic code should stop
/// iterating, discard the producer and rethrow the error when it encounters
/// a failure. Generic code is encouraged to preserve the items that got
/// successfully produced before the throw (including ones appended by
/// the call that ultimately ended in failure); however, whether this is
/// possible (or desirable) ultimately depends on the specific problem that
/// the algorithm is solving.
///
/// - Parameter target: An output span ready to take newly generated items.
/// - Returns: A boolean value indicating whether the operation was able to
/// append at least one item to the supplied output span without hitting
/// the end of the underlying sequence.
@inlinable
@_lifetime(target: copy target)
public mutating func generate(
into target: inout OutputSpan<Element>
) throws(Never) -> Bool {
var source = self.drainNext(maximumCount: target.freeCapacity)
if source.isEmpty { return false }
target._append(moving: &source)
return true
}
/// Skip at most the given number items in the underlying generative sequence,
/// decreasing it by the number of items successfully skipped.
///
/// This is equivalent to generating the same number of items then immediately
/// discarding them, except it may avoid the overhead of actually
/// materializing them.
///
/// As soon as the producer has run out of items, all subsequent calls to
/// this method stop decrementing `remainder` and return false.
///
/// The default implementation of this method calls `generate(into:)` with
/// a small temporary buffer, immediately discarding all generated items.
/// Conforming types are encouraged to replace this default approach
/// with a more efficient implementation whenever it is possible to do so.
///
/// ### Error handling
///
/// This method throws an error to indicate a failure while trying to skip
/// the upcoming next item in the sequence. Failure may happen midway through
/// skipping a batch of items, in which case the `remainder` will still be
/// decremented by the number of elements that were successfully skipped
/// before encountering the problem.
///
/// - Parameter remainder: The maximum number of items remaining to skip.
/// This method decrements this value by the number of items it
/// successfully skipped before returning.
/// - Returns: A boolean value indicating whether the operation was able to
/// satisfy the request at least partially without hitting the end of the
/// underlying consumable sequence.
@inlinable
@_lifetime(self: copy self)
public mutating func skip(
upTo n: inout Int
) throws(ProducerError) -> Bool {
precondition(n >= 0, "Can't skip a negative number of elements")
guard n > 0 else { return true }
let span = drainNext(maximumCount: n)
let success = span.count > 0
n &-= span.count
return success
}
}
#endif
@@ -0,0 +1,98 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2025 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 compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@available(SwiftStdlib 5.0, *)
extension Span: BorrowingSequence where Element: ~Copyable {
// FIXME: This simple definition cannot also be a backward (or bidirectional)
// iterator, nor a random-access iterator. If we want to go in that direction,
// we'll need to rather introduce a type more like `RigidArray.BorrowingIterator`.
public typealias BorrowingIterator = Self
@inlinable
public var estimatedCount: EstimatedCount {
.exactly(count)
}
@_lifetime(copy self)
@inlinable
public func makeBorrowingIterator() -> Span<Element> {
self
}
}
@available(SwiftStdlib 5.0, *)
extension MutableSpan: BorrowingSequence where Element: ~Copyable {
public typealias BorrowingIterator = Span<Element>.BorrowingIterator
@inlinable
public var estimatedCount: EstimatedCount {
.exactly(count)
}
@_lifetime(borrow self)
@inlinable
public func makeBorrowingIterator() -> Span<Element> {
self.span
}
}
@available(SwiftStdlib 5.0, *)
extension OutputSpan: BorrowingSequence where Element: ~Copyable {
public typealias BorrowingIterator = Span<Element>.BorrowingIterator
@inlinable
public var estimatedCount: EstimatedCount {
.exactly(count)
}
@_lifetime(borrow self)
@inlinable
public func makeBorrowingIterator() -> Span<Element> {
self.span
}
}
@available(SwiftStdlib 5.0, *)
extension InputSpan: BorrowingSequence where Element: ~Copyable {
public typealias BorrowingIterator = Span<Element>.BorrowingIterator
@inlinable
public var estimatedCount: EstimatedCount {
.exactly(count)
}
@_lifetime(borrow self)
@inlinable
public func makeBorrowingIterator() -> Span<Element> {
self.span
}
}
@available(SwiftStdlib 6.2, *)
extension Array: BorrowingSequence {
public typealias BorrowingIterator = Span<Element>.BorrowingIterator
@inlinable
public var estimatedCount: EstimatedCount {
.exactly(count)
}
@_lifetime(borrow self)
@inlinable
public func makeBorrowingIterator() -> Span<Element> {
self.span
}
}
#endif
@@ -0,0 +1,279 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2024 - 2025 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 InternalCollectionsUtilities
#endif
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
@available(SwiftStdlib 5.0, *)
extension BorrowingSequence where Self: ~Copyable & ~Escapable, Element: Copyable {
@inlinable
package func _copyContents(
intoPrefixOf buffer: UnsafeMutableBufferPointer<Element>
) -> Int {
var target = buffer
var it = self.makeBorrowingIterator()
while target.count != 0 {
let span = it.nextSpan(maximumCount: target.count)
if span.isEmpty {
return buffer.count - target.count
}
target._initializeAndDropPrefix(copying: span)
}
let test = it.nextSpan()
precondition(test.isEmpty, "Contents do not fit in target buffer")
return buffer.count
}
}
#if true
@available(SwiftStdlib 5.0, *)
extension BorrowingSequence where Self: ~Copyable & ~Escapable {
@inlinable
public func elementsEqual<
Other: BorrowingSequence<Element> & ~Copyable & ~Escapable
>(
_ other: borrowing Other,
) -> Bool where Element: Equatable {
switch (self.estimatedCount, other.estimatedCount) {
case let (.exactly(a), .exactly(b)):
guard a == b else { return false }
default:
break
}
var it1 = self.makeBorrowingIterator()
var it2 = other.makeBorrowingIterator()
while true {
let a = it1.nextSpan()
var i = 0
if a.isEmpty {
return it2.nextSpan().isEmpty
}
while i < a.count {
let b = it2.nextSpan(maximumCount: a.count)
if b.isEmpty {
return false
}
precondition(b.count <= a.count - i)
var j = 0
while j < b.count {
guard a[unchecked: i] == b[unchecked: j] else { return false }
i &+= 1
j &+= 1
}
}
}
}
}
@available(SwiftStdlib 5.0, *)
extension BorrowingSequence where Self: ~Copyable & ~Escapable {
/// Returns a Boolean value indicating whether two borrowing sequences contain
/// equivalent elements in the same order, using the given predicate as the
/// equivalence test.
///
/// The predicate must form an *equivalence relation* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
///
/// - Parameters:
/// - other: A BorrowingSequence to compare to this BorrowingSequence.
/// - areEquivalent: A predicate that returns `true` if its two arguments
/// are equivalent; otherwise, `false`.
/// - Returns: `true` if this BorrowingSequence and `other` contain equivalent items,
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
///
/// - Complexity: O(*m*), where *m* is the count of the longer of the input sequences.
@inlinable
public func elementsEqual<
E: Error,
Other: BorrowingSequence & ~Copyable & ~Escapable
>(
_ other: borrowing Other,
by areEquivalent: (borrowing Element, borrowing Other.Element) throws(E) -> Bool
) throws(E) -> Bool {
switch (self.estimatedCount, other.estimatedCount) {
case let (.exactly(a), .exactly(b)):
guard a == b else { return false }
default:
break
}
var it1 = self.makeBorrowingIterator()
var it2 = other.makeBorrowingIterator()
while true {
let a = it1.nextSpan()
var i = 0
if a.isEmpty {
return it2.nextSpan().isEmpty
}
while i < a.count {
let b = it2.nextSpan(maximumCount: a.count)
if b.isEmpty {
return false
}
precondition(b.count <= a.count - i)
var j = 0
while j < b.count {
guard try areEquivalent(a[unchecked: i], b[unchecked: j]) else {
return false
}
i &+= 1
j &+= 1
}
}
}
}
}
#else // rdar://150228920
@available(SwiftStdlib 5.0, *)
extension BorrowingSequence where Self: ~Copyable & ~Escapable {
@inlinable
public func elementsEqual<
Other: BorrowingSequence<Element> & ~Copyable & ~Escapable
>(
_ other: borrowing Other,
) -> Bool where Element: Equatable {
var it1 = self.makeBorrowingIterator()
var it2 = other.makeBorrowingIterator()
var a = Span<Element>()
var b = Span<Element>()
loop:
while true {
if a.isEmpty {
a = it1.nextSpan()
}
if b.isEmpty {
b = it2.nextSpan()
}
if a.isEmpty || b.isEmpty {
return a.isEmpty && b.isEmpty
}
let c = Swift.min(a.count, b.count)
var i = 0
while i < c {
guard a[unchecked: i] == b[unchecked: i] else { return false }
i &+= 1
}
a = a.extracting(droppingFirst: c)
b = b.extracting(droppingFirst: c)
}
}
}
@available(SwiftStdlib 5.0, *)
extension BorrowingSequence where Self: ~Copyable & ~Escapable {
@inlinable
@discardableResult
internal func _spanwiseZip<
Other: BorrowingSequence & ~Copyable & ~Escapable,
State: ~Copyable, E: Error
>(
state: inout State,
with other: borrowing Other,
by process: (inout State, Span<Element>, Span<Other.Element>) throws(E) -> Bool
) throws(E) -> Int {
var it1 = self.makeBorrowingIterator()
var it2 = other.makeBorrowingIterator()
var a = Span<Element>()
var b = Span<Other.Element>()
var offset = 0 // Offset of the start of the current spans
loop:
while true {
if a.isEmpty {
a = it1.nextSpan()
}
if b.isEmpty {
b = it2.nextSpan()
}
if a.isEmpty || b.isEmpty {
return offset
}
let c = Swift.min(a.count, b.count)
guard try process(&state, a.extracting(first: c), b.extracting(first: c)) else {
return offset
}
a = a.extracting(droppingFirst: c)
b = b.extracting(droppingFirst: c)
offset += c
}
}
/// Returns a Boolean value indicating whether this BorrowingSequence and another
/// BorrowingSequence contain equivalent elements in the same order, using the given
/// predicate as the equivalence test.
///
/// The predicate must form an *equivalence relation* over the elements. That
/// is, for any elements `a`, `b`, and `c`, the following conditions must
/// hold:
///
/// - `areEquivalent(a, a)` is always `true`. (Reflexivity)
/// - `areEquivalent(a, b)` implies `areEquivalent(b, a)`. (Symmetry)
/// - If `areEquivalent(a, b)` and `areEquivalent(b, c)` are both `true`, then
/// `areEquivalent(a, c)` is also `true`. (Transitivity)
///
/// - Parameters:
/// - other: A BorrowingSequence to compare to this BorrowingSequence.
/// - areEquivalent: A predicate that returns `true` if its two arguments
/// are equivalent; otherwise, `false`.
/// - Returns: `true` if this BorrowingSequence and `other` contain equivalent items,
/// using `areEquivalent` as the equivalence test; otherwise, `false.`
///
/// - Complexity: O(*m*), where *m* is the count of the longer of the input sequences.
@inlinable
public func elementsEqual<
E: Error,
Other: BorrowingSequence & ~Copyable & ~Escapable
>(
_ other: borrowing Other,
by areEquivalent: (borrowing Element, borrowing Other.Element) throws(E) -> Bool
) throws(E) -> Bool {
guard self.count == other.count else { return false }
var result = true
try _spanwiseZip(state: &result, with: other) { state, a, b throws(E) in
assert(a.count == b.count)
for i in a.indices {
guard try areEquivalent(a[i], b[i]) else {
state = false
return false
}
}
return true
}
return result
}
}
@available(SwiftStdlib 5.0, *)
extension BorrowingSequence where Self: ~Copyable & ~Escapable, Element: Equatable {
@inlinable
public func elementsEqual<
Other: BorrowingSequence<Element> & ~Copyable & ~Escapable
>(
_ other: borrowing Other,
) -> Bool {
self.elementsEqual(other, by: ==)
}
}
#endif
#endif
@@ -0,0 +1,139 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
public enum EstimatedCount {
case infinite
case exactly(Int)
case unknown
}
@available(SwiftStdlib 5.0, *)
public protocol BorrowingSequence<Element>: ~Copyable, ~Escapable {
associatedtype Element: ~Copyable
associatedtype BorrowingIterator: BorrowingIteratorProtocol<Element> & ~Copyable & ~Escapable
var isEmpty: Bool { get }
var estimatedCount: EstimatedCount { get }
@_lifetime(borrow self)
borrowing func makeBorrowingIterator() -> BorrowingIterator
func _customContainsEquatableElement(
_ element: borrowing Element
) -> Bool?
}
@available(SwiftStdlib 5.0, *)
extension BorrowingSequence where Self: ~Copyable & ~Escapable {
@inlinable
public var underestimatedCount: Int {
switch estimatedCount {
case .infinite:
Int.max
case .exactly(let c):
c
case .unknown:
0
}
}
@inlinable
public func _customContainsEquatableElement(_ element: borrowing Element) -> Bool? {
nil
}
}
@available(SwiftStdlib 5.0, *)
extension BorrowingSequence where Self: Sequence {
@inlinable
public func _customContainsEquatableElement(_ element: borrowing Element) -> Bool? {
nil
}
}
@available(SwiftStdlib 5.0, *)
extension BorrowingSequence where Element: Copyable {
// FIXME: How do we expect this to work for ~Copyable elements?
public var first: Element? {
var it = makeBorrowingIterator()
let span = it.nextSpan(maximumCount: 1)
guard !span.isEmpty else { return nil }
return span[0]
}
}
@available(SwiftStdlib 5.0, *)
extension BorrowingSequence where Self: ~Copyable & ~Escapable {
/// Implementation demo of what borrowing for-in loops would need to expand into.
@inlinable
public func _borrowingForEach<E: Error>(
_ body: (borrowing Element) throws(E) -> Void
) throws(E) -> Void {
var it = makeBorrowingIterator()
while true {
let span = it.nextSpan()
if span.isEmpty { break }
var i = 0
while i < span.count {
try body(span[unchecked: i])
i &+= 1
}
}
}
}
@available(SwiftStdlib 5.0, *)
extension BorrowingSequence where Self: ~Copyable & ~Escapable {
@inlinable
public func borrowingReduce<Result: ~Copyable, E: Error>(
into initial: consuming Result,
_ update: (inout Result, borrowing Self.Element) throws(E) -> ()
) throws(E) -> Result {
var result = initial
try self._borrowingForEach { item throws(E) in
try update(&result, item)
}
return result
}
@inlinable
public func borrowingReduce<Result: ~Copyable, E: Error>(
_ initial: consuming Result,
_ next: (consuming Result, borrowing Self.Element) throws(E) -> Result
) throws(E) -> Result {
var result = initial
#if false // FIXME: missing reinitialization of closure capture 'result' after consume
try self._borrowingForEach { item throws(E) in
result = try next(result, item)
}
#else
var it = makeBorrowingIterator()
while true {
let span = it.nextSpan()
if span.isEmpty { break }
var i = 0
while i < span.count {
result = try next(result, span[unchecked: i])
i &+= 1
}
}
#endif
return result
}
}
#endif
@@ -0,0 +1,268 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW
/// A type that supplies the values of a generative sequence by populating
/// a client-supplied series of `OutputSpan` instances. "Generative" sequences
/// transfer the ownership of items they produce to their clients, rather than
/// merely providing borrowing access to them. A `Producer` instance represents
/// an ongoing iteration over such a generative sequence.
@available(SwiftStdlib 5.0, *)
public protocol Producer<Element>: ~Copyable, ~Escapable {
/// The type of the items that this producer generates.
associatedtype Element: ~Copyable
/// The error that this producer may throw, or `Never` if this producer
/// always succeeds.
associatedtype ProducerError: Error = Never
/// A value less than or equal to the number of remaining items that this
/// producer is able to generate until it reaches its end.
///
/// The default implementation returns 0. If you provide your own
/// implementation, make sure to compute the value nondestructively.
var underestimatedCount: Int { get }
/// Generate the next batch of items into the supplied output span instance,
/// which must have room for at least one new element.
///
/// Repeatedly calling this method produces, in order, all the elements of the
/// underlying generative sequence. As soon as the sequence has run out of
/// elements, all subsequent calls return false without appending any new
/// items to their target. This method is not guaranteed to fully populate the
/// given output span, but it always appends at least one item until the end
/// of the underlying generative sequence.
///
/// The ownership of all generated elements is transferred to the caller of
/// this method -- it can arbitrarily store, mutate, consume or discard them
/// as needed, even across invocations of this method, or after the producer
/// is destroyed.
///
/// The returned Boolean value can be used to easily determine if the
/// method was able to make progress towards filling `target` without hitting
/// the end of the underlying sequence.
///
/// If `target` is a full span, this method is allowed to unconditionally
/// return true. Passing an empty span is not a reliable way to test if the
/// producer has reached its end. (Some producers may only be able to detect
/// that they are finished while trying to generate the next item.)
///
/// ### Error handling
///
/// This method throws an error to indicate a failure while trying to generate
/// the upcoming next item in the sequence. Failure may happen midway through
/// populating `target`, in which case the output span will still gain
/// new items despite the error. (Those items are successfully
/// generated, and do not necessarilly need to be discarded.)
///
/// This protocol does not specify the meaning of a failure, or the
/// precise state of the iterator after an error is thrown; however, the
/// error must not trigger runtime traps in subsequent attempts at iteration.
/// (After a failure, conforming types may choose to produce new items, or
/// signal the end of the iteration, or throw another error, which may or may
/// not match the first.)
///
/// Absent of more specific information, generic code should stop
/// iterating, discard the producer and rethrow the error when it encounters
/// a failure. Generic code is encouraged to preserve the items that got
/// successfully produced before the throw (including ones appended by
/// the call that ultimately ended in failure); however, whether this is
/// possible (or desirable) ultimately depends on the specific problem that
/// the algorithm is solving.
///
/// - Parameter target: An output span ready to take newly generated items.
/// - Returns: A boolean value indicating whether the operation was able to
/// append at least one item to the supplied output span without hitting
/// the end of the underlying sequence.
@_lifetime(target: copy target)
@_lifetime(self: copy self)
@discardableResult
mutating func generate(
into target: inout OutputSpan<Element>
) throws(ProducerError) -> Bool
/// Skip at most the given number items in the underlying generative sequence,
/// decreasing it by the number of items successfully skipped.
///
/// This is equivalent to generating the same number of items then immediately
/// discarding them, except it may avoid the overhead of actually
/// materializing them.
///
/// As soon as the producer has run out of items, all subsequent calls to
/// this method stop decrementing `n` and return false.
///
/// The default implementation of this method calls `generate(into:)` with
/// a small temporary buffer, immediately discarding all generated items.
/// Conforming types are encouraged to replace this default approach
/// with a more efficient implementation whenever it is possible to do so.
///
/// ### Error handling
///
/// This method throws an error to indicate a failure while trying to skip
/// the upcoming next item in the sequence. Failure may happen midway through
/// skipping a batch of items, in which case `n` will still be
/// decremented by the number of elements that were successfully skipped
/// before encountering the problem.
///
/// - Parameter n: The maximum number of items remaining to skip. This
/// must be greater than zero. This method decrements this value by the
/// number of items it successfully skipped before returning.
/// - Returns: A boolean value indicating whether the operation was able to
/// skip at least one item without hitting the end of the underlying
/// sequence.
@_lifetime(self: copy self)
mutating func skip(upTo n: inout Int) throws(ProducerError) -> Bool
/// Generate and return the next element in the underlying generative
/// sequence.
///
/// Repeatedly calling this method produces, in order, all the elements of the
/// underlying generative sequence. As soon as the sequence has run out of
/// elements, all subsequent calls return `nil`.
///
/// The ownership of all generated elements is transferred to the
/// caller of this method -- it can arbitrarily store, mutate,
/// consume or discard them as needed, even across invocations of this method,
/// or after the producer is destroyed.
///
/// This method throws an error to indicate a failure. This protocol does not
/// specify the meaning of such errors, or the precise state of the
/// iterator after an error is thrown; however, the error must not trigger
/// runtime traps in subsequent attempts at iteration.
/// (Conforming types may choose to produce new items, or signal the end of
/// the iteration, or throw another error, which may or may not match the
/// first.) Absent of more specific information, generic code should stop
/// iterating, discard the producer and rethrow the error when it encounters
/// a failure.
///
/// The default implementation of this method calls `generate(into:)` with
/// a temporary output span with room for a single item, and returns the
/// resulting contents. This often produces satisfactory results; but the
/// protocol allows conformances to customize this entry point if they believe
/// it to be necessary (for example, if they can take shortcuts that aren't
/// available in the bulk method). Custom implementations of `generateNext()`
/// must produce results that are indistinguishable from the default
/// implementation, but they may exhibit observably different performance
/// metrics.
@_lifetime(self: copy self)
mutating func generateNext() throws(ProducerError) -> Element?
}
@available(SwiftStdlib 5.0, *)
extension Producer where Self: ~Copyable & ~Escapable {
/// A value less than or equal to the number of remaining items that this
/// producer is able to generate until it reaches its end.
///
/// The default implementation returns 0. If you provide your own
/// implementation, make sure to compute the value nondestructively.
@inline(__always)
public var underestimatedCount: Int { 0 }
/// Skip at most the given number items in the underlying generative sequence,
/// decreasing it by the number of items successfully skipped.
///
/// This is equivalent to generating the same number of items then immediately
/// discarding them, except it may avoid the overhead of actually
/// materializing them.
///
/// As soon as the producer has run out of items, all subsequent calls to
/// this method stop decrementing `n` and return false.
///
/// The default implementation of this method calls `generate(into:)` with
/// a small temporary buffer, immediately discarding all generated items.
/// Conforming types are encouraged to replace this default approach
/// with a more efficient implementation whenever it is possible to do so.
///
/// ### Error handling
///
/// This method throws an error to indicate a failure while trying to skip
/// the upcoming next item in the sequence. Failure may happen midway through
/// skipping a batch of items, in which case `n` will still be
/// decremented by the number of elements that were successfully skipped
/// before encountering the problem.
///
/// - Parameter n: The maximum number of items remaining to skip. This
/// must be greater than zero. This method decrements this value by the
/// number of items it successfully skipped before returning.
/// - Returns: A boolean value indicating whether the operation was able to
/// skip at least one item without hitting the end of the underlying
/// sequence.
@_lifetime(self: copy self)
mutating func skip(upTo n: inout Int) throws(ProducerError) -> Bool {
precondition(n > 0, "Can't skip less than 1 item")
let maxBufferSize = 8
return try withTemporaryOutputSpan(
of: Element.self, capacity: Swift.min(maxBufferSize, n)
) { span throws(ProducerError) in
defer { n &-= span.count }
return try self.generate(into: &span)
}
}
/// Generate and return the next element in the underlying generative
/// sequence.
///
/// Repeatedly calling this method produces, in order, all the elements of the
/// underlying generative sequence. As soon as the sequence has run out of
/// elements, all subsequent calls return `nil`.
///
/// The ownership of all generated elements is transferred to the
/// caller of this method -- it can arbitrarily store, mutate,
/// consume or discard them as needed, even across invocations of this method,
/// or after the producer is destroyed.
///
/// This method throws an error to indicate a failure. This protocol does not
/// specify the meaning of such errors, or the precise state of the
/// iterator after an error is thrown; however, the error must not trigger
/// runtime traps in subsequent attempts at iteration.
/// (Conforming types may choose to produce new items, or signal the end of
/// the iteration, or throw another error, which may or may not match the
/// first.) Absent of more specific information, generic code should stop
/// iterating, discard the producer and rethrow the error when it encounters
/// a failure.
///
/// The default implementation of this method calls `generate(into:)` with
/// a temporary output span with room for a single item, and returns the
/// resulting contents. This often produces satisfactory results; but the
/// protocol allows conformances to customize this entry point if they believe
/// it to be necessary (for example, if they can take shortcuts that aren't
/// available in the bulk method). Custom implementations of `generateNext()`
/// must produce results that are indistinguishable from the default
/// implementation, but they may exhibit observably different performance
/// metrics.
@inlinable
@_lifetime(self: copy self)
public mutating func generateNext() throws(ProducerError) -> Element? {
try withUnsafeTemporaryAllocation(
of: Element.self, capacity: 1
) { buffer throws(ProducerError) in
var span = OutputSpan(buffer: buffer, initializedCount: 0)
guard try self.generate(into: &span) else { return nil }
return span.removeLast()
}
}
}
@available(SwiftStdlib 5.0, *)
extension Producer where Self: ~Copyable & ~Escapable {
/// Returns true if the producer has no more elements, consuming it in
/// the process. This is implemented by checking if it is possible to
/// skip one item.
///
/// This is useful in preconditions.
public consuming func _isAtEnd() throws(ProducerError) -> Bool {
var c = 1
return try !skip(upTo: &c)
}
}
#endif