+```
+
+`Span` is a small, frozen type in the Swift Standard Library, eminently amenable to optimizations -- efficiently traversing the elements of a span is a drastically simpler problem than iterating over an arbitrary sequence. `Iterable` forces conforming types to factor iteration into two distinct layers: clients still invoke custom code to retrieve the next batch of items, but once they have them, accessing the individual elements within each batch becomes dependably cheap.
+
+For iterables that physically store their contents in memory, implementing iteration simply requires exposing spans over their preexisting piecewise contiguous storage chunks -- the bigger the chunks, the more efficient iteration becomes, even if `nextSpan`'s implementation isn't visible to the optimizer.
+
+Click to expand footnote
+
+> Of course, it was always possible to factor the implementation of iterators this way, by splitting `next()` into two layers, with judicious use of `@inlinable` or even `@inline(always)` attributes to encourage better performance while we're iterating within a storage chunk. However, this required a deep understanding of the underlying issues, and a large amount of willpower to structure the implementation the right way: this meant that only a select handful of types made an effort, and clients couldn't depend on it.
+>
+> `Iterable` forces all conforming types to organize their implementation around this idea, drastically improving clients' ability to reason about performance costs, even in generic contexts.
+
+
+
+Bulk iteration is not without drawbacks: it comes with a drastically more complicated interface, increasing the mental load of authoring conforming types, and of solving problems using the protocol.
+
+To understand how `Iterable` works, we need to learn about what `Span` is, which requires us to also learn at least a little about nonescapable types. We need to figure out how to resolve a whole new class of compiler errors, and ultimately we need to get comfortable reading lifetime dependency declarations, to allow us to predict what operations we can express and architect our solutions without running into constant issues.
+
+Operations for bulk iteration are full of subtle design complications that often don't seem particularly important, but dismissing them can render the abstraction impossible to use in some contexts. For instance, `nextSpan`'s `maxCount` parameter is there to allow clients to limit the number of elements they receive at a time. Having to accommodate this limit is a significant complication for conforming types, so it is tempting to cut the complexity by force-feeding clients an arbitrary number of items. (After all, clients often set `maxCount` to `Int.max` anyway, and don't mind having to potentially deal with millions of items at a time.)
+
+However, consider a client that just wants to look at the first three elements to make a decision about what to do with the rest. Giving this caller four thousand items would put them in an awkward position: they would need to stash the leftovers somewhere, and then process them all before pulling on the iterator again. The spans that `nextSpan` returns are tied to an exclusive access of the iterator, which (currently at least) makes it impossible to actually store them alongside the iterator in any meaningful way: these clients would be drowned in a sea of elements they cannot process. By simplifying conforming implementations, we would significantly limit the usefulness of the protocol.
+
+Click to expand footnote
+
+> Throwing away the iterator and restarting it may seem like a possible workaround, but as `Iterable` types aren't required to produce the same items on repeated iterations, this cannot be a general solution. It only works on some iterable types, such as the containers we are introducing in this document.
+
+
+
+How bulk operations report/handle failures is a similarly subtle but important complication: operations that need to throw errors must be able to properly report partial success, to avoid data loss and to allow clients to identify precisely which element triggered the error. If the fifth element of an `Iterable` instance happens to trigger an error, it still needs to be possible for clients to reliably access the first four elements -- no matter what value they use for `maxCount`.
+
+In this document, we consider this added conceptual complexity a reasonable cost of improving the predictability of Swift performance. We're fully embracing bulk iteration across the full spectrum of container operations. Each flavor of iteration will be primarily built around one of the standard span types: `Span`, `MutableSpan`, `OutputSpan` and `InputSpan`.
+
+### "Iteration by Borrowing" vs "Iteration by Taking"
+
+Code iterating over a `Sequence` gains full ownership of the items it accesses. It can arbitrarily decide to store some of them for later processing, and arbitrarily mutate or discard them as it wishes. `Sequence` relinquishes all control over the elements it exposes, as an inherent part of its design. Because its elements are (implicitly) required to be copyable, this places no real restrictions on the kinds of types that can conform to `Sequence`. Conforming types are not _actually_ required to relinquish control over any of the items they contain just because someone is iterating over them: they can simply return copies of each element while also holding on to their "original" copy.
+
+In contrast, `Iterable` was designed to support noncopyable elements, which do not allow such simple workarounds. Returning a noncopyable instance means transferring unique ownership of it. For container types, this would be a destructive operation, as the contents would have to be physically moved out of the container, emptying it out or entirely consuming it in the process. This would not be workable as the default form of iteration: we naturally expect to be able to iterate over a container multiple times without destroying it in the process.
+
+To avoid this, `Iterable` instead chooses to return _borrowing references_ to the elements it traverses, not the elements themselves. Clients do not get ownership over the items they access -- they get a temporary window that they can peer through to see a batch of items at a time; but they don't get to break the glass (to modify or consume the items), and once the window moves to the next batch, they lose sight of all previously seen items.
+
+In this document, we'll call the ownership model of `Iterable` **iteration by borrowing**, as clients _borrow_ the elements they traverse. The other way to gain access to something is to _take_ ownership of it -- hence, we'll call the model `Sequence` follows **iteration by taking**.
+
+Click to expand footnote
+
+> People have sometimes referred to "iteration by taking elements" as "consuming iteration". Unfortunately, this is routinely misunderstood to mean that the sequence itself gets consumed, rather than its elements, and that makes it an actively confusing term. "Iteration by taking" is meant to describe what the client does to the _elements_, not what happens to the source of the iteration.
+
+
+
+Of course, the way `Iterable` only provides read-only, borrowing access to its elements severely limits what clients can do with them. Obviously, we will also need to provide iterator-like constructs that transfer ownership of their elements to the caller, so that it can collect them into a container type, or otherwise mutate/consume them as it wishes. In this document, we are modeling the idea of "iterating by taking elements" with protocol [`Producer`](#producers).
+
+A variant of the `Iterable` approach is one where instead of borrowing references, we provide mutable references to elements -- we change the unit of iteration from `Span` to `MutableSpan` (or change `Ref` to `MutableRef`). The source of the elements still retains ownership in this case, but clients are allowed to arbitrarily mutate or even replace them. In this document, we are modeling this approach with `MutableContainer`; we are not introducing an `Iterable`-style, generative protocol.
+
+### "Generative" vs "Visitative Iteration"
+
+`Sequence` and `Iterable` both allow their elements to be generated on the fly. We'll be calling this style of traversal **generative iteration**. This allows a wide spectrum of conforming types, but it complicates performance analysis, as the variable cost of on-demand generation inherently adds a difficult term to the complexity of element access.
+
+Additionally, generative iteration by _borrowing_ (as implemented by `Iterable`) has the crucial limitation that the client cannot hold on to generated items as they come out of the iterator -- it is only able to see a single batch of them at a time, and the minute it advances the iterator, it loses sight of all the items it previously encountered. Because `Iterable` allows elements to be generated (and discarded!) on the fly, clients must destroy all references to the elements they see before they can advance to the next batch. This strictly limits the kinds of algorithms we can implement over `Iterable`: in particular, we cannot define lookup or search algorithms that need to return references to specific elements (such as `min()` or `first(where:)`), unless we require `Element` to be copyable. The elements we want to reference may evaporate the moment we advance the iterator!
+
+Not all iterable types need to generate their items on demand. In particular, many of the most useful data structures physically hold their contents in memory, and they can implement iteration by simply locating their storage chunks and directly exposing spans over them. Arrays, linked lists, hashed sets, hashed dictionaries, ring buffers, search trees, ropes are all examples of such data structures, and of course there are many more.
+
+Data structures with preexisting storage form a highly useful subset of iterables, and it is worth giving them a name; we'll call such types **containers**, and the traversal they support **visitative iteration**. These terms emphasize that iterating over a container merely visits its preexisting contents, rather than materializing them on the fly. Locating items in preexisting storage is a far simpler task than generating them; and clients can safely extract and work with references to such items as long as they do not mutate the instance that contains them.
+
+Not all data structures are containers in this sense, of course. For example, Swift's standard `String` type is a sequence of `Character` instances, but those instances are not directly stored anywhere in `String`'s storage representation -- they need to be created on the fly, as we iterate over the string instance. `String` therefore implements _generative_ rather than _visitative_ iteration; it is not a container type. (Of course, it would be possible to build a container of text data; but to do it efficiently, we'd likely need to avoid using `Character`-style grapheme clusters as its `Element`.)
+
+### Failability
+
+The final design aspect we need to consider is failability: whether we need to allow traversable constructs to throw errors.
+
+The classic `Sequence` protocol provides no way for conforming types to signal a failure, other than by trapping or by stopping the iteration earlier than expected. For many developers, this feels like a defect -- `Sequence` allows (or even encourages) conforming types to produce their elements by running arbitrarily complex calculations; and of course those calculations can sometimes legitimately encounter non-fatal problems. The inability to properly signal failure leads to awkward workarounds.
+
+Using the terminology established in the previous section, the ability to fail is therefore a natural expectation for _generative_ constructs.
+
+The `Iterable` protocol addresses this by defining a `Failure` associated type and providing a throwing `nextSpan` method on its iterator. It relies on [typed throws][TypedThrows] so that conforming types that never need to throw can set `Never` as their failure type, enabling clients to avoid writing error handling code that deals with errors that are guaranteed never to happen.
+
+This potentially allows lazy `Iterable` algorithms (like `filter`) to take throwing closures, and cleanly propagate errors to clients. In exchange, failability greatly complicates the bulk iteration model, as operations need to be able to [properly report partial success](#bulk-failures).
+
+Click to expand footnote
+
+> However, we also expect a filter predicate to be able to throw a _different_ error type than the `Iterable`'s own `Failure`. We currently lack the means to express that, as the `nextSpan` method would need to be able to throw either error. We need to do further language-level work -- such as union error types -- to allow us to express such abstractions in a satisfying way.
+
+
+
+On the other hand, the ability to fail is far less important for _visitative_ constructs, like `Container` -- if the items we're visiting already exist in memory at the start of the iteration, there is little reason to take on the complexity of throwing. Therefore, our two visitative protocols (`Container` and `Drain`) do not allow throwing.
+
+This greatly simplifies the container model, but it does mean that throwing algorithms like our hypothetical lazy `filter` can only produce `Iterable` types -- they cannot return containers, even if their input is one.
+
+Click to expand footnote
+
+> Some readers may note a problem with the assumption that accessing storage held in memory cannot possibly fail. While it is true that accessing memory can trigger faults (e.g., consider `mmap`ped regions), we lack the means to turn these faults into recoverable errors in Swift, and it seems unlikely it would be actually desirable to design container protocols around a hypothetical future language direction like that. The pragmatic choice is to assume that container types are stored in memory allocated using Swift's dedicated heap allocation primitives, and access to them can never fail without crashing the entire process (or at least bringing down an isolated subsystem within it).
+
+
+
+Let us now introduce the actual protocols, starting with `Container` itself.
+
+## Read-Only Container Model
+
+Protocol `Container` is our ownership-aware analogue of `Collection`. It defines the abstract shape of a container type that physically holds its contents in memory, and makes them directly accessible to clients.
+
+The contents of a container can be traversed multiple times, nondestructively. The same container must exhibit identical contents across repeated traversals. Clients must be able to form references to container contents that aren't tied to a specific iteration state, only the container itself. This allows Swift functions to directly return such references to callers, allowing the implementation of a variety of useful container algorithms, including basic search/lookup methods.
+
+Let's start defining the new protocol.
+
+```swift
+protocol Container: Iterable, ~Copyable, ~Escapable
+where
+ Element: ~Copyable,
+ Failure == Never
+{...}
+```
+
+The `Container` protocol refines `Iterable`; `Iterable` algorithms are able to work with container types with no extra effort. However, not all iterable types can be containers. The requirement that a container's elements must preexist in memory rules out all iterables that generate items on demand; using the terms [we established above](#generative-iteration-vs-visitative-iteration), we say that iterables model _generative iteration_, while containers are restricted to _visitative_ semantics.
+
+`Container` requires `Failure` to be set to `Never`: because the contents of a container are required to exist in advance within the container instance, they can always be successfully iterated: there is never a need to throw an error.
+
+Naturally, container types are not required to be copyable, nor escapable. They don't require their elements to be copyable, either. (Support for nonescapable elements is a [highly desirable future direction](#support-for-nonescapable-element-types), but we currently lack the tools to express it.)
+
+### Counting Elements
+
+As containers physically store their elements, they inherently always have a specific count.
+
+```swift
+protocol Container: ... {
+ ...
+ var count: Int { get }
+ ...
+}
+```
+
+Repeated invocations of the `count` property on the same container must return the same value. The returned value must match the number of elements that can be accessed by iterating through the container.
+
+Unlike `Collection`, types conforming to `Container` are **required to produce their `count` in constant complexity**. This reflects the protocol's focus on predictable performance, and avoids a common worry with `Collection`. Conforming to this requirement typically requires container implementations to cache their count in an easily accessible stored property, and incrementally update it every time the container changes its size.
+
+Click to expand footnote
+
+> One consequence of this requirement is that constructs like lazy filter algorithms cannot practically conform to the protocol. However, they can still conform to `Iterable`, and that is in fact good enough for the vast majority of their use cases in practice. Notably, custom on-the-fly filtering is inherently incompatible with the expectation of predictable performance. (After all, the `Container` protocol exists to focus on high-performance use cases; it would be a mistake to dilute this focus until the protocol becomes indistinguishable from `Collection`.)
+>
+> `count` is required to return a finite integer that fits in `Int`. This can be a true limitation, as some containers may have more than `Int.max` elements, despite the protocol's requirement for preexisting storage! The storage requirement does not preclude some containers from linking specific storage chunks multiple times (or simply repeating them), without allocating separate storage for each duplicate run. Such repetitions can cause the count of a container to overflow `Int`'s range, without ever overflowing available memory. While such humongous containers are certainly interesting, we do not consider it crucial to provide dedicated support for them.
+>
+> In the design we are proposing, humongous containers can choose to either only conform to `Iterable`, or to trigger a trap if they are ever asked for their count. Client code often invokes `count` so that it can preallocate storage for related work; obviously that is not going to end well if a container's count exceeds `Int.max`. (And in fact trapping early is much preferable to allowing the operation to inevitably fail midway through some vast computation.)
+>
+> If we wanted to support such containers better, one option would be to have `count` return an optional; another would be to push the property down into a separate `FiniteContainer` protocol. The overwhelming complexity of these options does not feel to be anywhere in proportion to the practical importance of such cases. Which is not to say they don't exist: tree-based ropes in particular (like `Foundation`'s `AttributedString`) can easily grow to humongous sizes, by simply concatenating a rope with itself a few dozen times. However, these are mostly just curiosities; such trees are rarely (if ever) practically useful.
+
+
+
+As a small nod towards infinite/vast containers, `Container` still provides an `isEmpty` property that avoids problems with integer overflow:
+
+```swift
+protocol Container: ... {
+ ...
+ var isEmpty: Bool { get }
+ ...
+}
+```
+
+This comes with a default implementation that simply checks if `count` is zero. (`Collection` defines a default implementation for its `isEmpty` that compares `startIndex` to `endIndex`. Given that `Container` requires its `count` to have O(1) complexity, it is slightly better to define `isEmpty` in terms of it, as it avoids having to materialize two index instances.)
+
+Infinite/vast containers can provide their own `isEmpty` implementation that avoids using `count`, for example, by following `Collection`'s pattern. (They also need to provide a custom implementation for `underestimatedCount`, for the same reason.)
+
+### Container Indices
+
+As `Container` refines `Iterable`, it provides a `BorrowingIterator`, and we can use this iterator to access the elements of a container in batches, starting from its beginning. However, it would be a shame to stop there: `Container` can also provide a more flexible model for element access that acknowledges that its contents survive across iteration steps. To help model this, we introduce a slightly adapted version of `Collection`'s familiar `Index` concept.
+
+```swift
+protocol Container: ... {
+ ...
+ associatedtype Index: Equatable, Hashable
+ ...
+}
+```
+
+Our indices represent abstract positions within containers (just as they do in collections): one useful way to look at them is to say that they're addressing the logical boundaries between neighboring elements, with a "start index" addressing the boundary before the first element, and the "end index" addressing the boundary after the last. A container with five items therefore has six indices, addressing all its various logical positions:
+
+```
+ ┌─────┬─────┬─────┬─────┬─────┐
+ │ A │ B │ C │ D │ E │
+ └─────┴─────┴─────┴─────┴─────┘
+ ↑ ↑ ↑ ↑ ↑ ↑
+ 0 1 2 3 4 5
+ (start) (end)
+```
+
+Equivalently, we can say that each index addresses a specific element, with the end index addressing an imaginary empty slot after the last item in the container.
+
+Over the years, Swift's indices have proven to be extremely successful abstractions. This incarnation preserves them as copyable and escapable types, so that they can be processed without undue friction. Indices are soft references that are allowed to go stale when the underlying container is mutated; therefore, container operations taking indices are still required to carefully validate their inputs to catch misuse. (We could have chosen to replace indices with a nonescapable abstraction that would avoid this; however, in practice we found that direction to be [impractical](#cursors).)
+
+Every one of the standard container types we've introduced so far (from `Span` to `UniqueArray` and beyond) already defines an index that fits this model.
+
+`Container` indices are required to be `Equatable`, but unlike `Collection`, they do not need to be `Comparable`. Linked lists are commonly used in systems programming, and this choice allows some linked list implementations to usefully conform to `Container`. The lack of an inherent ordering does complicate the default implementations of some index operations -- [see below](#distance-from-to).
+
+In exchange, `Container` requires its indices to be `Hashable`. This does not put an undue burden on container implementations, but it does allow indices to be collected in sets or used as dictionary keys, enabling use cases such as dynamic filtering or out-of-band storage of data associated with container elements. (Not guaranteeing hashable indices is an old `Collection`wrinkle.)
+
+To acknowledge our performance goals, **we require that `Container` indices must be compared for equality and hashed with constant complexity**. If a container's index does happen to be `Comparable`, then it is required that `<` has O(1) complexity as well.
+
+Now that we have an `Index` type, we can define all the familiar operations that allow us to navigate within a container:
+
+```swift
+protocol Container: ... {
+ ...
+ 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
+ ...
+}
+```
+
+`startIndex` and `endIndex` work exactly like `Collection`'s corresponding properties, defining the bounds of a half-open range: `endIndex` returns a valid index that addresses the logical empty slot following the container's last element, while `startIndex` addresses the container's first element.
+
+`index(_:offsetBy:)` is the `Container` analogue of `BorrowingIterator`'s `skip(by:)` method. It has slightly different semantics though, as it follows `Collection`'s behavior: `index(_:offsetBy:)` always takes exactly the specified number of steps, and it traps if it runs off the end of the container.
+
+As `Container` models a forward-only container, its `index(_:offsetBy:)` operation requires a nonnegative offset. (We'll shortly introduce a `BidirectionalContainer` refinement that will relax this constraint.)
+
+
+
+As indices aren't required to be `Comparable`, the default implementation of `distance(from:to:)` cannot quickly validate that its `start` argument precedes `end`. To avoid having to run all the way to the end of the container to detect misuse, the algorithm instead iterates forward from both arguments, until it finds the other. This makes the default implementation twice as slow, but it allows it to correctly calculate negative distances. In the common case when `Index` is `Comparable`, we also provide a refined default algorithm that avoids this overhead.
+
+
+
+Notably, we replace `Collection`'s classic `index(_:offsetBy:limitedBy:)` requirement with an improved variant ([first introduced on `UniqueArray`][formIndex-offsetBy-limitedBy]) that reports the number of steps it was unable to take when reaching the limit. This avoids having to figure this out with a separate `distance(from:to:)` invocation, enabling more efficient use of this operation in situations that need this data; for example, it allows easy single-pass offsetting across concatenated containers. `Collection`'s original `index(_:offsetBy:limitedBy:)` operation is still available, as a standard algorithm based on the new requirement.
+
+
+
+The `limit` argument here (and also elsewhere throughout the `Container` interface surface) means a **limiting index**, intended to cause the operation to stop if it encounters the limit during its execution. A limit of this sort only stops the operation if it needs to actively iterate over the corresponding position; a limit that the operation never needs to visit has no effect, whether it happens to address a position before or after the visited range. For example, if we're trying to iterate forward by `n` steps, a limit that's behind the start position has no effect. These specific semantics allow types that cannot provide comparable indices to still correctly conform to the protocol. (For example, linked lists usually cannot determine relative ordering between their indices without actively iterating through the list in linear time, as we've seen with `distance(from:to:)`.)
+
+
+
+[formIndex-offsetBy-limitedBy]: https://github.com/swiftlang/swift/blob/swift-6.4.x-DEVELOPMENT-SNAPSHOT-2026-07-06-a/stdlib/public/core/UniqueArray/UniqueArray%2BContainer.swift#L267-L273
+
+
+### Visitative Iteration
+
+The preferred way to iterate over the contents of a `Container` is to repeatedly invoke its `nextSpan` operation:
+
+```swift
+protocol Container: ... {
+ ...
+ @_lifetime(borrow self)
+ func nextSpan(after index: inout Index) -> Span
+ ...
+}
+```
+
+Like the corresponding iterator method on `Iterable`, this implements [bulk iteration](#elementwise-iteration-vs-bulk-iteration): it gives clients access to a batch of items all at once, allowing them to quickly iterate over the returned `Span` instance without invoking any other `Container` methods.
+
+However, this `nextSpan` function is only allowed to mutate an index, not the container itself. Additionally, the spans returned by `nextSpan` are declared to be scoped to a "borrow" of the container, too. This is the crucial difference from `Iterable`, whose spans extend (and are tied to) a particular mutation of the iterator. This is what causes `Container` to fundamentally require its elements to preexist in memory -- it isn't possible for a `nextSpan` with this signature to materialize items on the fly. Containers are required to implement [visitative iteration](#generative-vs-visitative-iteration).
+
+`Container.nextSpan` returns a `Span` instance that begins with the container's element that the given index addresses, and runs to the end of the container's storage chunk that contains it. On return, the index is updated to address the item following the last element in the returned span. If the input index is the `endIndex`, then the method returns an empty span, and leaves the index as is.
+
+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:
+
+```swift
+ var index = items.startIndex
+ while true {
+ let span = items.nextSpan(after: &index)
+ if span.isEmpty { break }
+ // Process items in `span`
+ }
+ // `index` is now equal to `items.endIndex`
+```
+
+We expect that for-in loops over container types will use this iteration style, to allow clients to form `Ref` instances over the element that's currently visited by the loop.
+
+
+The spans returned by `nextSpan` 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.
+
+Repeated invocations of `nextSpan` on the same container and index are guaranteed to expose identical elements, in the same order, and grouped into spans of consistent counts.
+
+Sometimes we don't want to iterate all the way to the end of a container: for instance, we may just want to look at a specific subrange, or we may need to access a specific number of elements. For these cases, `Container` also provides a delimited variant of `nextSpan`, modeled after `formIndex(_:offsetBy:limitedBy:)`:
+
+```swift
+protocol Container: ... {
+ ...
+ @_lifetime(borrow self)
+ func nextSpan(after index: inout Index, maxCount: Int, limitedBy limit: Index) -> Span
+ ...
+}
+```
+
+
+The `maxCount` argument gives the caller control over the number of items it receives from the iterator, while `limit` allows the caller to request that the result never step over a specific index. These parameters let callers avoid overrunning their target, which would significantly complicate container use.
+
+Not all containers are contiguous, so `maxCount` only sets an upper bound. To read a specific number of items, the caller usually needs to invoke `nextSpan` in a loop:
+
+```swift
+var items: some Container
+var index = items.startIndex
+var remainder = numberOfItemsToRead
+while remainder > 0 {
+ let next = items.nextSpan(after: &index, maxCount: remainder)
+ guard !next.isEmpty else {
+ // Container does not have enough items
+ break
+ }
+ remainder -= next.count
+ // Process items in `next`
+}
+```
+
+This more powerful form of `nextSpan` is a core primitive; by default, most other `Container` requirements are implemented in terms of it. For example, here is the default implementation of `index(_:offsetBy:)`:
+
+```swift
+extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
+ func index(_ index: Index, offsetBy n: Int) -> Index {
+ var index = index
+ var n = n
+ let end = self.endIndex
+ while n > 0 {
+ let c = self.nextSpan(after: &index, maxCount: n, limitedBy: end).count
+ precondition(c > 0, "Cannot advance index beyond the end of the container")
+ n &-= c
+ }
+ return index
+ }
+}
+```
+
+Containers often hold their contents in piecewise contiguous storage chunks. As this default implementation iterates over entire chunks, it can be considerably more efficient than stepping through indices one by one, like `Collection` does. As the elements are required to preexist in memory, materializing spans over them is relatively cheap -- `nextSpan` merely needs to locate storage, not populate its contents. Still, it is often possible to implement `Container` operations more directly, and it is good practice to do so whenever it leads to measurable improvement.
+
+The default implementation of `distance(from:to:)` poses an interesting problem: `Container` only allows forward iteration, so to measure the distance between two indices, we have to start iterating from the one addressing the earlier one. But `Container` does not require its `Index` to be `Comparable`, so we cannot easily decide which index goes first! We have three options to resolve this:
+
+1. Only provide a default `distance` algorithm for containers with comparable indices.
+
+ ```swift
+ extension Container
+ where
+ Self: ~Copyable & ~Escapable,
+ Element: ~Copyable,
+ Index: Comparable
+ {
+ func distance(from start: Index, to end: Index) -> Int {
+ var (i, j, forward): (Index, Index, Bool) = (start <= end
+ ? (start, end, true)
+ : (end, start, false))
+ var d = 0
+ while i < j {
+ let span = self.nextSpan(after: &i, maxCount: .max, limitedBy: j)
+ precondition(span.count > 0, "Invalid Container")
+ d += span.count
+ }
+ return forward ? d : -d
+ }
+ }
+ ```
+
+ This visits exactly as many storage chunks as exist between the indices, so it is the most efficient way to calculate the distance. (Without knowing more about the internals of the container.)
+
+2. Require `start` to precede `end`, but with no easy way to validate this other than letting iteration go all the way to the end of the container.
+
+ ```swift
+ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
+ func distance(from start: Index, to end: Index) -> Int {
+ var i = start
+ var d = 0
+ while true {
+ let c = self.nextSpan(after: &i, maxCount: .max, limitedBy: end).count
+ d += c
+ if i == end { break }
+ precondition(c > 0, "Invalid Container or 'start' does not precede 'end'")
+ }
+ return d
+ }
+ }
+ ```
+
+ This option is equivalent to the previous one if `start` happens to come before `end`, but it runs all the way to the end of the container and then traps if they are in the wrong order. `Collection`'s original `distance` had no trouble returning negative values, so choosing this option could invite accidental misuse.
+
+3. Allow `start` and `end` to be in any order, but iterate forward from both ends until we find the other:
+
+ ```swift
+ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
+ func distance(from start: Index, to end: Index) -> Int {
+ // This variant allows start to follow end, but as indices aren't
+ // comparable, we have to measure distances from both ends.
+ var d1 = 0
+ var d2 = 0
+ var i1 = start
+ var i2 = end
+ var forward = true
+ var backward = true
+ while forward || backward {
+ if forward {
+ let c = self.nextSpan(after: &i1, limitedBy: end).count
+ d1 += c
+ if i1 == end { return d1 }
+ if c == 0 { forward = false }
+ }
+ if backward {
+ let c = self.nextSpan(after: &i2, limitedBy: start).count
+ d2 -= c
+ if i2 == start { return d2 }
+ if c == 0 { backward = false }
+ }
+ }
+ fatalError("Invalid Container")
+ }
+ }
+ ```
+
+ This option has to visit (at worst) twice as many items as the previous two in their regular execution, as the `limitedBy:` arguments [have no effect if the specified `limit` lies behind the start position](#limiting-index-semantics).
+
+To preserve continuity/interoperability with `Collection` (whose distance allows any ordering), `Container` implements option 3, while also providing the simpler/faster implementation from option 1, for the common case when `Index` is `Comparable`.
+
+For convenience, `Container` provides overloads that (effectively) make `nextSpan`'s `maxCount` and `limit` arguments optional:
+
+```swift
+extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
+ @_lifetime(borrow self)
+ func nextSpan(after index: inout Index, maxCount: Int) -> Span {
+ self.nextSpan(after: &index, maxCount: maxCount, limitedBy: self.endIndex)
+ }
+
+ @_lifetime(borrow self)
+ func nextSpan(after index: inout Index, limitedBy limit: Index) -> Span {
+ self.nextSpan(after: &index, maxCount: .max, limitedBy: limit)
+ }
+}
+```
+
+(The snippets above have already relied on these to avoid spelling out `maxCount`.)
+
+### Subscripting
+
+Bulk iteration is nice, but sometimes we do just want to access an individual element addressed by a specific index. For these cases, `Container` provides an indexing subscript with a [`borrow` accessor][BorrowAndMutate]:
+
+```swift
+protocol Container: ... {
+ ...
+ subscript(index: Index) -> Element { borrow }
+ ...
+}
+```
+
+This (alongside all the shared index operations) makes `Container` instantly familiar to developers who have used `Collection`. Of course, this indexing subscript is not the same as the classic `Collection` subscript: it has a `borrow` accessor, not a getter. As of Swift 6.4, we cannot even put its borrowed result in a local variable; to do that, we need to manually create a borrowing reference by wrapping the result in a `Ref` instance:
+
+```swift
+let item = someContainer[index] // error: 'someContainer.subscript' is borrowed and cannot be consumed
+let item2 = Ref(someContainer[index]) // OK
+```
+
+### Interaction with `Iterable`
+
+#### `ContainerIterator`
+
+`Container` refines `Iterable`, and its operations allow us to create standard implementations for `Iterable` requirements, allowing developers to avoid creating a custom iterator from scratch each time they need to create a container type. The standard iterator adapter is called `ContainerIterator`, and it serves the same purpose in the `Container` world as `IndexingIterator` does for `Collection`.
+
+A `ContainerIterator` instance stores a borrowing reference to a container value, alongside a current position inside it:
+
+```swift
+struct ContainerIterator<
+ Base: Container & ~Copyable /*& ~Escapable*/
+>: ~Copyable, ~Escapable
+where Base.Element: ~Copyable
+{
+ typealias Element = Base.Element
+
+ internal let _base: Ref // Note: This doesn't currently support nonescapable Bases
+ internal let _end: Base.Index
+ internal var _position: Base.Index
+}
+
+@available(SwiftStdlib 6.4, *)
+extension ContainerIterator: BorrowingIteratorProtocol
+where
+ Base: ~Copyable /*& ~Escapable*/,
+ Base.Element: ~Copyable
+{
+
+ @_lifetime(&self)
+ mutating func nextSpan(maxCount: Int) -> Span {
+ _base.value.nextSpan(after: &self._position, maxCount: maxCount, limitedBy: _end)
+ }
+
+ @_lifetime(self: copy self)
+ mutating func skip(by maximumOffset: Int) -> Int { ... }
+}
+```
+
+Compare this to `IndexingIterator`, which holds a _copy_ of its base collection, plus a current index. `ContainerIterator` implements the same idea, adapted for the borrowing ownership model. (It adds a limiting index to allow iterating over a subrange of elements in a container -- this is intended to substitute for a common use case of `Collection` slices.)
+
+#### Conversions Between Indices and Iterators
+
+`Container` resolves a long-standing `Collection` limitation by providing standard operations to start an iterator from a specific index (or between two indices), and to retrieve the current index of an existing iterator:
+
+```swift
+protocol Container: ... {
+ ...
+ @_lifetime(borrow self)
+ func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator
+ func currentIndex(of iterator: borrowing BorrowingIterator) -> Index
+ ...
+}
+
+extension Container
+where
+ Self: ~Copyable & ~Escapable,
+ Element: ~Copyable
+{
+ @_lifetime(borrow self)
+ func makeBorrowingIterator() -> BorrowingIterator {
+ self.makeBorrowingIterator(from: self.startIndex, to: self.endIndex)
+ }
+
+ @_lifetime(borrow self)
+ func makeBorrowingIterator(from start: Index) -> BorrowingIterator {
+ self.makeBorrowingIterator(from: start, to: self.endIndex)
+ }
+}
+```
+
+#### Default Implementations of `Iterable` requirements
+
+The `underestimatedCount` of a `Container` is simply its count:
+
+```swift
+extension Container
+where
+ Self: ~Copyable & ~Escapable,
+ Element: ~Copyable
+{
+ var underestimatedCount: Int { self.count }
+}
+```
+
+We'd like the `Container` protocol to declare `ContainerIterator` as its default borrowing iterator type:
+
+```swift
+protocol Container: ... {
+ ...
+ associatedtype BorrowingIterator = ContainerIterator
+ ...
+}
+```
+
+Unfortunately, this isn't currently possible, as `Ref` is not yet able to address nonescapable targets, and `Container` does need to allow nonescapable conforming types (such as `Span`). In its current form, `ContainerIterator` does not work for those, so nonescapable containers will need to manually implement a suitable iterator type.
+
+However, we can at least supply default implementations for all `Iterable`-related operations when `Iterator` happens to be `ContainerIterator`:
+
+```swift
+extension Container
+where
+ Self: ~Copyable,
+ Element: ~Copyable,
+ BorrowingIterator == ContainerIterator
+{
+ @_lifetime(borrow self)
+ func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator {
+ ContainerIterator(_borrowing: self, from: start, to: end)
+ }
+
+ func currentIndex(of iterator: borrowing BorrowingIterator) -> Index {
+ iterator._position
+ }
+}
+```
+
+### Optional Lookup Hooks
+
+`Collection` defines two customization hooks for quickly looking up the first and last indices of an `Equatable` element instance. We directly include the same requirements on `Container`:
+
+```swift
+protocol Container: ... {
+ ...
+ func _customIndexOfEquatableElement(_ element: borrowing Element) -> Index??
+ func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index??
+ ...
+}
+```
+
+On `Collection`, these hooks allow conforming types to customize the standard `firstIndex(of:)` and `lastIndex(of:)` operations to implement more efficient algorithms than linear search. For instance, a hashed set type may implement these hooks to provide lookup operations with an expected complexity of O(1).
+
+Like with `Collection`, these operations come with default implementations that simply return `nil`, indicating that there is no shortcut available for looking up elements.
+
+### Performance Requirements
+
+To achieve predictable performance, `Container` operations are expected to have the following worst-case complexities:
+
+| Operation | Complexity |
+|---|---|
+| `isEmpty` | O(1) |
+| `count` | O(1) |
+| `endIndex` | O(1) (non-negotiable requirement) |
+| `startIndex` | O(1) |
+| `nextSpan(...)` | O(1) |
+| `subscript(_:)` | O(1) |
+| `index(after:)` | O(1) |
+| `formIndex(after:)` | O(1) |
+| `index(_:offsetBy:)` | O(`n`) |
+| `formIndex(_:offsetBy:)` | O(`n`) |
+| `formIndex(_:offsetBy:limitedBy:)` | O(`n`) |
+| `distance(from:to:)` | O(*d*) where *d* is the absolute value of the actual distance |
+| `makeBorrowingIterator(...)` | O(1) |
+| `currentIndex(of:)` | O(1) |
+| `_customIndexOfEquatableElement(_:)` | O(1) |
+| `_customLastIndexOfEquatableElement(_:)` | O(1) |
+
+These correspond to similar (sometimes implicit) expectations on `Collection`'s operations, stated more consistently. Of these, only the constant complexity of `endIndex` is a hard requirement; the others are setting rough expectations that may sometimes need to be violated. All containers are required to clearly document any deviations from the expectations above.
+
+Common examples of containers with unusually high index navigation costs:
+
+- Containers with sparsely populated storage may need to scan an arbitrarily large number of empty storage slots between valid elements.
+
+ Hashed containers like the standard `Set` and `Dictionary` types are prominent examples of this -- their `index(after:)` implementation has a worst-case complexity that's linear in their storage capacities, which can be arbitrarily larger than their count. (Even when averaged over iterating over the entire contents of a dictionary, `index(after:)`'s amortized complexity is still O(`capacity`/`count`) i.e., the inverse of the current load factor -- which still has no constant upper bound.) This is difficult to mitigate in practice; for example, implementing a minimum load factor would resolve this, but it would lead to constant allocation churn that (in most cases) would be considered much worse than inconsistent iteration speed.
+
+- Container types built around balanced trees (such as sorted sets or ropes) commonly need to replace/augment many of these complexities with "O(log(`count`))" terms.
+
+### The Full `Container` protocol
+
+```swift
+protocol Container:
+ Iterable, ~Copyable, ~Escapable
+ where Element: ~Copyable, Failure == Never
+{
+ associatedtype Index: Equatable, Hashable
+ /*associatedtype BorrowingIterator = ContainerIterator*/
+
+ @_lifetime(borrow self)
+ func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator
+
+ func currentIndex(of iterator: borrowing BorrowingIterator) -> Index
+
+ var isEmpty: Bool { get }
+ var count: Int { get }
+ var startIndex: Index { get }
+ var endIndex: Index { get }
+
+ @_lifetime(borrow self)
+ func nextSpan(after index: inout Index) -> Span
+
+ @_lifetime(borrow self)
+ func nextSpan(
+ after index: inout Index,
+ maxCount: Int,
+ limitedBy limit: Index
+ ) -> Span
+
+ subscript(index: Index) -> Element { borrow }
+
+ 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
+
+ func _customIndexOfEquatableElement(_ element: borrowing Element) -> Index??
+ func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index??
+}
+```
+
+### Conforming to `Container`
+
+Types that wish to conform to protocol `Container` must, at minimum, complete the following tasks:
+
+1. Implement an `Index` type, and an index validation strategy. Dereferencing an index must be both safe and highly efficient: it must be possible to reliably and quickly check that an index represents a valid position in the container, and then use the data inside the index to efficiently find the correct element in the container's storage.
+
+2. Implement `startIndex` and `endIndex` properties. `endIndex` must be as efficient as possible; it is required to have O(1) complexity, on every container type.
+
+3. Implement a `count` property with O(1) complexity. Often, this requires backing it by a stored property that gets incrementally updated every time the container changes its size.
+
+4. Choose a `BorrowingIterator` type, and implement the related methods `makeBorrowingIterator(from:to:)` and `currentIndex(of:)`. The most straightforward choice is to use the standard `ContainerIterator` type; it provides a reasonable default for most container types.
+
+5. Implement the `nextSpan(after:maxCount:limitedBy:)` method. This is the core container primitive: the rest of container operations all come with default implementations based on this one.
+
+6. If the container is able to look up elements by value, provide custom implementations of `_custom[Last]IndexOfEquatableElement` so that standard algorithms can avoid falling back to linear searching.
+
+7. Implement custom implementations for additional container requirements, as needed. It is often possible to supply hand-optimized implementations that exploit the specific details of the container to provide measurably more efficient code than what the standard implementations achieve. Whether it is worth taking the extra effort to do this up front depends on the kind of container we're building, and its intended target use cases.
+
+Once a container type ships in source (or ABI) stable code base, its choices for `Index` and `BorrowingIterator` types get baked into its interface, and become tricky (or impossible) to change in future releases. However, it will still be possible to change the implementations of specific operations, for example, to replace the default implementation of an operation with a more efficient alternative.
+
+### Bidirectional Containers
+
+Note: This and the following sections are not yet complete.
+
+```swift
+protocol BidirectionalContainer: Container, ~Copyable, ~Escapable
+where Element: ~Copyable, Index: Comparable
+{
+ override associatedtype Element: ~Copyable
+ override associatedtype Index
+
+ func spanBoundary(before index: Index) -> (index: Index, distance: Int)
+
+ func spanBoundary(
+ before index: Index, maxDistance: Int, limitedBy limit: Index
+ ) -> (index: Index, distance: Int)
+
+ func index(before i: Index) -> Index
+ func formIndex(before i: inout Index)
+
+ override func index(after index: Index) -> Index
+ override func formIndex(after index: inout Index)
+
+ @_nonoverride func index(_ index: Index, offsetBy n: Int) -> Index
+ @_nonoverride func formIndex(_ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index)
+ @_nonoverride func distance(from start: Index, to end: Index) -> Int
+}
+```
+
+Note: Some `Container` requirements are redeclared as `override`s to help associated type inference; others are kept separate with `@_nonoverride`.
+
+Click to expand footnote
+
+> `@_nonoverride` creates separate witness table entries, allowing divergent implementations in conditional conformances. This enables conforming types to provide distinct implementations depending on whether the caller is generic over `Container` or `BidirectionalContainer`.
+>
+> (Unfortunately, neither `override` nor `@_nonoverride` allows callers that are generic over `Container` to automatically dispatch to a more constrained bidirectional implementation variant. Still, at least `@_nonoverride` enables more refined implementations to take effect when the caller is explicitly generic over `BidirectionalContainer`.)
+>
+> `@_nonoverride` should be used on requirements with new semantic constraints in refining protocols.
+>
+> Collection types usually do not come with conditional conformances to refining collection protocols (as the resulting behavior can be quite confusing), so the separate witness entries rarely if ever get exercised in practice. I don't expect things would be different with `Container`.
+>
+> FIXME: Consider avoiding using `@_nonoverride`, reducing witness sizes.
+
+
+### Random-Access Containers
+
+```
+protocol RandomAccessContainer
+: BidirectionalContainer, ~Copyable, ~Escapable
+where Element: ~Copyable, Index: Comparable {
+ override associatedtype Element: ~Copyable
+ override associatedtype Index
+
+ override func index(after index: Index) -> Index
+ override func index(before index: Index) -> Index
+
+ override func formIndex(after index: inout Index)
+ override func formIndex(before index: inout Index)
+
+ @_nonoverride func index(_ index: Index, offsetBy n: Int) -> Index
+ @_nonoverride func formIndex(_ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index)
+ @_nonoverride func distance(from start: Index, to end: Index) -> Int
+}
+```
+
+Click to expand footnote
+
+> `RandomAccessContainer` should technically redeclare single-steppers like `index(after:)` as `@_nonoverride`, as the protocol adds a semantic requirement for O(1) complexity. However, we emulate `RandomAccessCollection`'s (not necessarily well-justified) decision to leave these marked as overrides, forcing all types to have a single implementation that fulfills the (unique) requirement. (I haven't seen a case where these steppers would need to vary their implementation, while offsetting/distance calculations do sometimes want that, at least in theory. Not so much in practice though -- see e.g. `ZipSequence`'s lack of a conditional (random-access) collection conformance.)
+
+
+
+## Mutable Containers
+
+### `protocol PermutableContainer`
+
+```swift
+protocol PermutableContainer: Container, ~Copyable, ~Escapable
+where Element: ~Copyable
+{
+ @_lifetime(self: copy self)
+ mutating func swapAt(_ i: Index, _ j: Index)
+}
+```
+
+### `protocol MutableContainer`
+
+```swift
+protocol MutableContainer:
+ PermutableContainer, ~Copyable, ~Escapable
+where
+ Element: ~Copyable
+{
+ subscript(index: Index) -> Element { borrow mutate }
+
+ @_lifetime(&self)
+ mutating func nextMutableSpan(after index: inout Index) -> MutableSpan
+
+ @_lifetime(&self)
+ mutating func nextMutableSpan(
+ after index: inout Index,
+ maxCount: Int,
+ limitedBy limit: Index
+ ) -> MutableSpan
+}
+```
+
+## Producers
+
+## In-Place Consumption
+
+### `struct InputSpan`
+
+```swift
+struct InputSpan: ~Copyable, ~Escapable {
+ deinit
+ init()
+ init(buffer: UnsafeMutableBufferPointer, initializedCount: Int)
+ consuming func finalize(for buffer: UnsafeMutableBufferPointer) -> Int
+
+ var count: Int { get }
+ var freeCapacity: Int { get }
+ var isEmpty: Bool { get }
+ var isFull: Bool { get }
+
+ typealias Index = Int
+ var startIndex: Index { get }
+ var endIndex: Index { get }
+ var indices: Range { get }
+
+ subscript(_ index: Int) -> Element { borrow mutate }
+ subscript(unchecked index: Int) -> Element { borrow mutate }
+
+ mutating func swapAt(_ i: Index, _ j: Index)
+ mutating func swapAt(unchecked i: Index, unchecked j: Index)
+
+ mutating func prepend(_ value: consuming Element)
+ mutating func removeFirst() -> Element
+ mutating func removeFirst(_ k: Int)
+ mutating func popFirst() -> Element?
+ mutating func removeAll()
+ mutating func prepend(moving source: UnsafeMutableBufferPointer)
+ mutating func prepend(repeating repeatedValue: Element, count: Int) where Element: Copyable
+ mutating func prepend(copying source: UnsafeBufferPointer) where Element: Copyable
+ mutating func prepend(copying source: borrowing Span) where Element: Copyable
+
+ var span: Span { get }
+ var mutableSpan: MutableSpan { @_lifetime(&self) mutating get }
+
+ @_lifetime(self: copy self)
+ mutating func withUnsafeMutableBufferPointer(
+ _ body: (UnsafeMutableBufferPointer, inout Int) throws(E) -> R
+ ) throws(E) -> R
+
+ mutating func consumePrefix(upTo n: Int) -> InputSpan
+}
+```
+
+### `protocol Drain`
+
+## Range-Replaceable Containers
+
+### Index Ranges and Range Expressions
+
+### Adding Elements to a Container
+
+### Replacing Subranges
+
+### Consuming Subranges
+
+### Removing Subranges
+
+### Dynamic Containers
+
+## Rejected Directions
+
+### Cursors
+
+### Index Rounding Operations
+
+```
+ /// Return the nearest valid index in this container less than or equal to
+ /// the given index value, which must be valid in at least one view of self.
+ ///
+ /// This operation is important for container types that provide multiple
+ /// alternative projections (or "views") over the same underlying
+ /// representation, with each view conforming to `Container`, and sharing
+ /// the same `Index`. (Like `String` does with its UTF-8, UTF-16,
+ /// Unicode scalar and character views in the `Collection` world.)
+ /// This rounding operation enables clients to convert/normalize valid index
+ /// values in one container view into valid indices in another, allowing them
+ /// to (easily) decide whether two (potentially misaligned) index values
+ /// address the same element.
+ ///
+ /// The default implementation of this operation simply returns `index`.
+ ///
+ /// - Complexity: Recommended to be O(1). Conforming types must clearly
+ /// document deviations from this expectation.
+ func index(alignedDown index: Index) -> Index
+
+ /// Return the nearest valid index in this container greater than or equal to
+ /// the given index value, which must be valid in at least one view of self.
+ ///
+ /// This operation is important for container types that provide multiple
+ /// alternative projections (or "views") over the same underlying
+ /// representation, with each view conforming to `Container`, and sharing
+ /// the same `Index`. (Like `String` does with its UTF-8, UTF-16,
+ /// Unicode scalar and character views in the `Collection` world.)
+ /// This rounding operation enables clients to convert/normalize valid index
+ /// values in one container view into valid indices in another, allowing them
+ /// to (easily) decide whether two (potentially misaligned) index values
+ /// address the same element.
+ ///
+ /// The default implementation of this operation simply returns `index`.
+ ///
+ /// - Complexity: Recommended to be O(1). Conforming types must clearly
+ /// document deviations from this expectation.
+ func index(alignedUp index: Index) -> Index
+```
+
+## Potential Future Directions
+
+### Support for Nonescapable `Element` Types
+
+### Factoring Indexing Out of Containers
+
+(`protocol Indexable` with no element access; allows indexable producers, with the cost of greatly increased conceptual complexity.)
+
+### A Protocol for Directly Initializing Storage
diff --git a/Package.swift b/Package.swift
index 263a4918..70c83e3c 100644
--- a/Package.swift
+++ b/Package.swift
@@ -116,7 +116,6 @@ let extraSettings: [SwiftSetting] = [
.enableExperimentalFeature("AddressableParameters"),
.enableExperimentalFeature("AddressableTypes"),
.enableExperimentalFeature("SuppressedAssociatedTypesWithDefaults"), // Requires Swift 6.4
-
// Note: if you touch these, please make sure to also update the similar lists in
// CMakeLists.txt and Xcode/Shared.xcconfig.
]
diff --git a/Sources/BasicContainers/CMakeLists.txt b/Sources/BasicContainers/CMakeLists.txt
index 29bc573c..ceeb6e37 100644
--- a/Sources/BasicContainers/CMakeLists.txt
+++ b/Sources/BasicContainers/CMakeLists.txt
@@ -57,6 +57,7 @@ target_sources(${module_name} PRIVATE
"HashTable/_HTable+Bucket.swift"
"HashTable/_HTable+Consumption.swift"
"HashTable/_HTable+Debug.swift"
+ "HashTable/_HTable+Deprecated.swift"
"HashTable/_HTable+Find.swift"
"HashTable/_HTable+Insert.swift"
"HashTable/_HTable+Iteration.swift"
diff --git a/Sources/BasicContainers/HashTable/_HTable+Deprecated.swift b/Sources/BasicContainers/HashTable/_HTable+Deprecated.swift
new file mode 100644
index 00000000..449d93db
--- /dev/null
+++ b/Sources/BasicContainers/HashTable/_HTable+Deprecated.swift
@@ -0,0 +1,63 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 COLLECTIONS_SINGLE_MODULE
+
+#if compiler(>=6.2)
+extension _HTable.BucketIterator {
+ // FIXME: Remove after 27.0 releases
+ @available(*, deprecated, renamed: "advanceToOccupied(maxCount:)")
+ @usableFromInline
+ @discardableResult
+ @_lifetime(self: copy self)
+ internal mutating func advanceToOccupied(
+ maximumCount: Int
+ ) -> Bool {
+ self.advanceToOccupied(maxCount: maximumCount)
+ }
+
+ // FIXME: Remove after 27.0 releases
+ @available(*, deprecated, renamed: "advanceToUnoccupied(maxCount:)")
+ @usableFromInline
+ @discardableResult
+ @_lifetime(self: copy self)
+ internal mutating func advanceToUnoccupied(
+ maximumCount: Int
+ ) -> Bool {
+ self.advanceToUnoccupied(maxCount: maximumCount)
+ }
+
+ // FIXME: Remove after 27.0 releases
+ @available(*, deprecated, renamed: "nextOccupiedRegion(maxCount:)")
+ @usableFromInline
+ @_lifetime(self: copy self)
+ internal mutating func nextOccupiedRegion(
+ maximumCount: Int
+ ) -> Range? {
+ self.nextOccupiedRegion(maxCount: maximumCount)
+ }
+
+ // FIXME: Remove after 27.0 releases
+ @available(*, deprecated, renamed: "nextUnoccupiedRegion(maxCount:)")
+ @usableFromInline
+ @_lifetime(self: copy self)
+ internal mutating func nextUnoccupiedRegion(
+ maximumCount: Int
+ ) -> Range? {
+ self.nextUnoccupiedRegion(maxCount: maximumCount)
+ }
+}
+#endif
+
+#endif
+
diff --git a/Sources/BasicContainers/HashTable/_HTable+Iteration.swift b/Sources/BasicContainers/HashTable/_HTable+Iteration.swift
index 2905a889..728ee918 100644
--- a/Sources/BasicContainers/HashTable/_HTable+Iteration.swift
+++ b/Sources/BasicContainers/HashTable/_HTable+Iteration.swift
@@ -232,9 +232,9 @@ extension _HTable.BucketIterator {
@discardableResult
@_lifetime(self: copy self)
package mutating func advanceToOccupied(
- maximumCount: Int
+ maxCount: Int
) -> Bool {
- var remainder = UInt(bitPattern: maximumCount)
+ var remainder = UInt(bitPattern: maxCount)
if isAtEnd { return false }
if _words == nil {
let delta = Swift.min(_endBucket._offset &- _bucket._offset, remainder)
@@ -309,11 +309,11 @@ extension _HTable.BucketIterator {
@discardableResult
@_lifetime(self: copy self)
package mutating func advanceToUnoccupied(
- maximumCount: Int
+ maxCount: Int
) -> Bool {
- assert(maximumCount > 0)
+ assert(maxCount > 0)
assert(!isAtEnd)
- var remainder = UInt(bitPattern: maximumCount)
+ var remainder = UInt(bitPattern: maxCount)
if _words == nil {
let delta = Swift.min(_endBucket._offset &- _bucket._offset, remainder)
_bucket._offset &+= delta
@@ -363,13 +363,13 @@ extension _HTable.BucketIterator {
@usableFromInline
@_lifetime(self: copy self)
package mutating func nextOccupiedRegion(
- maximumCount: Int = .max
+ maxCount: Int = .max
) -> Range? {
- assert(maximumCount > 0)
+ assert(maxCount > 0)
guard self.advanceToOccupied() else { return nil }
assert(self.isOccupied)
let start = self.currentBucket
- self.advanceToUnoccupied(maximumCount: maximumCount)
+ self.advanceToUnoccupied(maxCount: maxCount)
let end = self.currentBucket
return Range(uncheckedBounds: (start, end))
}
@@ -377,13 +377,13 @@ extension _HTable.BucketIterator {
@usableFromInline
@_lifetime(self: copy self)
package mutating func nextUnoccupiedRegion(
- maximumCount: Int = .max
+ maxCount: Int = .max
) -> Range? {
- assert(maximumCount > 0)
+ assert(maxCount > 0)
guard self.advanceToUnoccupied() else { return nil }
assert(!self.isOccupied)
let start = self.currentBucket
- self.advanceToOccupied(maximumCount: maximumCount)
+ self.advanceToOccupied(maxCount: maxCount)
let end = self.currentBucket
return Range(uncheckedBounds: (start, end))
}
diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift
index 0099c261..f0df517b 100644
--- a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift
+++ b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift
@@ -130,6 +130,7 @@ extension RigidArray where Element: ~Copyable {
public mutating func append(
moving items: inout InputSpan
) {
+ // FIXME: Remove this when `InputSpan` starts conforming to RangeReplaceableContainer
items.withUnsafeMutableBufferPointer { buffer, count in
let source = buffer._extracting(last: count)
unsafe self.append(moving: source)
@@ -152,6 +153,7 @@ extension RigidArray where Element: ~Copyable {
public mutating func append(
moving items: inout OutputSpan
) {
+ // FIXME: Remove this when `OutputSpan` starts conforming to RangeReplaceableContainer
items.withUnsafeMutableBufferPointer { buffer, count in
let source = buffer._extracting(first: count)
unsafe self.append(moving: source)
@@ -159,6 +161,7 @@ extension RigidArray where Element: ~Copyable {
}
}
+#if !UnstableContainersPreview
/// Appends the elements of a given array to the end of this array by moving
/// them between the containers. On return, the input array becomes empty, but
/// it is not destroyed, and it preserves its original storage capacity.
@@ -174,107 +177,10 @@ extension RigidArray where Element: ~Copyable {
public mutating func append(
moving items: inout RigidArray
) {
- // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers
items.edit { span in
self.append(moving: &span)
}
}
-}
-
-@available(SwiftStdlib 5.0, *)
-extension RigidArray where Element: ~Copyable {
-#if UnstableContainersPreview
- /// Appends the elements of a given container to the end of this array by
- /// consuming the source container.
- ///
- /// If the target array does not have sufficient capacity to hold all items
- /// in the source array, then this triggers a runtime error.
- ///
- /// - Parameters:
- /// - items: A container whose contents to move into this array.
- ///
- /// - Complexity: O(`items.count`)
- @_alwaysEmitIntoClient
- public mutating func append(
- consuming items: consuming RigidArray
- ) {
- // FIXME: Remove this in favor of a generic algorithm over consumable containers
- var items = items
- self.append(moving: &items)
- }
-#endif
-}
-
-@available(SwiftStdlib 5.0, *)
-extension RigidArray where Element: ~Copyable {
-#if compiler(>=6.4) && UnstableContainersPreview
- /// 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 & ~Copyable & ~Escapable
- >(
- addingCount newItemCount: Int,
- from producer: inout P
- ) throws(E)
- where P.Element: ~Copyable
- {
- try self.append(addingCount: newItemCount) { target throws(E) in
- while !target.isFull {
- guard try producer.generate(into: &target) else { break }
- }
- }
- }
-#endif
-
-#if compiler(>=6.4) && UnstableContainersPreview
- /// 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 & ~Copyable & ~Escapable
- >(
- from producer: inout P
- ) throws(E)
- where P.Element: ~Copyable
- {
- 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
}
@@ -331,7 +237,7 @@ extension RigidArray {
/// - Complexity: O(`newElements.count`)
@_alwaysEmitIntoClient
public mutating func append(copying items: Span) {
- unsafe items.withUnsafeBufferPointer { source in
+ items.withUnsafeBufferPointer { source in
unsafe self.append(copying: source)
}
}
@@ -347,6 +253,7 @@ extension RigidArray {
}
#if compiler(>=6.4) && UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@inlinable
internal mutating func _append<
Source: Iterable_ & ~Copyable & ~Escapable
@@ -369,6 +276,7 @@ extension RigidArray {
/// - newElements: A container whose contents to copy into the array.
///
/// - Complexity: O(`newElements.count`)
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func append<
@@ -412,6 +320,7 @@ extension RigidArray {
/// - newElements: The new elements to copy into the array.
///
/// - Complexity: O(*m*), where *m* is the length of `newElements`.
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func append<
diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift
index d1a607c6..2447d23f 100644
--- a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift
+++ b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift
@@ -138,7 +138,7 @@ extension RigidArray where Element: ~Copyable {
#endif
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 6.4, *)
+@available(SwiftStdlib 5.0, *)
extension RigidArray where Element: ~Copyable {
@_alwaysEmitIntoClient
@inline(__always)
@@ -148,9 +148,9 @@ extension RigidArray where Element: ~Copyable {
}
}
-@available(SwiftStdlib 6.4, *)
+@available(SwiftStdlib 5.0, *)
extension RigidArray where Element: ~Copyable {
- @available(SwiftStdlib 6.4, *)
+ @available(SwiftStdlib 5.0, *)
@frozen
public struct SubrangeConsumer: ~Copyable, ~Escapable {
// FIXME: We have to use our own MutableRef because the standard one
@@ -191,20 +191,25 @@ extension RigidArray where Element: ~Copyable {
}
-@available(SwiftStdlib 6.4, *)
+@available(SwiftStdlib 5.0, *)
extension RigidArray.SubrangeConsumer: Drain where Element: ~Copyable {
}
-@available(SwiftStdlib 6.4, *)
+@available(SwiftStdlib 5.0, *)
extension RigidArray.SubrangeConsumer where Element: ~Copyable {
+ @inlinable
+ public var count: Int {
+ _remainder.count
+ }
+
@inlinable
@_lifetime(&self)
@_lifetime(self: copy self)
- public mutating func drainNext(maximumCount: Int) -> InputSpan {
+ public mutating func drainNext(maxCount: Int) -> InputSpan {
if _remainder.isEmpty {
return .init()
}
- let buffer = _remainder._trim(first: maximumCount)
+ let buffer = _remainder._trim(first: maxCount)
return _overrideLifetime(
InputSpan(buffer: buffer, initializedCount: buffer.count),
mutating: &self)
diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift
index 3ae8cc59..dc72b4df 100644
--- a/Sources/BasicContainers/RigidArray/RigidArray+Container.swift
+++ b/Sources/BasicContainers/RigidArray/RigidArray+Container.swift
@@ -19,25 +19,46 @@ import ContainersPreview
#if compiler(>=6.2)
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension RigidArray: Iterable_ where Element: ~Copyable {
- public typealias IterableIterator_ = SpanIterator
+ public typealias BorrowingIterator_ = Span.BorrowingIterator_
+
@_alwaysEmitIntoClient
@inline(__always)
- public func makeIterableIterator_() -> IterableIterator_ {
- SpanIterator(self.span)
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ let span = self.span
+ let it = span.makeBorrowingIterator_()
+ // FIXME: `it` is borrowing `span`, not self
+ return _overrideLifetime(it, borrowing: self)
}
}
#endif
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
-extension RigidArray: Container where Element: ~Copyable {}
+@available(SwiftStdlib 6.4, *)
+extension RigidArray: Container where Element: ~Copyable {
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func makeBorrowingIterator(
+ from start: Index, to end: Index
+ ) -> BorrowingIterator_ {
+ // FIXME: `makeBorrowingIterator` would be borrowing the temporary `span`, not self
+ self.span._makeBorrowingIterator(from: start, to: end)
+ }
-@available(SwiftStdlib 5.0, *)
+ @_alwaysEmitIntoClient
+ public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index {
+ precondition(
+ iterator._span.isTriviallyIdentical(to: self.span),
+ "Invalid iterator instance")
+ return iterator._start
+ }
+}
+
+@available(SwiftStdlib 6.4, *)
extension RigidArray: BidirectionalContainer where Element: ~Copyable {}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension RigidArray: RandomAccessContainer where Element: ~Copyable {}
#if compiler(>=6.4)
@@ -134,7 +155,7 @@ extension RigidArray where Element: ~Copyable {
let p = _storage.baseAddress.unsafelyUnwrapped.advanced(by: index)
return UnsafePointer(p)
}
-
+
@inlinable @inline(__always)
internal mutating func _mutablePtr(
to index: Int
@@ -142,7 +163,29 @@ extension RigidArray where Element: ~Copyable {
_checkItemIndex(index)
return _storage.baseAddress.unsafelyUnwrapped.advanced(by: index)
}
-
+
+#if compiler(>=6.4)
+ /// Accesses the element at the specified position.
+ ///
+ /// - Parameter position: The position of the element to access.
+ /// The position must be a valid index of the array that is not equal
+ /// to the `endIndex` property.
+ ///
+ /// - Complexity: O(1)
+ @inlinable
+ public subscript(position: Int) -> Element {
+ @inline(__always)
+ @_unsafeSelfDependentResult
+ borrow {
+ _ptr(to: position).pointee
+ }
+ @inline(__always)
+ @_unsafeSelfDependentResult
+ mutate {
+ &_mutablePtr(to: position).pointee
+ }
+ }
+#else
/// Accesses the element at the specified position.
///
/// - Parameter position: The position of the element to access.
@@ -161,6 +204,7 @@ extension RigidArray where Element: ~Copyable {
_mutablePtr(to: position)
}
}
+#endif
}
@available(SwiftStdlib 5.0, *)
@@ -308,10 +352,6 @@ extension RigidArray where Element: ~Copyable {
/// On return, `n` is set to zero if the operation succeeded without
/// hitting the limit; otherwise, `n` reflects the number of steps that
/// couldn't be taken.
- /// - Parameter limit: A valid index of the array to use as a limit.
- /// If `n > 0`, a limit that is less than `index` has no effect.
- /// Likewise, if `n < 0`, a limit that is greater than `index` has no
- /// effect.
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public func formIndex(
@@ -320,9 +360,17 @@ extension RigidArray where Element: ~Copyable {
index._advance(by: &n, limitedBy: limit)
}
+ @inlinable
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Int
+ ) -> Span {
+ self.span._nextSpan(after: &index)
+ }
+
/// Return a span over the array's storage that begins with the element at
/// the given index, and extends to the end of the contiguous storage chunk
- /// that contains it, but no more than `maximumCount` items.
+ /// that contains it, but no more than `maxCount` items.
///
/// On return, the index is updated to address the next item following the
/// end of the returned span.
@@ -333,30 +381,30 @@ extension RigidArray where Element: ~Copyable {
///
/// var index = items.startIndex
/// while true {
- /// let span = items.nextSpan(after: &index, maximumCount: 4)
+ /// let span = items.nextSpan(after: &index, maxCount: 4)
/// if span.isEmpty { break }
/// // Process items in `span`
/// }
///
- /// The `maximumCount` argument gives the caller control over the number of
+ /// The `maxCount` argument gives the caller control over the number of
/// items it receives from the iterator. This lets the caller avoid getting
/// more elements than it would be able to immediately process, which would
/// significantly complicate container use.
///
/// If the caller is able to process any number available items, it can signal
- /// that by passing `Int.max` as the `maximumCount`, or simply by calling the
+ /// that by passing `Int.max` as the `maxCount`, or simply by calling the
/// `nexSpan(after:)` method, which does precisely that. This is frequently
/// the case when the caller simply wants to iterate over the entire
/// container in a single loop.
///
- /// `maximumCount` sets an upper bound. To read a specific number of items,
+ /// `maxCount` sets an upper bound. To read a specific number of items,
/// the caller usually needs to invoke `nextSpan` in a loop:
///
/// var items: some Container
/// var index = items.startIndex
/// var remainder = numberOfItemsToRead
/// while remainder > 0 {
- /// let next = items.nextSpan(after: &index, maximumCount: remainder)
+ /// let next = items.nextSpan(after: &index, maxCount: remainder)
/// guard !next.isEmpty else {
/// // Container does not have enough items
/// break
@@ -379,10 +427,14 @@ extension RigidArray where Element: ~Copyable {
/// - 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.
- /// - Parameter maximumCount: The maximum number of items the caller is able
- /// to process immediately. `maximumCount` must be greater than zero.
+ /// - Parameter maxCount: The maximum number of items the caller is able
+ /// to process immediately. `maxCount` must be greater than zero.
/// If you are able to process an arbitrary number of items, set
- /// `maximumCount` to `Int.max`, or call the `nextSpan(after:)` method.
+ /// `maxCount` to `Int.max`, or call the `nextSpan(after:)` method.
+ /// - Parameter limit: A valid index of the array to use as a limit.
+ /// If `n > 0`, a limit that is less than `index` has no effect.
+ /// Likewise, if `n < 0`, a limit that is greater than `index` has no
+ /// effect.
/// - 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
@@ -391,35 +443,58 @@ extension RigidArray where Element: ~Copyable {
@inlinable
@_lifetime(borrow self)
public func nextSpan(
- after index: inout Int, maximumCount: Int
+ after index: inout Int, maxCount: Int, limitedBy limit: Index
) -> Span {
- _checkValidIndex(index)
- precondition(maximumCount > 0, "maximumCount must be positive")
- let start = index
- index = start &+ Swift.min(maximumCount, _count &- start)
- return _span(in: Range(uncheckedBounds: (start, index)))
+ self.span._nextSpan(after: &index, maxCount: maxCount, limitedBy: limit)
}
@inlinable
@_lifetime(&self)
- public mutating func nextMutableSpan(after index: inout Int, maximumCount: Int) -> MutableSpan {
+ public mutating func nextMutableSpan(
+ after index: inout Int
+ ) -> MutableSpan {
_checkValidIndex(index)
- precondition(maximumCount > 0, "maximumCount must be positive")
- let start = index
- index = start &+ Swift.min(maximumCount, _count &- start)
- return _mutableSpan(in: Range(uncheckedBounds: (start, index)))
+ return _mutableSpan(in: Range(uncheckedBounds: (index, count)))
}
@inlinable
+ @_lifetime(&self)
+ public mutating func nextMutableSpan(
+ after index: inout Int, maxCount: Int, limitedBy limit: Int
+ ) -> MutableSpan {
+ _checkValidIndex(index)
+ _checkValidIndex(limit)
+ precondition(maxCount > 0, "maxCount must be positive")
+ let end = index._clampedUp(
+ towards: count, maxDistance: maxCount, limitedBy: limit)
+ return _mutableSpan(in: Range(uncheckedBounds: (index, end)))
+ }
+
+ @_alwaysEmitIntoClient
+ public func spanBoundary(before index: Index) -> (index: Index, distance: Int) {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ return (0, index)
+ }
+
+ @_alwaysEmitIntoClient
+ public func spanBoundary(
+ before index: Index, maxDistance: Int, limitedBy limit: Index
+ ) -> (index: Index, distance: Int) {
+ self.span.spanBoundary(
+ before: index, maxDistance: maxDistance, limitedBy: limit)
+ }
+
+ @_alwaysEmitIntoClient
@_lifetime(borrow self)
public func previousSpan(
- before index: inout Int, maximumCount: Int
+ before index: inout Int, maxCount: Int
) -> Span {
+ // FIXME: Remove this in favor of the BidirectionalContainer algorithm.
_checkValidIndex(index)
- precondition(maximumCount > 0, "maximumCount must be positive")
+ precondition(maxCount > 0, "maxCount must be positive")
let start = index
- index = start &- Swift.min(maximumCount, start)
- return _span(in: Range(uncheckedBounds: (index, start)))
+ index = start &- Swift.min(maxCount, start)
+ return _span(in: Range(uncheckedBounds: (start, index)))
}
}
diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift
index 43cc2db5..3719fbbe 100644
--- a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift
+++ b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift
@@ -15,6 +15,39 @@
@available(SwiftStdlib 5.0, *)
extension RigidArray where Element: ~Copyable {
+ @available(*, deprecated, renamed: "nextSpan(after:maxCount:)")
+ @inlinable
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Int, maximumCount: Int
+ ) -> Span {
+ self.nextSpan(
+ after: &index,
+ maxCount: maximumCount,
+ limitedBy: self.endIndex)
+ }
+
+ @available(*, deprecated, renamed: "nextMutableSpan(after:maxCount:)")
+ @inlinable
+ @_lifetime(&self)
+ public mutating func nextMutableSpan(
+ after index: inout Int, maximumCount: Int
+ ) -> MutableSpan {
+ self.nextMutableSpan(
+ after: &index,
+ maxCount: maximumCount,
+ limitedBy: self.endIndex)
+ }
+
+ @available(*, deprecated, renamed: "previousSpan(before:maxCount:)")
+ @inlinable
+ @_lifetime(borrow self)
+ public func previousSpan(
+ before index: inout Int, maximumCount: Int
+ ) -> Span {
+ self.previousSpan(before: &index, maxCount: maximumCount)
+ }
+
/// Append a given number of items to the end of this array by populating
/// an output span.
///
diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift b/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift
index e32a8c49..fcb8a698 100644
--- a/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift
+++ b/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift
@@ -25,9 +25,13 @@ extension RigidArray where Element: ~Copyable {
}
}
-#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+#if compiler(>=6.4)
+@available(SwiftStdlib 6.4, *)
extension RigidArray: Equatable where Element: Equatable & ~Copyable {
+}
+
+@available(SwiftStdlib 5.0, *)
+extension RigidArray where Element: Equatable & ~Copyable {
@inlinable
public static func ==(
left: borrowing Self,
diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Hashable.swift b/Sources/BasicContainers/RigidArray/RigidArray+Hashable.swift
index 3b0e264f..7cab7841 100644
--- a/Sources/BasicContainers/RigidArray/RigidArray+Hashable.swift
+++ b/Sources/BasicContainers/RigidArray/RigidArray+Hashable.swift
@@ -17,13 +17,28 @@
import InternalCollectionsUtilities
#endif
+#if compiler(>=6.4)
+@available(SwiftStdlib 6.4, *)
+extension RigidArray: Hashable where Element: Hashable & ~Copyable {
+}
+
@available(SwiftStdlib 5.0, *)
-extension RigidArray /*: Hashable */ where Element: Hashable /* & ~Copyable */ {
+extension RigidArray where Element: Hashable & ~Copyable {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(self.count)
self.span._hashContents(into: &hasher)
}
}
+#else
+@available(SwiftStdlib 5.0, *)
+extension RigidArray where Element: Hashable {
+ @inlinable
+ public func hash(into hasher: inout Hasher) {
+ hasher.combine(self.count)
+ self.span._hashContents(into: &hasher)
+ }
+}
+#endif
#endif
diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift
index 62976415..c06037db 100644
--- a/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift
+++ b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift
@@ -122,6 +122,7 @@ extension RigidArray /*where Element: Copyable*/ {
/// just enough capacity to store the contents.
/// - contents: The container whose contents to copy into the new array.
/// The container must not contain more than `capacity` elements.
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public init(
@@ -144,6 +145,7 @@ extension RigidArray /*where Element: Copyable*/ {
/// just enough capacity to store the contents.
/// - contents: The container whose contents to copy into the new array.
/// The container must not contain more than `capacity` elements.
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public init>(
diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift
index 82b7da61..80599107 100644
--- a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift
+++ b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift
@@ -170,6 +170,7 @@ extension RigidArray where Element: ~Copyable {
moving items: inout InputSpan,
at index: Int
) {
+ // FIXME: Remove when InputSpan starts conforming to RangeReplaceableContainer
items.withUnsafeMutableBufferPointer { buffer, count in
let source = buffer._extracting(last: count)
unsafe self.insert(moving: source, at: index)
@@ -199,6 +200,7 @@ extension RigidArray where Element: ~Copyable {
moving items: inout OutputSpan,
at index: Int
) {
+ // FIXME: Remove when OutputSpan starts conforming to RangeReplaceableContainer
items.withUnsafeMutableBufferPointer { buffer, count in
let source = buffer._extracting(first: count)
unsafe self.insert(moving: source, at: index)
@@ -206,6 +208,7 @@ extension RigidArray where Element: ~Copyable {
}
}
+#if !UnstableContainersPreview
/// Inserts the elements of a given array into the given position in this
/// array by moving them between the containers. On return, the input array
/// becomes empty, but it is not destroyed, and it preserves its original
@@ -234,88 +237,9 @@ extension RigidArray where Element: ~Copyable {
self.insert(moving: &source, at: index)
}
}
-}
-
-@available(SwiftStdlib 5.0, *)
-extension RigidArray where Element: ~Copyable {
-#if UnstableContainersPreview
- /// Inserts the elements of a given array into the given position in this
- /// array by consuming the source container.
- ///
- /// All existing elements at or following the specified position are moved to
- /// make room for the new items.
- ///
- /// If the capacity of the array isn't sufficient to accommodate the new
- /// elements, then this method triggers a runtime error.
- ///
- /// - Parameters:
- /// - items: The array whose contents to move into `self`.
- /// - index: The position at which to insert the new items.
- /// `index` must be a valid index in the array.
- ///
- /// - Complexity: O(`count` + `items.count`)
- @_alwaysEmitIntoClient
- public mutating func insert(
- consuming items: consuming RigidArray,
- at index: Int
- ) {
- // FIXME: Remove this in favor of a generic algorithm over consumable containers
- var items = items
- self.insert(moving: &items, at: index)
- }
#endif
}
-@available(SwiftStdlib 5.0, *)
-extension RigidArray where Element: ~Copyable {
-#if compiler(>=6.4) && UnstableContainersPreview
- /// 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 & ~Copyable & ~Escapable
- >(
- addingCount newItemCount: Int,
- from producer: inout P,
- at index: Int
- ) throws(E)
- where P.Element: ~Copyable
- {
- 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
@@ -406,85 +330,31 @@ extension RigidArray {
}
}
-#if compiler(>=6.4) && UnstableContainersPreview
@_alwaysEmitIntoClient
- internal mutating func _insertContainer<
- C: Container & ~Copyable & ~Escapable
- >(
- at index: Int,
- copying items: borrowing C,
- newCount: Int
+ package mutating func _insertCollection(
+ addingCount newCount: Int,
+ copying items: some Collection,
+ at index: Index
) {
- var it = items.makeIterableIterator_()
- insert(addingCount: newCount, at: index) { target in
- while !target.isFull {
- let source = it.nextSpan_(maximumCount: target.freeCapacity)
- precondition(!source.isEmpty, "Broken container: mismatching count")
- target._append(copying: source)
+ // FIXME: Remove this -- RangeReplaceContainer already has this algorithm,
+ // albeit with stricter availability.
+ let done: Void? = items.withContiguousStorageIfAvailable { buffer in
+ precondition(buffer.count == newCount, "Broken Collection: mismatching count")
+ self.insert(addingCount: buffer.count, at: index) { target in
+ target._append(copying: buffer)
}
}
- precondition(it.nextSpan_().isEmpty, "Broken container: mismatching count")
- }
-#endif
-
- @inlinable
- internal mutating func _insertCollection(
- at index: Int,
- copying items: some Collection,
- newCount: Int
- ) {
- _checkValidIndex(index)
- precondition(newCount <= freeCapacity, "RigidArray capacity overflow")
- let gap = unsafe _openGap(at: index, count: newCount)
-
- let done: Void? = items.withContiguousStorageIfAvailable { buffer in
- let i = unsafe gap._initializePrefix(copying: buffer)
- precondition(
- i == newCount,
- "Broken Collection: count doesn't match contents")
- _count += newCount
- }
if done != nil { return }
-
- var (it, copied) = unsafe items._copyContents(initializing: gap)
- precondition(
- it.next() == nil && copied == newCount,
- "Broken Collection: count doesn't match contents")
- _count += newCount
+ var it = items.makeIterator()
+ self.insert(addingCount: newCount, at: index) { target in
+ while !target.isFull {
+ guard let item = it.next() else { preconditionFailure() }
+ target.append(item)
+ }
+ }
+ precondition(it.next() == nil, "Broken Collection")
}
-#if compiler(>=6.4) && UnstableContainersPreview
- /// Copies the elements of a container into this array at the specified
- /// position.
- ///
- /// The new elements are inserted before the element currently at the
- /// specified index. If you pass the array's `endIndex` as the `index`
- /// parameter, then the new elements are appended to the end of the array.
- ///
- /// All existing elements at or following the specified position are moved to
- /// make room for the new item.
- ///
- /// If the capacity of the array isn't sufficient to accommodate the new
- /// elements, then this method triggers a runtime error.
- ///
- /// - Parameters:
- /// - newElements: The new elements to insert into the array.
- /// - index: The position at which to insert the new elements. It must be
- /// a valid index of the array.
- ///
- /// - Complexity: O(`self.count` + `newElements.count`).
- @_alwaysEmitIntoClient
- @inline(__always)
- public mutating func insert<
- C: Container & ~Copyable & ~Escapable
- >(
- copying newElements: borrowing C, at index: Int
- ) {
- _insertContainer(
- at: index, copying: newElements, newCount: newElements.count)
- }
-#endif
-
/// Copies the elements of a collection into this array at the specified
/// position.
///
@@ -504,46 +374,13 @@ extension RigidArray {
/// a valid index of the array.
///
/// - Complexity: O(`count` + `newElements.count`)
- @inlinable
- @inline(__always)
- public mutating func insert(
- copying newElements: some Collection, at index: Int
- ) {
- _insertCollection(
- at: index, copying: newElements, newCount: newElements.count)
- }
-
-#if compiler(>=6.4) && UnstableContainersPreview
- /// Copies the elements of a container into this array at the specified
- /// position.
- ///
- /// The new elements are inserted before the element currently at the
- /// specified index. If you pass the array's `endIndex` as the `index`
- /// parameter, then the new elements are appended to the end of the array.
- ///
- /// All existing elements at or following the specified position are moved to
- /// make room for the new item.
- ///
- /// If the capacity of the array isn't sufficient to accommodate the new
- /// elements, then this method triggers a runtime error.
- ///
- /// - Parameters:
- /// - newElements: The new elements to insert into the array.
- /// - index: The position at which to insert the new elements. It must be
- /// a valid index of the array.
- ///
- /// - Complexity: O(`self.count` + `newElements.count`)
@_alwaysEmitIntoClient
@inline(__always)
- public mutating func insert<
- C: Container & Collection
- >(
- copying newElements: borrowing C, at index: Int
+ public mutating func insert(
+ copying items: some Collection, at index: Int
) {
- _insertContainer(
- at: index, copying: newElements, newCount: newElements.count)
+ _insertCollection(addingCount: items.count, copying: items, at: index)
}
-#endif
}
#endif
diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift
index 7770abea..1b41f517 100644
--- a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift
+++ b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift
@@ -114,7 +114,7 @@ extension RigidArray where Element: ~Copyable {
/// - Complexity: O(`count`)
@_alwaysEmitIntoClient
public mutating func removeSubrange(_ bounds: some RangeExpression) {
- // FIXME: Remove this in favor of a standard algorithm.
+ // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm.
removeSubrange(bounds.relative(to: indices))
}
}
@@ -129,7 +129,7 @@ extension RigidArray where Element: ~Copyable {
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public mutating func popLast() -> Element? {
- // FIXME: Remove this in favor of a standard algorithm.
+ // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm.
if isEmpty { return nil }
return removeLast()
}
diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift
index 0d332c7a..b193c14e 100644
--- a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift
+++ b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift
@@ -446,7 +446,7 @@ extension RigidArray where Element: ~Copyable {
/// - 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`)
+ /// - Complexity: O(`self.count` + `newItemCount`)
@_alwaysEmitIntoClient
public mutating func replace<
E: Error,
@@ -577,12 +577,13 @@ extension RigidArray {
removing subrange: Range,
copying newElements: Span
) {
- unsafe newElements.withUnsafeBufferPointer { buffer in
+ newElements.withUnsafeBufferPointer { buffer in
unsafe self.replace(removing: subrange, copying: buffer)
}
}
#if compiler(>=6.4) && UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@inlinable
internal mutating func _replace<
C: Container & ~Copyable & ~Escapable
@@ -591,10 +592,10 @@ extension RigidArray {
copyingContainer items: borrowing C,
newCount: Int
) {
- var it = items.makeIterableIterator_()
+ var it = items.makeBorrowingIterator_()
self.replace(removing: subrange, addingCount: newCount) { target in
while !target.isFull {
- let source = it.nextSpan_(maximumCount: target.freeCapacity)
+ let source = it.nextSpan_(maxCount: target.freeCapacity)
precondition(
!source.isEmpty,
"Broken Container: count doesn't match contents")
@@ -661,6 +662,7 @@ extension RigidArray {
/// - newElements: The new elements to copy into the collection.
///
/// - Complexity: O(`self.count` + `newElements.count`)
+ @available(SwiftStdlib 6.4, *)
@inlinable
@inline(__always)
public mutating func replace<
@@ -742,6 +744,7 @@ extension RigidArray {
///
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
+ @available(SwiftStdlib 6.4, *)
@inlinable
@inline(__always)
public mutating func replace<
diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift
index 23b8383a..7eaba400 100644
--- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift
+++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift
@@ -20,7 +20,7 @@ import ContainersPreview
#if compiler(>=6.4) && UnstableHashedContainers
@available(SwiftStdlib 5.0, *)
-extension RigidDictionary {
+extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
@inlinable
public func isTriviallyIdentical(to other: borrowing Self) -> Bool {
self._keys.isTriviallyIdentical(to: other._keys)
@@ -29,7 +29,7 @@ extension RigidDictionary {
}
@available(SwiftStdlib 5.0, *)
-extension RigidDictionary {
+extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
@inlinable
public func isEqual(
to other: borrowing Self,
@@ -56,8 +56,11 @@ extension RigidDictionary {
}
}
+@available(SwiftStdlib 6.4, *)
+extension RigidDictionary: Equatable where Key: ~Copyable, Value: Equatable & ~Copyable {}
+
@available(SwiftStdlib 5.0, *)
-extension RigidDictionary: Equatable where Value: Equatable {
+extension RigidDictionary where Key: ~Copyable, Value: Equatable & ~Copyable {
@inlinable
public static func ==(left: borrowing Self, right: borrowing Self) -> Bool {
left.isEqual(to: right, by: ==)
diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift
index 398785cd..5b49ff4d 100644
--- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift
+++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift
@@ -18,8 +18,12 @@ import ContainersPreview
#if compiler(>=6.4) && UnstableHashedContainers
+@available(SwiftStdlib 6.4, *)
+extension RigidDictionary: Hashable where Value: Hashable & ~Copyable {
+}
+
@available(SwiftStdlib 5.0, *)
-extension RigidDictionary: Hashable where Value: Hashable { // Should be Hashable
+extension RigidDictionary where Value: Hashable & ~Copyable {
@inlinable
public func hash(into hasher: inout Hasher) {
var commutativeHash = 0
diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift
index 198e3606..de7e2951 100644
--- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift
+++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift
@@ -15,7 +15,7 @@
import ContainersPreview
#endif
-#if compiler(>=6.4) && UnstableHashedContainers
+#if compiler(>=6.4) && UnstableHashedContainers && UnstableContainersPreview
@available(SwiftStdlib 6.2, *)
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
@@ -50,7 +50,7 @@ where Key: ~Copyable, Value: ~Copyable
public typealias Element_ = Element
@frozen
- public struct IterableIterator_: ~Escapable {
+ public struct BorrowingIterator_: ~Escapable {
public typealias Element = RigidDictionary.Index
@usableFromInline
@@ -73,21 +73,21 @@ where Key: ~Copyable, Value: ~Copyable
public var underestimatedCount_: Int { self._base.value.count }
@_lifetime(borrow self) // FIXME: Should be @_lifetime(copy self)
- public func makeIterableIterator_() -> IterableIterator_ {
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
let bit = self._base.value.makeBucketIterator()
// FIXME: This override really should not be necessary. Check if the real `struct Borrow` fixes it.
let override = _overrideLifetime(bit, copying: self)
- return IterableIterator_(_it: override)
+ return BorrowingIterator_(_it: override)
}
}
@available(SwiftStdlib 6.4, *)
-extension RigidDictionary.Indices.IterableIterator_: IterableIteratorProtocol_
+extension RigidDictionary.Indices.BorrowingIterator_: BorrowingIteratorProtocol_
where Key: ~Copyable, Value: ~Copyable {
public typealias Element_ = Element
@_lifetime(&self)
- public mutating func nextSpan_(maximumCount: Int) -> Span {
+ public mutating func nextSpan_(maxCount: Int) -> Span {
guard _it.advanceToOccupied() else { return .init() }
_current[0] = Element(_bucket: _it.currentBucket)
_it.advanceToNextBit()
diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Keys.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Keys.swift
index 49d5e1ce..539ef596 100644
--- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Keys.swift
+++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Keys.swift
@@ -15,19 +15,15 @@
@available(SwiftStdlib 5.0, *)
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
+ @_alwaysEmitIntoClient
+ public var keys: RigidSet {
+ borrow {
+ _keys
+ }
+ }
-#if false // This requires the BorrowAndMutateAccessors feature that isn't available yet.
-// @inlinable
-// public var keys: RigidSet {
-// borrow {
-// _keys
-// }
-// }
-#endif
-
- /// This is a stand-in for an eventual computed property with a `borrow`
- /// accessor. It is destined for deprecation once that feature becomes
- /// available.
+ // FIXME: Remove
+ @available(*, deprecated, renamed: "keys")
@_alwaysEmitIntoClient
public func withKeys(
_ body: (borrowing RigidSet) throws(E) -> R
diff --git a/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift b/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift
index 555248de..a62eb9bb 100644
--- a/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift
+++ b/Sources/BasicContainers/RigidSet/RigidSet+BorrowingSequence.swift
@@ -33,13 +33,13 @@ extension RigidSet: Iterable_ where Element: ~Copyable {
@inlinable
@_lifetime(borrow self)
- public borrowing func makeIterableIterator_() -> IterableIterator_ {
- IterableIterator_(_set: self)
+ public borrowing func makeBorrowingIterator_() -> BorrowingIterator_ {
+ BorrowingIterator_(_set: self)
}
@frozen
- public struct IterableIterator_:
- IterableIteratorProtocol_,
+ public struct BorrowingIterator_:
+ BorrowingIteratorProtocol_,
~Copyable,
~Escapable
{
@@ -70,11 +70,11 @@ extension RigidSet: Iterable_ where Element: ~Copyable {
}
@_alwaysEmitIntoClient
- @_lifetime(&self) // FIXME: This should be `@_lifetime(copy self)`
- public mutating func nextSpan_(maximumCount: Int) -> Span {
- precondition(maximumCount > 0, "maximumCount must be positive")
+ @_lifetime(&self)
+ public mutating func nextSpan_(maxCount: Int) -> Span {
+ precondition(maxCount > 0, "maxCount must be positive")
guard
- let next = _bucketIterator.nextOccupiedRegion(maximumCount: maximumCount)
+ let next = _bucketIterator.nextOccupiedRegion(maxCount: maxCount)
else {
return .init()
}
diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Deprecated.swift b/Sources/BasicContainers/RigidSet/RigidSet+Deprecated.swift
new file mode 100644
index 00000000..e328f5e0
--- /dev/null
+++ b/Sources/BasicContainers/RigidSet/RigidSet+Deprecated.swift
@@ -0,0 +1,67 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 COLLECTIONS_SINGLE_MODULE // Don't define these outside the Xcode project
+
+#if compiler(>=6.4) && UnstableHashedContainers
+@available(SwiftStdlib 5.0, *)
+extension RigidSet where Element: ~Copyable {
+ @available(*, deprecated, renamed: "insert(addingCount:initializingWith:)")
+ @_alwaysEmitIntoClient
+ public mutating func insert(
+ maximumCount: Int,
+ initializingWith initializer: (inout OutputSpan) throws(E) -> Void
+ ) throws(E) -> Void {
+ try self.insert(addingCount: maximumCount, initializingWith: initializer)
+ }
+
+ #if UnstableContainersPreview
+ @available(*, deprecated, renamed: "insert(addingCount:from:)")
+ @_alwaysEmitIntoClient
+ public mutating func insert<
+ E: Error,
+ P: Producer & ~Copyable & ~Escapable
+ >(
+ maximumCount: Int?,
+ from producer: inout P
+ ) throws(E)
+ where P.Element: ~Copyable
+ {
+ try self.insert(addingCount: maximumCount, from: &producer)
+ }
+ #endif
+
+#if UnstableContainersPreview
+ @available(*, deprecated, renamed: "insert(addingCount:from:)")
+ @_alwaysEmitIntoClient
+ public mutating func insert<
+ D: Drain & ~Copyable & ~Escapable
+ >(
+ maximumCount: Int?,
+ from drain: inout D
+ ) {
+ var remainder = drain.count
+ while remainder > 0 {
+ var span = drain.drainNext(maxCount: remainder)
+ guard !span.isEmpty else { break }
+ remainder &-= span.count
+ while let next = span.popFirst() {
+ self.insert(next)
+ }
+ }
+ }
+ #endif
+}
+#endif
+
+#endif
diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift b/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift
index d5796880..5deb0e5a 100644
--- a/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift
+++ b/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift
@@ -20,7 +20,7 @@ import ContainersPreview
#if compiler(>=6.4) && UnstableHashedContainers
@available(SwiftStdlib 5.0, *)
-extension RigidSet {
+extension RigidSet where Element: ~Copyable {
@inlinable
public func isTriviallyIdentical(to other: borrowing Self) -> Bool {
self._members == other._members
@@ -28,19 +28,19 @@ extension RigidSet {
}
}
-#if UnstableContainersPreview
@available(SwiftStdlib 6.4, *)
-extension RigidSet: Equatable {}
+extension RigidSet: Equatable where Element: ~Copyable {}
@available(SwiftStdlib 5.0, *)
-extension RigidSet {
+extension RigidSet where Element: ~Copyable {
@inlinable
public static func ==(left: borrowing Self, right: borrowing Self) -> Bool {
if left.isTriviallyIdentical(to: right) { return true }
guard left.count == right.count else { return false }
-
- var lit = left.makeIterableIterator_()
+
+ #if UnstableContainersPreview
+ var lit = left.makeBorrowingIterator_()
while true {
let l = lit.nextSpan_()
if l.isEmpty { break }
@@ -50,9 +50,14 @@ extension RigidSet {
i &+= 1
}
}
+ #else
+ var i = left.startIndex
+ while i != left.endIndex {
+ guard right.contains(left[i]) else { return false }
+ i = left.index(after: i)
+ }
+ #endif
return true
}
}
#endif
-
-#endif
diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift b/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift
index cc028880..058032a7 100644
--- a/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift
+++ b/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift
@@ -19,10 +19,10 @@ import ContainersPreview
#if compiler(>=6.4) && UnstableHashedContainers && UnstableContainersPreview
@available(SwiftStdlib 6.4, *)
-extension RigidSet: Hashable {}
+extension RigidSet: Hashable where Element: ~Copyable {}
@available(SwiftStdlib 5.0, *)
-extension RigidSet {
+extension RigidSet where Element: ~Copyable {
@inlinable
public func hash(into hasher: inout Hasher) {
// Generate a seed from a snapshot of the hasher. This makes members' hash
@@ -37,12 +37,12 @@ extension RigidSet {
public func _rawHashValue(seed: Int) -> Int {
#if UnstableContainersPreview
var hash = 0
- var it = self.makeIterableIterator_()
+ var it = self.makeBorrowingIterator_()
while true {
let next = it.nextSpan_()
var i = 0
while i < next.count {
- hash ^= next[i]._rawHashValue(seed: seed)
+ hash ^= next[unchecked: i]._rawHashValue(seed: seed)
i &+= 1
}
}
diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Index.swift b/Sources/BasicContainers/RigidSet/RigidSet+Index.swift
index 5fe511f1..2ee7675a 100644
--- a/Sources/BasicContainers/RigidSet/RigidSet+Index.swift
+++ b/Sources/BasicContainers/RigidSet/RigidSet+Index.swift
@@ -100,10 +100,10 @@ extension RigidSet where Element: ~Copyable {
@inlinable
public subscript(index: Index) -> Element {
- // FIXME: Use borrow accessor here
- unsafeAddress {
+ @_unsafeSelfDependentResult
+ borrow {
_checkItemIndex(index)
- return .init(_memberPtr(at: index._bucket))
+ return _memberPtr(at: index._bucket).pointee
}
}
}
diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift b/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift
index 7146c0b3..4bb4f0dd 100644
--- a/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift
+++ b/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift
@@ -46,7 +46,7 @@ extension RigidSet where Element: ~Copyable {
initializingWith initializer: (inout OutputSpan) throws(E) -> Void
) throws(E) {
self.init(capacity: capacity)
- try self.insert(maximumCount: capacity, initializingWith: initializer)
+ try self.insert(addingCount: capacity, initializingWith: initializer)
}
#if UnstableContainersPreview
@@ -61,7 +61,7 @@ extension RigidSet where Element: ~Copyable {
where P.Element: ~Copyable
{
self.init(capacity: capacity)
- try self.insert(maximumCount: capacity, from: &producer)
+ try self.insert(addingCount: capacity, from: &producer)
}
#endif
@@ -74,7 +74,7 @@ extension RigidSet where Element: ~Copyable {
from drain: inout D
) {
self.init(capacity: capacity)
- self.insert(maximumCount: capacity, from: &drain)
+ self.insert(addingCount: capacity, from: &drain)
}
#endif
}
@@ -82,6 +82,7 @@ extension RigidSet where Element: ~Copyable {
@available(SwiftStdlib 5.0, *)
extension RigidSet /* where Element: Copyable */ {
#if UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public init<
@@ -117,6 +118,7 @@ extension RigidSet /* where Element: Copyable */ {
}
#if UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public init<
@@ -130,6 +132,7 @@ extension RigidSet /* where Element: Copyable */ {
try self._insert(copying: contents)
}
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public init<
diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift
index 0fdd0c99..7bee7ad0 100644
--- a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift
+++ b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift
@@ -12,6 +12,7 @@
//===----------------------------------------------------------------------===//
#if !COLLECTIONS_SINGLE_MODULE
+import InternalCollectionsUtilities
import ContainersPreview
#endif
@@ -102,7 +103,8 @@ extension RigidSet where Element: ~Copyable {
/// Inserts the given element in the set if it is not already present.
///
/// - Parameter item: An element to insert into the set.
- /// - Returns:
+ /// - Returns: `item` if an equal member already exists in the set;
+ /// otherwise `nil`.
@inlinable
@discardableResult
public mutating func insert(
@@ -121,14 +123,14 @@ extension RigidSet where Element: ~Copyable {
extension RigidSet where Element: ~Copyable {
@_alwaysEmitIntoClient
public mutating func insert(
- maximumCount: Int,
+ addingCount newItemCount: Int,
initializingWith initializer: (inout OutputSpan) throws(E) -> Void
) throws(E) -> Void {
- precondition(maximumCount >= 0, "Cannot insert a negative number of items")
- guard maximumCount > 0 else { return }
- precondition(freeCapacity >= maximumCount, "RigidSet capacity overflow")
- var remainder = maximumCount
-
+ precondition(newItemCount >= 0, "Cannot insert a negative number of items")
+ guard newItemCount > 0 else { return }
+ precondition(freeCapacity >= newItemCount, "RigidSet capacity overflow")
+ var remainder = newItemCount
+
// FIXME: Instead of getting temporary buffers, we could place the new
// items in unoccupied buckets, then incrementally
// rehash them into their correct location, like the stdlib does for
@@ -171,13 +173,13 @@ extension RigidSet where Element: ~Copyable {
E: Error,
P: Producer & ~Copyable & ~Escapable
>(
- maximumCount: Int? = nil,
+ addingCount newItemCount: Int? = nil,
from producer: inout P
) throws(E)
where P.Element: ~Copyable
{
try self.insert(
- maximumCount: maximumCount ?? freeCapacity
+ addingCount: newItemCount ?? freeCapacity
) { target throws(E) in
while !target.isFull {
guard try producer.generate(into: &target) else { break }
@@ -186,23 +188,36 @@ extension RigidSet where Element: ~Copyable {
}
#endif
+#if UnstableContainersPreview
+ @_alwaysEmitIntoClient
+ public mutating func insert<
+ E: Error,
+ P: CountedProducer & ~Copyable & ~Escapable
+ >(
+ from producer: consuming P
+ ) throws(E) {
+ try self.insert(addingCount: producer.count, from: &producer)
+ try producer._expectEnd("Invalid CountedProducer")
+ }
+#endif
+
#if UnstableContainersPreview
@_alwaysEmitIntoClient
public mutating func insert<
D: Drain & ~Copyable & ~Escapable
>(
- maximumCount: Int? = nil,
- from drain: inout D
+ from drain: consuming D
) {
- var remainder = maximumCount ?? freeCapacity
+ var remainder = drain.count
while remainder > 0 {
- var span = drain.drainNext(maximumCount: remainder)
+ var span = drain.drainNext(maxCount: remainder)
guard !span.isEmpty else { break }
remainder &-= span.count
while let next = span.popFirst() {
self.insert(next)
}
}
+ drain._expectEnd("Invalid Drain")
}
#endif
}
@@ -221,6 +236,7 @@ extension RigidSet /* where Element: Copyable */ {
}
#if UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
package mutating func _insert<
S: Iterable_ & ~Copyable & ~Escapable
@@ -228,7 +244,7 @@ extension RigidSet /* where Element: Copyable */ {
copying items: borrowing S
) throws(S.Failure_)
where S.Element_ == Element {
- var it = items.makeIterableIterator_()
+ var it = items.makeBorrowingIterator_()
while true {
let span = try it.nextSpan_()
guard !span.isEmpty else { break }
@@ -238,6 +254,7 @@ extension RigidSet /* where Element: Copyable */ {
#endif
#if UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insert<
@@ -260,6 +277,7 @@ extension RigidSet /* where Element: Copyable */ {
}
#if UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insert<
diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift
index 7a66eddb..56027fe9 100644
--- a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift
+++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift
@@ -132,6 +132,7 @@ extension UniqueArray where Element: ~Copyable {
_storage.append(moving: &items)
}
+#if !UnstableContainersPreview
/// Appends the elements of a given array to the end of this array by moving
/// them between the containers. On return, the input array becomes empty, but
/// it is not destroyed, and it preserves its original storage capacity.
@@ -149,70 +150,19 @@ extension UniqueArray where Element: ~Copyable {
public mutating func append(
moving items: inout RigidArray
) {
- // FIXME: Remove this in favor of a generic algorithm over range-replaceable containers
_ensureFreeCapacity(items.count)
- _storage.append(moving: &items)
+ items.edit { source in
+ source.withUnsafeMutableBufferPointer { buffer, count in
+ _storage.append(moving: buffer._extracting(first: count))
+ count = 0
+ }
+ }
}
+#endif
}
@available(SwiftStdlib 5.0, *)
extension UniqueArray where Element: ~Copyable {
-#if UnstableContainersPreview
- /// Appends the elements of a given container to the end of this array by
- /// consuming the source container.
- ///
- /// If the target array does not have sufficient capacity to hold all items
- /// in the source array, then this automatically grows the target array's
- /// capacity, using a geometric growth rate.
- ///
- /// - Parameters:
- /// - items: An array whose items to move to the end of this array.
- ///
- /// - Complexity: O(`items.count`)
- @_alwaysEmitIntoClient
- public mutating func append(
- consuming items: consuming RigidArray
- ) {
- // FIXME: Remove this in favor of a generic algorithm over consumable containers
- var items = items
- self.append(moving: &items)
- }
-#endif
-
-#if compiler(>=6.4) && UnstableContainersPreview
- /// 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 & ~Copyable & ~Escapable
- >(
- addingCount newItemCount: Int,
- from producer: inout P
- ) throws(E)
- where P.Element: ~Copyable
- {
- _ensureFreeCapacity(newItemCount)
- try _storage.append(addingCount: newItemCount, from: &producer)
- }
-#endif
#if compiler(>=6.4) && UnstableContainersPreview
/// Appends all the items generated by a producer to the end of this deque.
@@ -308,6 +258,7 @@ extension UniqueArray {
}
#if compiler(>=6.4) && UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@inlinable
internal mutating func _append<
Source: Iterable_ & ~Copyable & ~Escapable
@@ -316,7 +267,7 @@ extension UniqueArray {
) throws(Source.Failure_)
where Source.Element_ == Element {
_ensureFreeCapacity(newElements.underestimatedCount_)
- var it = newElements.makeIterableIterator_()
+ var it = newElements.makeBorrowingIterator_()
while true {
let span = try it.nextSpan_()
if span.isEmpty { break }
@@ -341,6 +292,7 @@ extension UniqueArray {
///
/// - Complexity: O(`newElements.count`), when amortized over many invocations
/// over the same array.
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func append<
@@ -396,6 +348,7 @@ extension UniqueArray {
///
/// - Complexity: O(`newElements.count`), when amortized over many invocations
/// over the same array.
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func append<
diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift
index 01364e04..8b848901 100644
--- a/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift
+++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Consumption.swift
@@ -117,7 +117,7 @@ extension UniqueArray where Element: ~Copyable {
#endif
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 6.4, *)
+@available(SwiftStdlib 5.0, *)
extension UniqueArray where Element: ~Copyable {
public typealias SubrangeConsumer = RigidArray.SubrangeConsumer
diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift
index c314324e..53116a7c 100644
--- a/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift
+++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Container.swift
@@ -19,32 +19,45 @@ import ContainersPreview
#if compiler(>=6.2)
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension UniqueArray: Iterable_ where Element: ~Copyable {
- public typealias IterableIterator_ = RigidArray.IterableIterator_
+ public typealias BorrowingIterator_ = Span.BorrowingIterator_
@inlinable
public var underestimatedCount_: Int { count }
@_alwaysEmitIntoClient
@inline(__always)
- public func makeIterableIterator_() -> IterableIterator_ {
- self._storage.makeIterableIterator_()
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ self._storage.makeBorrowingIterator_()
}
}
#endif
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
-extension UniqueArray: Container where Element: ~Copyable {}
+@available(SwiftStdlib 6.4, *)
+extension UniqueArray: Container where Element: ~Copyable {
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func makeBorrowingIterator(
+ from start: Index, to end: Index
+ ) -> BorrowingIterator_ {
+ _storage.makeBorrowingIterator(from: start, to: end)
+ }
-@available(SwiftStdlib 5.0, *)
+ @_alwaysEmitIntoClient
+ public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index {
+ _storage.currentIndex(of: iterator)
+ }
+}
+
+@available(SwiftStdlib 6.4, *)
extension UniqueArray: BidirectionalContainer where Element: ~Copyable {}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension UniqueArray: RandomAccessContainer where Element: ~Copyable {}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension UniqueArray: MutableContainer where Element: ~Copyable {}
#if compiler(>=6.4)
@@ -104,6 +117,27 @@ extension UniqueArray where Element: ~Copyable {
@inline(__always)
public var indices: Range { _storage.indices }
+#if compiler(>=6.4)
+ /// Accesses the element at the specified position.
+ ///
+ /// - Parameter position: The position of the element to access.
+ /// The position must be a valid index of the array that is not equal
+ /// to the `endIndex` property.
+ ///
+ /// - Complexity: O(1)
+ @inlinable
+ public subscript(position: Int) -> Element {
+ @inline(__always)
+ borrow {
+ _storage[position]
+ }
+ @inline(__always)
+ @_unsafeSelfDependentResult // FIXME: Why is this necessary?
+ mutate {
+ &_storage[position]
+ }
+ }
+#else
/// Accesses the element at the specified position.
///
/// - Parameter position: The position of the element to access.
@@ -122,6 +156,7 @@ extension UniqueArray where Element: ~Copyable {
_storage._mutablePtr(to: position)
}
}
+#endif
}
@available(SwiftStdlib 5.0, *)
@@ -283,7 +318,7 @@ extension UniqueArray where Element: ~Copyable {
/// Return a span over the array's storage that begins with the element at
/// the given index, and extends to the end of the contiguous storage chunk
- /// that contains it, but no more than `maximumCount` items.
+ /// that contains it, but no more than `maxCount` items.
///
/// On return, the index is updated to address the next item following the
/// end of the returned span.
@@ -294,30 +329,30 @@ extension UniqueArray where Element: ~Copyable {
///
/// var index = items.startIndex
/// while true {
- /// let span = items.nextSpan(after: &index, maximumCount: 4)
+ /// let span = items.nextSpan(after: &index, maxCount: 4)
/// if span.isEmpty { break }
/// // Process items in `span`
/// }
///
- /// The `maximumCount` argument gives the caller control over the number of
+ /// The `maxCount` argument gives the caller control over the number of
/// items it receives from the iterator. This lets the caller avoid getting
/// more elements than it would be able to immediately process, which would
/// significantly complicate container use.
///
/// If the caller is able to process any number available items, it can signal
- /// that by passing `Int.max` as the `maximumCount`, or simply by calling the
+ /// that by passing `Int.max` as the `maxCount`, or simply by calling the
/// `nexSpan(after:)` method, which does precisely that. This is frequently
/// the case when the caller simply wants to iterate over the entire
/// container in a single loop.
///
- /// `maximumCount` sets an upper bound. To read a specific number of items,
+ /// `maxCount` sets an upper bound. To read a specific number of items,
/// the caller usually needs to invoke `nextSpan` in a loop:
///
/// var items: some Container
/// var index = items.startIndex
/// var remainder = numberOfItemsToRead
/// while remainder > 0 {
- /// let next = items.nextSpan(after: &index, maximumCount: remainder)
+ /// let next = items.nextSpan(after: &index, maxCount: remainder)
/// guard !next.isEmpty else {
/// // Container does not have enough items
/// break
@@ -340,10 +375,10 @@ extension UniqueArray where Element: ~Copyable {
/// - 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.
- /// - Parameter maximumCount: The maximum number of items the caller is able
- /// to process immediately. `maximumCount` must be greater than zero.
+ /// - Parameter maxCount: The maximum number of items the caller is able
+ /// to process immediately. `maxCount` must be greater than zero.
/// If you are able to process an arbitrary number of items, set
- /// `maximumCount` to `Int.max`, or call the `nextSpan(after:)` method.
+ /// `maxCount` to `Int.max`, or call the `nextSpan(after:)` method.
/// - 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
@@ -352,25 +387,49 @@ extension UniqueArray where Element: ~Copyable {
@inlinable
@_lifetime(borrow self)
public func nextSpan(
- after index: inout Int, maximumCount: Int
+ after index: inout Int
) -> Span {
- _storage.nextSpan(after: &index, maximumCount: maximumCount)
+ _storage.nextSpan(after: &index)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Int, maxCount: Int, limitedBy limit: Int
+ ) -> Span {
+ _storage.nextSpan(after: &index, maxCount: maxCount, limitedBy: limit)
}
@inlinable
@_lifetime(&self)
public mutating func nextMutableSpan(
- after index: inout Int, maximumCount: Int
+ after index: inout Int, maxCount: Int, limitedBy limit: Int
) -> MutableSpan {
- _storage.nextMutableSpan(after: &index, maximumCount: maximumCount)
+ _storage.nextMutableSpan(after: &index, maxCount: maxCount, limitedBy: limit)
}
- @inlinable
+ @_alwaysEmitIntoClient
+ public func spanBoundary(
+ before index: Index
+ ) -> (index: Index, distance: Int) {
+ _storage.spanBoundary(before: index)
+ }
+
+ @_alwaysEmitIntoClient
+ public func spanBoundary(
+ before index: Index, maxDistance: Int, limitedBy limit: Index
+ ) -> (index: Index, distance: Int) {
+ _storage.spanBoundary(
+ before: index, maxDistance: maxDistance, limitedBy: limit)
+ }
+
+ @_alwaysEmitIntoClient
@_lifetime(borrow self)
public func previousSpan(
- before index: inout Int, maximumCount: Int
+ before index: inout Int, maxCount: Int
) -> Span {
- _storage.previousSpan(before: &index, maximumCount: maximumCount)
+ // FIXME: Remove this in favor of the BidirectionalContainer algorithm.
+ _storage.previousSpan(before: &index, maxCount: maxCount)
}
}
diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift
index 8a7b7028..9142329a 100644
--- a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift
+++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift
@@ -15,6 +15,39 @@
@available(SwiftStdlib 5.0, *)
extension UniqueArray where Element: ~Copyable {
+ @available(*, deprecated, renamed: "nextSpan(after:maxCount:)")
+ @inlinable
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Int, maximumCount: Int
+ ) -> Span {
+ self.nextSpan(
+ after: &index,
+ maxCount: maximumCount,
+ limitedBy: self.endIndex)
+ }
+
+ @available(*, deprecated, renamed: "nextMutableSpan(after:maxCount:)")
+ @inlinable
+ @_lifetime(&self)
+ public mutating func nextMutableSpan(
+ after index: inout Int, maximumCount: Int
+ ) -> MutableSpan {
+ self.nextMutableSpan(
+ after: &index,
+ maxCount: maximumCount,
+ limitedBy: self.endIndex)
+ }
+
+ @available(*, deprecated, renamed: "previousSpan(before:maxCount:)")
+ @inlinable
+ @_lifetime(borrow self)
+ public func previousSpan(
+ before index: inout Int, maximumCount: Int
+ ) -> Span {
+ self.previousSpan(before: &index, maxCount: maximumCount)
+ }
+
/// Initializes a new unique array with the specified capacity and no elements.
@available(*, deprecated, renamed: "init(minimumCapacity:)")
@inlinable
diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Equatable.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Equatable.swift
index a87f386d..c61d4f85 100644
--- a/Sources/BasicContainers/UniqueArray/UniqueArray+Equatable.swift
+++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Equatable.swift
@@ -24,9 +24,13 @@ extension UniqueArray where Element: ~Copyable {
}
}
-#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+#if compiler(>=6.4)
+@available(SwiftStdlib 6.4, *)
extension UniqueArray: Equatable where Element: Equatable & ~Copyable {
+}
+
+@available(SwiftStdlib 5.0, *)
+extension UniqueArray where Element: Equatable & ~Copyable {
@inlinable
public static func ==(
left: borrowing Self,
diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Hashable.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Hashable.swift
index c2584c07..646cbc12 100644
--- a/Sources/BasicContainers/UniqueArray/UniqueArray+Hashable.swift
+++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Hashable.swift
@@ -13,16 +13,30 @@
#if compiler(>=6.2)
-@available(SwiftStdlib 5.0, *)
-extension UniqueArray /*: Hashable */ where Element: Hashable /* & ~Copyable */ {
- @inlinable
- public func hash(into hasher: inout Hasher) {
- hasher.combine(self.count)
- let span = self.span
- for i in 0 ..< count {
- hasher.combine(span[unchecked: i])
- }
- }
+#if !COLLECTIONS_SINGLE_MODULE
+import InternalCollectionsUtilities
+#endif
+
+#if compiler(>=6.4)
+@available(SwiftStdlib 6.4, *)
+extension UniqueArray: Hashable where Element: Hashable & ~Copyable {
}
+@available(SwiftStdlib 5.0, *)
+extension UniqueArray where Element: Hashable & ~Copyable {
+ @inlinable
+ public func hash(into hasher: inout Hasher) {
+ self._storage.hash(into: &hasher)
+ }
+}
+#else
+@available(SwiftStdlib 5.0, *)
+extension UniqueArray where Element: Hashable {
+ @inlinable
+ public func hash(into hasher: inout Hasher) {
+ self._storage.hash(into: &hasher)
+ }
+}
+#endif
+
#endif
diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Initializers.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Initializers.swift
index 678933f1..ce4ce62a 100644
--- a/Sources/BasicContainers/UniqueArray/UniqueArray+Initializers.swift
+++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Initializers.swift
@@ -94,6 +94,7 @@ extension UniqueArray /*where Element: Copyable*/ {
/// just enough capacity to store the contents.
/// - contents: A sequence whose contents to copy into the new array.
/// The sequence must not contain more than `capacity` elements.
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public init(
@@ -131,6 +132,7 @@ extension UniqueArray /*where Element: Copyable*/ {
/// - capacity: The storage capacity of the new array, or nil to allocate
/// just enough capacity to store the contents.
/// - contents: The container whose contents to copy into the new array.
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public init>(
diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift
index 83d19688..00f052a0 100644
--- a/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift
+++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift
@@ -144,6 +144,7 @@ extension UniqueArray where Element: ~Copyable {
moving items: inout InputSpan,
at index: Int
) {
+ // FIXME: Remove when InputSpan starts conforming to RangeReplaceableContainer
_ensureFreeCapacity(items.count)
_storage.insert(moving: &items, at: index)
}
@@ -171,10 +172,12 @@ extension UniqueArray where Element: ~Copyable {
moving items: inout OutputSpan,
at index: Int
) {
+ // FIXME: Remove when OutputSpan starts conforming to RangeReplaceableContainer
_ensureFreeCapacity(items.count)
_storage.insert(moving: &items, at: index)
}
+#if !UnstableContainersPreview
/// Inserts the elements of a given array into the given position in this
/// array by moving them between the containers. On return, the input array
/// becomes empty, but it is not destroyed, and it preserves its original
@@ -186,6 +189,7 @@ extension UniqueArray where Element: ~Copyable {
///
/// - Parameters:
/// - items: An array whose contents to move into `self`.
+ /// - index: The position in `self` at which to insert the new items.
///
/// - Complexity: O(`self.count` + `items.count`)
@_alwaysEmitIntoClient
@@ -197,88 +201,9 @@ extension UniqueArray where Element: ~Copyable {
_ensureFreeCapacity(items.count)
_storage.insert(moving: &items, at: index)
}
-}
-
-@available(SwiftStdlib 5.0, *)
-extension UniqueArray where Element: ~Copyable {
-#if UnstableContainersPreview
- /// Inserts the elements of a given array into the given position in this
- /// array by consuming the source container.
- ///
- /// If the array does not have sufficient capacity to hold all elements,
- /// then this reallocates storage to extend its capacity, using a geometric
- /// growth rate.
- ///
- /// - Parameters:
- /// - items: A fully initialized buffer whose contents to move into
- /// the array.
- ///
- /// - Complexity: O(`self.count` + `items.count`)
- @_alwaysEmitIntoClient
- public mutating func insert(
- consuming items: consuming RigidArray,
- at index: Int
- ) {
- // FIXME: Remove this in favor of a generic algorithm over consumable containers
- // FIXME: Avoid moving the subsequent elements twice.
- _ensureFreeCapacity(items.count)
- _storage.insert(consuming: items, at: index)
- }
#endif
}
-@available(SwiftStdlib 5.0, *)
-extension UniqueArray where Element: ~Copyable {
-#if compiler(>=6.4) && UnstableContainersPreview
- /// 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 & ~Copyable & ~Escapable
- >(
- addingCount newItemCount: Int,
- from producer: inout P,
- at index: Int
- ) throws(E)
- where P.Element: ~Copyable
- {
- 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 {
/// Copies the elements of a fully initialized buffer pointer into this
@@ -368,42 +293,6 @@ extension UniqueArray {
_storage.insert(copying: newElements, at: index)
}
-#if compiler(>=6.4) && UnstableContainersPreview
- /// Copies the elements of a container into this array at the specified
- /// position.
- ///
- /// The new elements are inserted before the element currently at the
- /// specified index. If you pass the array's `endIndex` as the `index`
- /// parameter, then the new elements are appended to the end of the array.
- ///
- /// All existing elements at or following the specified position are moved to
- /// make room for the new item.
- ///
- /// If the array does not have sufficient capacity to hold enough elements,
- /// then this reallocates the array's storage to extend its capacity, using a
- /// geometric growth rate.
- ///
- /// - Parameters:
- /// - newElements: The new elements to insert into the array.
- /// - index: The position at which to insert the new elements. It must be
- /// a valid index of the array.
- ///
- /// - Complexity: O(*n* + *m*), where *n* is count of this array and
- /// *m* is the count of `newElements`.
- @_alwaysEmitIntoClient
- @inline(__always)
- public mutating func insert<
- C: Container & ~Copyable & ~Escapable
- >(
- copying newElements: borrowing C, at index: Int
- ) {
- // FIXME: Avoid moving the subsequent elements twice.
- let c = newElements.count
- _ensureFreeCapacity(c)
- _storage._insertContainer(at: index, copying: newElements, newCount: c)
- }
-#endif
-
/// Copies the elements of a collection into this array at the specified
/// position.
///
@@ -428,48 +317,15 @@ extension UniqueArray {
public mutating func insert(
copying newElements: some Collection, at index: Int
) {
+ // FIXME: Remove this -- RangeReplaceContainer already has this algorithm.
+ // (Note that this would be source breaking while RRC lives in the separate
+ // ContainersPreview module.)
// FIXME: Avoid moving the subsequent elements twice.
let newCount = newElements.count
_ensureFreeCapacity(newCount)
_storage._insertCollection(
- at: index, copying: newElements, newCount: newCount)
+ addingCount: newCount, copying: newElements, at: index)
}
-
-#if compiler(>=6.4) && UnstableContainersPreview
- /// Copies the elements of a container into this array at the specified
- /// position.
- ///
- /// The new elements are inserted before the element currently at the
- /// specified index. If you pass the array's `endIndex` as the `index`
- /// parameter, then the new elements are appended to the end of the array.
- ///
- /// All existing elements at or following the specified position are moved to
- /// make room for the new item.
- ///
- /// If the array does not have sufficient capacity to hold enough elements,
- /// then this reallocates the array's storage to extend its capacity, using a
- /// geometric growth rate.
- ///
- /// - Parameters:
- /// - newElements: The new elements to insert into the array.
- /// - index: The position at which to insert the new elements. It must be
- /// a valid index of the array.
- ///
- /// - Complexity: O(*n* + *m*), where *n* is count of this array and
- /// *m* is the count of `newElements`.
- @_alwaysEmitIntoClient
- @inline(__always)
- public mutating func insert<
- C: Container & Collection
- >(
- copying newElements: borrowing C, at index: Int
- ) {
- // FIXME: Avoid moving the subsequent elements twice.
- let c = newElements.count
- _ensureFreeCapacity(c)
- _storage._insertContainer(at: index, copying: newElements, newCount: c)
- }
-#endif
}
#endif
diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift
index e910461b..deaa5bc1 100644
--- a/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift
+++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Removals.swift
@@ -103,7 +103,7 @@ extension UniqueArray where Element: ~Copyable {
/// - Complexity: O(`self.count`)
@_alwaysEmitIntoClient
public mutating func removeSubrange(_ bounds: some RangeExpression) {
- // FIXME: Remove this in favor of a standard algorithm.
+ // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm.
removeSubrange(bounds.relative(to: indices))
}
}
@@ -118,6 +118,7 @@ extension UniqueArray where Element: ~Copyable {
/// - Complexity: O(1)
@_alwaysEmitIntoClient
public mutating func popLast() -> Element? {
+ // FIXME: Remove this in favor of the RangeReplaceableContainer algorithm.
if isEmpty { return nil }
return removeLast()
}
diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift
index 2b6c91b5..9c6603e9 100644
--- a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift
+++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift
@@ -346,7 +346,7 @@ extension UniqueArray where Element: ~Copyable {
@available(SwiftStdlib 5.0, *)
extension UniqueArray where Element: ~Copyable {
#if compiler(>=6.4) && UnstableContainersPreview
- /// Replaces the specified range of elements by at most `maximumCount` items
+ /// Replaces the specified range of elements by at most `maxCount` items
/// generated by a producer.
///
/// This method has the effect of removing the specified range of elements
@@ -367,8 +367,8 @@ extension UniqueArray 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 `maxCount`, or the producer hitting its end, or
+ /// throwing an error. If the producer has more than `maxCount` items left in
/// its underlying sequence, then extra items remain available after this
/// method returns.
///
@@ -551,6 +551,7 @@ extension UniqueArray {
///
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
+ @available(SwiftStdlib 6.4, *)
@inlinable
@inline(__always)
public mutating func replace<
@@ -641,6 +642,7 @@ extension UniqueArray {
///
/// - Complexity: O(*n* + *m*), where *n* is count of this array and
/// *m* is the count of `newElements`.
+ @available(SwiftStdlib 6.4, *)
@inlinable
@inline(__always)
public mutating func replace<
diff --git a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Keys.swift b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Keys.swift
index b09a0c45..324f7b33 100644
--- a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Keys.swift
+++ b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Keys.swift
@@ -15,19 +15,15 @@
@available(SwiftStdlib 5.0, *)
extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
+ @_alwaysEmitIntoClient
+ public var keys: RigidSet {
+ borrow {
+ _storage.keys
+ }
+ }
-#if false // This requires the BorrowAndMutateAccessors feature that isn't available yet.
-// @inlinable
-// public var keys: RigidSet {
-// borrow {
-// _storage.keys
-// }
-// }
-#endif
-
- /// This is a stand-in for an eventual computed property with a `borrow`
- /// accessor. It is destined for deprecation once that feature becomes
- /// available.
+ // FIXME: Remove
+ @available(*, deprecated, renamed: "keys")
@_alwaysEmitIntoClient
public func withKeys(
_ body: (borrowing RigidSet) throws(E) -> R
diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+BorrowingSequence.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+BorrowingSequence.swift
index 549c415e..9cc21b7a 100644
--- a/Sources/BasicContainers/UniqueSet/UniqueSet+BorrowingSequence.swift
+++ b/Sources/BasicContainers/UniqueSet/UniqueSet+BorrowingSequence.swift
@@ -21,7 +21,7 @@ import ContainersPreview
@available(SwiftStdlib 5.0, *)
extension UniqueSet: Iterable_ where Element: ~Copyable {
public typealias Element_ = Element
- public typealias IterableIterator_ = RigidSet.IterableIterator_
+ public typealias BorrowingIterator_ = RigidSet.BorrowingIterator_
@inlinable
public var underestimatedCount_: Int { count }
@@ -35,8 +35,8 @@ extension UniqueSet: Iterable_ where Element: ~Copyable {
@inlinable
@_lifetime(borrow self)
- public borrowing func makeIterableIterator_() -> IterableIterator_ {
- IterableIterator_(_set: _storage)
+ public borrowing func makeBorrowingIterator_() -> BorrowingIterator_ {
+ BorrowingIterator_(_set: _storage)
}
}
#endif
diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Deprecations.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Deprecations.swift
new file mode 100644
index 00000000..08823fe8
--- /dev/null
+++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Deprecations.swift
@@ -0,0 +1,30 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 COLLECTIONS_SINGLE_MODULE // Don't define these outside the Xcode project
+
+#if compiler(>=6.4) && UnstableHashedContainers
+@available(SwiftStdlib 5.0, *)
+extension UniqueSet where Element: ~Copyable {
+ @available(*, deprecated, renamed: "insert(addingCount:initializingWith:)")
+ @_alwaysEmitIntoClient
+ public mutating func insert(
+ maximumCount: Int,
+ initializingWith initializer: (inout OutputSpan) throws(E) -> Void
+ ) throws(E) -> Void {
+ try self.insert(addingCount: maximumCount, initializingWith: initializer)
+ }
+}
+#endif
+
+#endif
diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Equatable.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Equatable.swift
index 3bd9e660..6dcd462a 100644
--- a/Sources/BasicContainers/UniqueSet/UniqueSet+Equatable.swift
+++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Equatable.swift
@@ -20,7 +20,7 @@ import ContainersPreview
#if compiler(>=6.4) && UnstableHashedContainers && UnstableContainersPreview
@available(SwiftStdlib 5.0, *)
-extension UniqueSet {
+extension UniqueSet where Element: ~Copyable {
@inlinable
@inline(__always)
public func isTriviallyIdentical(to other: borrowing Self) -> Bool {
@@ -29,10 +29,10 @@ extension UniqueSet {
}
@available(SwiftStdlib 6.4, *)
-extension UniqueSet: Equatable {}
+extension UniqueSet: Equatable where Element: ~Copyable {}
@available(SwiftStdlib 5.0, *)
-extension UniqueSet {
+extension UniqueSet where Element: ~Copyable {
@inlinable
@inline(__always)
public static func ==(left: borrowing Self, right: borrowing Self) -> Bool {
diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Hashable.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Hashable.swift
index 61468f5a..62a1f956 100644
--- a/Sources/BasicContainers/UniqueSet/UniqueSet+Hashable.swift
+++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Hashable.swift
@@ -19,10 +19,10 @@ import ContainersPreview
#if compiler(>=6.4) && UnstableHashedContainers && UnstableContainersPreview
@available(SwiftStdlib 6.4, *)
-extension UniqueSet: Hashable {}
+extension UniqueSet: Hashable where Element: ~Copyable {}
@available(SwiftStdlib 5.0, *)
-extension UniqueSet {
+extension UniqueSet where Element: ~Copyable {
@inlinable
public func hash(into hasher: inout Hasher) {
_storage.hash(into: &hasher)
diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift
index 4dc1f451..2d48fb6d 100644
--- a/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift
+++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift
@@ -59,10 +59,8 @@ extension UniqueSet where Element: ~Copyable {
@inlinable
public subscript(index: Index) -> Element {
- // FIXME: Use borrow accessor here
- unsafeAddress {
- _checkItemIndex(index)
- return .init(_storage._memberPtr(at: index._bucket))
+ borrow {
+ _storage[index]
}
}
}
diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift
index 03ffcf4f..a4b65a36 100644
--- a/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift
+++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift
@@ -46,7 +46,7 @@ extension UniqueSet where Element: ~Copyable {
) throws(E) {
self.init(minimumCapacity: minimumCapacity)
try self.insert(
- maximumCount: minimumCapacity,
+ addingCount: minimumCapacity,
initializingWith: initializer)
}
@@ -75,6 +75,7 @@ extension UniqueSet where Element: ~Copyable {
extension UniqueSet where Element: Copyable {
#if UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
public init<
S: Iterable_ & ~Copyable & ~Escapable
@@ -94,6 +95,7 @@ extension UniqueSet where Element: Copyable {
}
#if UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
public init<
S: Iterable_ & Sequence
diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift
index 1a9d235b..ac095a70 100644
--- a/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift
+++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift
@@ -56,7 +56,8 @@ extension UniqueSet where Element: ~Copyable {
/// Inserts the given element in the set if it is not already present.
///
/// - Parameter item: An element to insert into the set.
- /// - Returns:
+ /// - Returns: `item` if an equal member already exists in the set;
+ /// otherwise `nil`.
@inlinable
@discardableResult
public mutating func insert(
@@ -71,12 +72,12 @@ extension UniqueSet where Element: ~Copyable {
extension UniqueSet where Element: ~Copyable {
@_alwaysEmitIntoClient
public mutating func insert(
- maximumCount: Int,
+ addingCount newItemCount: Int,
initializingWith initializer: (inout OutputSpan) throws(E) -> Void
) throws(E) -> Void {
- _ensureFreeCapacity(maximumCount)
+ _ensureFreeCapacity(newItemCount)
try _storage.insert(
- maximumCount: maximumCount, initializingWith: initializer)
+ addingCount: newItemCount, initializingWith: initializer)
}
#if UnstableContainersPreview
@@ -92,7 +93,7 @@ extension UniqueSet where Element: ~Copyable {
var done = false
while !done {
_ensureFreeCapacity(Swift.max(producer.underestimatedCount, 1))
- try self.insert(maximumCount: self.freeCapacity) { target throws(E) in
+ try self.insert(addingCount: self.freeCapacity) { target throws(E) in
while !target.isFull, !done {
done = try !producer.generate(into: &target)
}
@@ -130,6 +131,7 @@ extension UniqueSet /* where Element: Copyable */ {
}
#if UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
package mutating func _insert<
S: Iterable_ & ~Copyable & ~Escapable
@@ -138,7 +140,7 @@ extension UniqueSet /* where Element: Copyable */ {
) throws(S.Failure_)
where S.Element_ == Element {
_ensureFreeCapacity(items.underestimatedCount_)
- var it = items.makeIterableIterator_()
+ var it = items.makeBorrowingIterator_()
while true {
let span = try it.nextSpan_()
guard !span.isEmpty else { break }
@@ -148,6 +150,7 @@ extension UniqueSet /* where Element: Copyable */ {
#endif
#if UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insert<
@@ -170,6 +173,7 @@ extension UniqueSet /* where Element: Copyable */ {
}
#if UnstableContainersPreview
+ @available(SwiftStdlib 6.4, *)
@_alwaysEmitIntoClient
@inline(__always)
public mutating func insert<
diff --git a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift
index 5b6c7610..715bb5ab 100644
--- a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift
+++ b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift
@@ -87,15 +87,15 @@ internal struct _ChunkedBitsBackwardIterator {
extension IteratorProtocol where Element == Bool {
mutating func _nextChunk(
- maximumCount: UInt = _Word._capacity
+ maxCount: UInt = _Word._capacity
) -> (bits: _Word, count: UInt) {
- assert(maximumCount <= _Word.capacity)
+ assert(maxCount <= _Word.capacity)
var bits = _Word.empty
var c: UInt = 0
while let v = next() {
if v { bits.insert(c) }
c += 1
- if c == maximumCount { break }
+ if c == maxCount { break }
}
return (bits, c)
}
diff --git a/Sources/BitCollections/BitArray/BitArray+Copy.swift b/Sources/BitCollections/BitArray/BitArray+Copy.swift
index 2cc80b73..f40faecb 100644
--- a/Sources/BitCollections/BitArray/BitArray+Copy.swift
+++ b/Sources/BitCollections/BitArray/BitArray+Copy.swift
@@ -162,7 +162,7 @@ extension BitArray._UnsafeHandle {
var it = source.makeIterator()
if pos.bit > 0 {
let (bits, count) = it._nextChunk(
- maximumCount: _Word._capacity - pos.bit)
+ maxCount: _Word._capacity - pos.bit)
_copy(bits: bits, count: count, to: pos)
pos.value += count
}
diff --git a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift
index ca1e319e..7cf20ac8 100644
--- a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift
+++ b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift
@@ -285,7 +285,7 @@ extension BitArray {
var pos = _BitPosition(_count)
if pos.bit > 0 {
let (bits, count) = it._nextChunk(
- maximumCount: _Word._capacity - pos.bit)
+ maxCount: _Word._capacity - pos.bit)
guard count > 0 else { return }
_count += count
_update { $0._copy(bits: bits, count: count, to: pos) }
diff --git a/Sources/ContainersPreview/CMakeLists.txt b/Sources/ContainersPreview/CMakeLists.txt
index f703ddb1..35317ad1 100644
--- a/Sources/ContainersPreview/CMakeLists.txt
+++ b/Sources/ContainersPreview/CMakeLists.txt
@@ -25,9 +25,18 @@ else()
endif()
target_sources(${module_name} PRIVATE
- "Extensions/Optional+Extras.swift"
- "Extensions/OutputSpan+Extras.swift"
- "Extensions/TemporaryAllocation.swift"
+ "Conformances/Array+Iterable.swift"
+ "Conformances/ClosedRange+Iterable.swift"
+ "Conformances/InlineArray+Iterable.swift"
+ "Conformances/InputSpan+Container.swift"
+ "Conformances/InputSpan+Iterable.swift"
+ "Conformances/MutableSpan+Container.swift"
+ "Conformances/MutableSpan+Iterable.swift"
+ "Conformances/OutputSpan+Container.swift"
+ "Conformances/OutputSpan+Iterable.swift"
+ "Conformances/Range+Iterable.swift"
+ "Conformances/Span+Container.swift"
+ "Conformances/Span+Iterable.swift"
"Protocols/Container/BidirectionalContainer.swift"
"Protocols/Container/Container.swift"
"Protocols/Container/Container+Filter.swift"
@@ -40,18 +49,18 @@ target_sources(${module_name} PRIVATE
"Protocols/Container/RangeExpression2.swift"
"Protocols/Container/RangeReplaceableContainer.swift"
"Protocols/Container/Strideable+Limits.swift"
- "Protocols/IterableIteratorProtocol.swift"
- "Protocols/IterableIteratorProtocol+Copy.swift"
- "Protocols/IterableIteratorProtocol+ElementsEqual.swift"
- "Protocols/IterableIteratorProtocol+Filter.swift"
- "Protocols/IterableIteratorProtocol+Map.swift"
- "Protocols/IterableIteratorProtocol+MapError.swift"
- "Protocols/IterableIteratorProtocol+Reduce.swift"
- "Protocols/IterableIteratorProtocol+SpanwiseZip.swift"
+ "Protocols/BorrowingIteratorProtocol.swift"
+ "Protocols/BorrowingIteratorProtocol+Copy.swift"
+ "Protocols/BorrowingIteratorProtocol+ElementsEqual.swift"
+ "Protocols/BorrowingIteratorProtocol+Filter.swift"
+ "Protocols/BorrowingIteratorProtocol+Map.swift"
+ "Protocols/BorrowingIteratorProtocol+MapError.swift"
+ "Protocols/BorrowingIteratorProtocol+Reduce.swift"
+ "Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift"
"Protocols/Iterable.swift"
"Protocols/Iterable+Algorithms.swift"
- "Protocols/Iterable+Standard Conformances.swift"
"Protocols/Iterable+Utilities.swift"
+ "Protocols/CountedProducer.swift"
"Protocols/Drain.swift"
"Protocols/Drain+Map.swift"
"Protocols/Drain+Reduce.swift"
@@ -60,9 +69,10 @@ target_sources(${module_name} PRIVATE
"Protocols/Producer+Filter.swift"
"Protocols/Producer+Map.swift"
"Protocols/Producer+Reduce.swift"
+ "Protocols/Producer+Unfold.swift"
"Types/InputSpan.swift"
"Types/MutableRef.swift"
+ "Types/OutputSpan+Helpers.swift"
"Types/Shared.swift"
- "Types/SpanIterator.swift"
"Types/UniqueBox.swift"
)
diff --git a/Sources/ContainersPreview/Conformances/Array+Iterable.swift b/Sources/ContainersPreview/Conformances/Array+Iterable.swift
new file mode 100644
index 00000000..5d6f4b2b
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/Array+Iterable.swift
@@ -0,0 +1,31 @@
+//===----------------------------------------------------------------------===//
+//
+// 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) && UnstableContainersPreview
+
+@available(SwiftStdlib 6.4, *)
+extension Array: Iterable_ {
+ public typealias Element_ = Element
+ public typealias BorrowingIterator_ = Span.BorrowingIterator_
+
+ @inlinable
+ public var underestimatedCount_: Int { count }
+
+ @_lifetime(borrow self)
+ @inlinable
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ BorrowingIterator_(self.span)
+ }
+}
+
+#endif
diff --git a/Sources/ContainersPreview/Conformances/ClosedRange+Iterable.swift b/Sources/ContainersPreview/Conformances/ClosedRange+Iterable.swift
new file mode 100644
index 00000000..c4e199b2
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/ClosedRange+Iterable.swift
@@ -0,0 +1,69 @@
+//===----------------------------------------------------------------------===//
+//
+// 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) && UnstableContainersPreview
+
+@available(SwiftStdlib 6.2, *)
+extension ClosedRange: Iterable_
+where Bound: Strideable, Bound.Stride: SignedInteger
+{
+ public typealias Element_ = Bound
+
+ @frozen
+ public struct BorrowingIterator_: BorrowingIteratorProtocol_, ~Copyable {
+ @usableFromInline
+ internal var _current: InlineArray<1, Bound>
+
+ @usableFromInline
+ internal var _last: Bound
+
+ @usableFromInline
+ internal var _progress: Bool
+
+ @inlinable
+ internal init(_ base: ClosedRange) {
+ self._current = .init(repeating: base.lowerBound)
+ self._last = base.upperBound
+ self._progress = false
+ }
+ @inlinable
+ @_lifetime(&self)
+ public mutating func nextSpan_(maxCount: Int) -> Span {
+ if _progress {
+ _current[0] = _current[0].advanced(by: 1)
+ }
+ guard _current[0] <= _last else {
+ _progress = false
+ return .init()
+ }
+ _progress = true
+ return _current.span
+ }
+ }
+
+ @inlinable
+ public var underestimatedCount_: Int {
+ guard let distance = Int(exactly: lowerBound.distance(to: upperBound))
+ else { return 0 }
+ let advanced = distance.addingReportingOverflow(1)
+ guard !advanced.overflow else { return 0 }
+ return advanced.partialValue
+ }
+
+ @inlinable
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ BorrowingIterator_(self)
+ }
+}
+
+#endif
diff --git a/Sources/ContainersPreview/Conformances/InlineArray+Iterable.swift b/Sources/ContainersPreview/Conformances/InlineArray+Iterable.swift
new file mode 100644
index 00000000..b503e97d
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/InlineArray+Iterable.swift
@@ -0,0 +1,31 @@
+//===----------------------------------------------------------------------===//
+//
+// 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) && UnstableContainersPreview
+
+@available(SwiftStdlib 6.4, *)
+extension InlineArray: Iterable_ where Element: ~Copyable {
+ public typealias Element_ = Element
+ public typealias BorrowingIterator_ = Span.BorrowingIterator_
+
+ @inlinable
+ public var underestimatedCount_: Int { count }
+
+ @_lifetime(borrow self)
+ @inlinable
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ BorrowingIterator_(self.span)
+ }
+}
+
+#endif
diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift
new file mode 100644
index 00000000..6a88e605
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift
@@ -0,0 +1,100 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the Swift Collections open source project
+//
+// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+//
+// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
+//
+//===----------------------------------------------------------------------===//
+
+#if !COLLECTIONS_SINGLE_MODULE
+import InternalCollectionsUtilities
+#endif
+
+#if compiler(>=6.4) && UnstableContainersPreview
+@available(SwiftStdlib 6.4, *)
+extension InputSpan: RandomAccessContainer, MutableContainer
+where Element: ~Copyable
+{
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func makeBorrowingIterator(
+ from start: Index,
+ to end: Index
+ ) -> BorrowingIterator_ {
+ let span = self.span
+ let it = span.makeBorrowingIterator(from: start, to: end)
+ // FIXME: `it` is borrowing `span`, not self
+ return _overrideLifetime(it, borrowing: self)
+ }
+
+ @_alwaysEmitIntoClient
+ public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index {
+ self.span.currentIndex(of: iterator)
+ }
+}
+#endif
+
+#if compiler(>=6.2) && UnstableContainersPreview
+@available(SwiftStdlib 5.0, *)
+extension InputSpan where Element: ~Copyable {
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public var startIndex: Index { 0 }
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public var endIndex: Index { count }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func nextSpan(after index: inout Index) -> Span {
+ self.span._nextSpan(after: &index)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Index, maxCount: Int, limitedBy limit: Index
+ ) -> Span {
+ self.span._nextSpan(after: &index, maxCount: maxCount, limitedBy: limit)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(&self)
+ public mutating func nextMutableSpan(
+ after index: inout Index
+ ) -> MutableSpan {
+ self.mutableSpan._nextMutableSpan(after: &index)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(&self)
+ public mutating func nextMutableSpan(
+ after index: inout Index, maxCount: Int, limitedBy limit: Index
+ ) -> MutableSpan {
+ self.mutableSpan._nextMutableSpan(after: &index, maxCount: maxCount, limitedBy: limit)
+ }
+
+ @_alwaysEmitIntoClient
+ public func spanBoundary(before index: Index) -> (index: Index, distance: Int) {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ return (0, index)
+ }
+
+ @_alwaysEmitIntoClient
+ public func spanBoundary(
+ before index: Index, maxDistance: Int, limitedBy limit: Index
+ ) -> (index: Index, distance: Int) {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ precondition(limit >= 0 && limit <= count, "Index out of bounds")
+ precondition(maxDistance > 0, "maxDistance must be positive")
+ let p = index._clampedDown(towards: 0, maxDistance: maxDistance, limitedBy: limit)
+ return (p, index &- p)
+ }
+}
+#endif
diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Iterable.swift b/Sources/ContainersPreview/Conformances/InputSpan+Iterable.swift
new file mode 100644
index 00000000..98d1d49c
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/InputSpan+Iterable.swift
@@ -0,0 +1,30 @@
+//===----------------------------------------------------------------------===//
+//
+// 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) && UnstableContainersPreview
+
+@available(SwiftStdlib 6.4, *)
+extension InputSpan: Iterable_ where Element: ~Copyable {
+ public typealias BorrowingIterator_ = Span.BorrowingIterator_
+
+ @inlinable
+ public var underestimatedCount_: Int { count }
+
+ @_lifetime(borrow self)
+ @inlinable
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ BorrowingIterator_(self.span)
+ }
+}
+
+#endif
diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift
new file mode 100644
index 00000000..ed5625ff
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift
@@ -0,0 +1,156 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the Swift Collections open source project
+//
+// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+//
+// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
+//
+//===----------------------------------------------------------------------===//
+
+#if !COLLECTIONS_SINGLE_MODULE
+import InternalCollectionsUtilities
+#endif
+
+#if compiler(>=6.4) && UnstableContainersPreview
+@available(SwiftStdlib 6.4, *)
+extension MutableSpan: RandomAccessContainer where Element: ~Copyable {
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func makeBorrowingIterator(
+ from start: Int, to end: Int
+ ) -> BorrowingIterator_ {
+ // FIXME: `makeBorrowingIterator` would be borrowing the temporary `span`, not self
+ self.span._makeBorrowingIterator(from: start, to: end)
+ }
+
+ @_alwaysEmitIntoClient
+ public func currentIndex(
+ of iterator: borrowing BorrowingIterator_
+ ) -> Int {
+ precondition(
+ self.span.isTriviallyIdentical(to: iterator._span),
+ "Invalid iterator")
+ return iterator._start
+ }
+}
+#endif
+
+#if compiler(>=6.2) && UnstableContainersPreview
+@available(SwiftStdlib 5.0, *)
+extension MutableSpan where Element: ~Copyable {
+ @_alwaysEmitIntoClient
+ public var startIndex: Int {
+ 0
+ }
+
+ @_alwaysEmitIntoClient
+ public var endIndex: Int {
+ count
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Int
+ ) -> Span {
+ self.span._nextSpan(after: &index)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Index, maxCount: Int, limitedBy limit: Index
+ ) -> Span {
+ self.span._nextSpan(after: &index, maxCount: maxCount, limitedBy: limit)
+ }
+
+ @_alwaysEmitIntoClient
+ public func spanBoundary(
+ before index: Index
+ ) -> (index: Index, distance: Int) {
+ self.span.spanBoundary(before: index)
+ }
+
+ @_alwaysEmitIntoClient
+ public func spanBoundary(
+ before index: Index, maxDistance: Int, limitedBy limit: Index
+ ) -> (index: Index, distance: Int) {
+ self.span.spanBoundary(before: index, maxDistance: maxDistance, limitedBy: limit)
+ }
+}
+#endif
+
+#if compiler(>=6.4) && UnstableContainersPreview
+@available(SwiftStdlib 6.4, *)
+extension MutableSpan: MutableContainer where Element: ~Copyable {}
+#endif
+
+#if compiler(>=6.2) && UnstableContainersPreview
+@available(SwiftStdlib 5.0, *)
+extension MutableSpan where Element: ~Copyable {
+ @_alwaysEmitIntoClient
+ @_lifetime(copy self)
+ public consuming func _nextMutableSpan(
+ after index: inout Int
+ ) -> MutableSpan {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ let end = self.count
+ let r = self._consumingExtracting(unchecked: Range(uncheckedBounds: (index, end)))
+ index = end
+ return r
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(&self)
+ public mutating func nextMutableSpan(
+ after index: inout Int
+ ) -> MutableSpan {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ let end = self.count
+ let r = self._mutatingExtracting(
+ unchecked: Range(uncheckedBounds: (index, end)))
+ index = end
+ return r
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(copy self)
+ public consuming func _nextMutableSpan(
+ after index: inout Int, maxCount: Int, limitedBy limit: Int
+ ) -> MutableSpan {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ precondition(limit >= 0 && limit <= count, "Index out of bounds")
+ precondition(maxCount > 0, "maxCount must be positive")
+ var end = index &+ Swift.min(maxCount, count &- index)
+ if limit >= index, limit < end {
+ end = limit
+ }
+ let r = self._consumingExtracting(
+ unchecked: Range(uncheckedBounds: (index, end)))
+ index = end
+ return r
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(&self)
+ public mutating func nextMutableSpan(
+ after index: inout Int, maxCount: Int, limitedBy limit: Int
+ ) -> MutableSpan {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ precondition(limit >= 0 && limit <= count, "Index out of bounds")
+ precondition(maxCount > 0, "maxCount must be positive")
+ var end = index &+ Swift.min(maxCount, count &- index)
+ if limit >= index, limit < end {
+ end = limit
+ }
+ let r = self._mutatingExtracting(
+ unchecked: Range(uncheckedBounds: (index, end)))
+ index = end
+ return r
+ }
+}
+#endif
diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Iterable.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Iterable.swift
new file mode 100644
index 00000000..d736962f
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/MutableSpan+Iterable.swift
@@ -0,0 +1,35 @@
+//===----------------------------------------------------------------------===//
+//
+// 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) && UnstableContainersPreview
+
+@available(SwiftStdlib 6.4, *)
+extension MutableSpan: Iterable_ where Element: ~Copyable {
+ public typealias BorrowingIterator_ = Span.BorrowingIterator_
+ public typealias Element_ = Element
+
+ @inlinable
+ public var underestimatedCount_: Int { count }
+
+ @_lifetime(borrow self)
+ @inlinable
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ // FIXME: This should be declared to return BorrowingIterator, but it
+ // clashes with the stdlib's alternate definition:
+ // error: 'BorrowingIterator' is ambiguous for type lookup in this context
+ // Two different typealiases with the same name wreaks havoc with inference?
+ BorrowingIterator_(self.span)
+ }
+}
+
+#endif
diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift
new file mode 100644
index 00000000..f048680a
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/OutputSpan+Container.swift
@@ -0,0 +1,92 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the Swift Collections open source project
+//
+// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+//
+// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
+//
+//===----------------------------------------------------------------------===//
+
+#if !COLLECTIONS_SINGLE_MODULE
+import InternalCollectionsUtilities
+#endif
+
+#if compiler(>=6.4) && UnstableContainersPreview
+@available(SwiftStdlib 6.4, *)
+extension OutputSpan: RandomAccessContainer, MutableContainer
+where Element: ~Copyable
+{
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func makeBorrowingIterator(
+ from start: Index, to end: Index
+ ) -> BorrowingIterator_ {
+ // FIXME: `makeBorrowingIterator` would be borrowing the temporary `span`, not self
+ self.span._makeBorrowingIterator(from: start, to: end)
+ }
+
+ @_alwaysEmitIntoClient
+ public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index {
+ self.span.currentIndex(of: iterator)
+ }
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public var startIndex: Index { 0 }
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public var endIndex: Index { count }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func nextSpan(after index: inout Index) -> Span {
+ self.span._nextSpan(after: &index)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Index, maxCount: Int, limitedBy limit: Int
+ ) -> Span {
+ self.span._nextSpan(after: &index, maxCount: maxCount, limitedBy: limit)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(&self)
+ public mutating func nextMutableSpan(
+ after index: inout Index
+ ) -> MutableSpan {
+ self.mutableSpan._nextMutableSpan(after: &index)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(&self)
+ public mutating func nextMutableSpan(
+ after index: inout Index, maxCount: Int, limitedBy limit: Index
+ ) -> MutableSpan {
+ self.mutableSpan._nextMutableSpan(after: &index, maxCount: maxCount, limitedBy: limit)
+ }
+
+ @_alwaysEmitIntoClient
+ public func spanBoundary(before index: Index) -> (index: Index, distance: Int) {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ return (0, index)
+ }
+
+ @_alwaysEmitIntoClient
+ public func spanBoundary(
+ before index: Index, maxDistance: Int, limitedBy limit: Index
+ ) -> (index: Index, distance: Int) {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ precondition(limit >= 0 && limit <= count, "Index out of bounds")
+ precondition(maxDistance > 0, "maxDistance must be positive")
+ let p = index._clampedDown(towards: 0, maxDistance: maxDistance, limitedBy: limit)
+ return (p, index &- p)
+ }
+}
+#endif
diff --git a/Sources/ContainersPreview/Conformances/OutputSpan+Iterable.swift b/Sources/ContainersPreview/Conformances/OutputSpan+Iterable.swift
new file mode 100644
index 00000000..60f6f170
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/OutputSpan+Iterable.swift
@@ -0,0 +1,31 @@
+//===----------------------------------------------------------------------===//
+//
+// 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) && UnstableContainersPreview
+
+@available(SwiftStdlib 6.4, *)
+extension OutputSpan: Iterable_ where Element: ~Copyable {
+ public typealias Element_ = Element
+ public typealias BorrowingIterator_ = Span.BorrowingIterator_
+
+ @inlinable
+ public var underestimatedCount_: Int { count }
+
+ @_lifetime(borrow self)
+ @inlinable
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ BorrowingIterator_(self.span)
+ }
+}
+
+#endif
diff --git a/Sources/ContainersPreview/Conformances/Range+Iterable.swift b/Sources/ContainersPreview/Conformances/Range+Iterable.swift
new file mode 100644
index 00000000..d44995dc
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/Range+Iterable.swift
@@ -0,0 +1,68 @@
+//===----------------------------------------------------------------------===//
+//
+// 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) && UnstableContainersPreview
+
+@available(SwiftStdlib 6.4, *)
+extension Range: Iterable_
+where Bound: Strideable, Bound.Stride: SignedInteger
+{
+ public typealias Element_ = Bound
+
+ @frozen
+ public struct BorrowingIterator_: BorrowingIteratorProtocol_, ~Copyable {
+ @usableFromInline
+ internal var _current: InlineArray<1, Bound>
+
+ @usableFromInline
+ internal var _end: Bound
+
+ @usableFromInline
+ internal var _progress: Bool
+
+ @inlinable
+ internal init(_ base: Range) {
+ self._current = .init(repeating: base.lowerBound)
+ self._end = base.upperBound
+ self._progress = false
+ }
+ @inlinable
+ @_lifetime(&self)
+ public mutating func nextSpan_(maxCount: Int) -> Span {
+ if _progress {
+ _current[0] = _current[0].advanced(by: 1)
+ }
+ guard _current[0] < _end else {
+ _progress = false
+ return .init()
+ }
+ _progress = true
+ return _current.span
+ }
+ }
+
+ @inlinable
+ public var underestimatedCount_: Int {
+ guard let count = Int(exactly: lowerBound.distance(to: upperBound)) else {
+ return 0
+ }
+ return count
+ }
+
+ @inlinable
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ BorrowingIterator_(self)
+ }
+}
+
+#endif
diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift
new file mode 100644
index 00000000..95fac5e1
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/Span+Container.swift
@@ -0,0 +1,115 @@
+//===----------------------------------------------------------------------===//
+//
+// This source file is part of the Swift Collections open source project
+//
+// Copyright (c) 2024 - 2026 Apple Inc. and the Swift project authors
+// Licensed under Apache License v2.0 with Runtime Library Exception
+//
+// See https://swift.org/LICENSE.txt for license information
+//
+// SPDX-License-Identifier: Apache-2.0 WITH Swift-exception
+//
+//===----------------------------------------------------------------------===//
+
+#if compiler(>=6.4) && UnstableContainersPreview
+@available(SwiftStdlib 6.4, *)
+extension Span: RandomAccessContainer where Element: ~Copyable {
+ @_alwaysEmitIntoClient
+ @_lifetime(copy self)
+ package func _makeBorrowingIterator(from start: Int, to end: Int) -> BorrowingIterator_ {
+ // Note: This is declared `copy self` so that types can forward to it without having to override lifetimes.
+ // FIXME: SpanIterator needs to have a public "slicing" initializer
+ BorrowingIterator_(self, from: start, to: end)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func makeBorrowingIterator(from start: Int, to end: Int) -> BorrowingIterator_ {
+ _makeBorrowingIterator(from: start, to: end)
+ }
+
+ @_alwaysEmitIntoClient
+ public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Int {
+ // FIXME: SpanIterator needs to have public `base` and `position` properties
+ precondition(
+ self.isTriviallyIdentical(to: iterator._span),
+ "Invalid iterator")
+ return iterator._start
+ }
+}
+#endif
+
+#if compiler(>=6.2)
+@available(SwiftStdlib 5.0, *)
+extension Span where Element: ~Copyable {
+ @_alwaysEmitIntoClient
+ public var startIndex: Int {
+ 0
+ }
+
+ @_alwaysEmitIntoClient
+ public var endIndex: Int {
+ count
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(copy self)
+ public func _nextSpan(after index: inout Int) -> Self {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ let result = self.extracting(last: count - index)
+ index = count
+ return result
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func nextSpan(after index: inout Int) -> Self {
+ _nextSpan(after: &index)
+ }
+
+ // FIXME: This has the proper lifetime declaration but can't fulfill the Container requirement.
+ @_alwaysEmitIntoClient
+ @_lifetime(copy self)
+ public func _nextSpan(
+ after index: inout Int, maxCount: Int, limitedBy limit: Int
+ ) -> Self {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ precondition(maxCount > 0, "maxCount must be positive")
+ precondition(limit >= 0 && limit <= count, "Index out of bounds")
+ var end = index &+ Swift.min(maxCount, count &- index)
+ if limit >= index, limit < end {
+ end = limit
+ }
+ let r = self.extracting(unchecked: Range(uncheckedBounds: (index, end)))
+ index = end
+ return r
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Int, maxCount: Int, limitedBy limit: Int
+ ) -> Self {
+ _nextSpan(after: &index, maxCount: maxCount, limitedBy: limit)
+ }
+
+ @_alwaysEmitIntoClient
+ public func spanBoundary(
+ before index: Index
+ ) -> (index: Index, distance: Int) {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ return (0, index)
+ }
+
+ @_alwaysEmitIntoClient
+ public func spanBoundary(
+ before index: Index, maxDistance: Int, limitedBy limit: Index
+ ) -> (index: Index, distance: Int) {
+ precondition(index >= 0 && index <= count, "Index out of bounds")
+ precondition(limit >= 0 && limit <= count, "Index out of bounds")
+ precondition(maxDistance > 0, "maxDistance must be positive")
+ let p = index._clampedDown(towards: 0, maxDistance: maxDistance, limitedBy: limit)
+ return (p, index &- p)
+ }
+}
+#endif
diff --git a/Sources/ContainersPreview/Conformances/Span+Iterable.swift b/Sources/ContainersPreview/Conformances/Span+Iterable.swift
new file mode 100644
index 00000000..f841bc26
--- /dev/null
+++ b/Sources/ContainersPreview/Conformances/Span+Iterable.swift
@@ -0,0 +1,89 @@
+//===----------------------------------------------------------------------===//
+//
+// 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) && UnstableContainersPreview
+
+@available(SwiftStdlib 6.4, *)
+extension Span: Iterable_ where Element: ~Copyable {
+ public typealias Element_ = Element
+
+ @inlinable
+ public var underestimatedCount_: Int { count }
+
+ @inlinable
+ @_lifetime(borrow self)
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ BorrowingIterator_(self)
+ }
+}
+
+@available(SwiftStdlib 5.0, *)
+extension Span where Element: ~Copyable {
+ /// A borrowing iterator that provides access to the elements of a single
+ /// span through a `BorrowingIteratorProtocol` interface.
+ @available(SwiftStdlib 6.4, *)
+ public struct BorrowingIterator_:
+ BorrowingIteratorProtocol_, ~Copyable, ~Escapable
+ {
+ public typealias Element_ = Element
+
+ @usableFromInline
+ package var _span: Span
+ @usableFromInline
+ package var _start: Int
+ @usableFromInline
+ package var _count: Int
+
+ @_lifetime(copy elements)
+ public init(_ elements: Span) {
+ _span = elements
+ _start = 0
+ _count = elements.count
+ }
+
+ @_lifetime(copy elements)
+ public init(_ elements: Span, from start: Int, to end: Int) {
+ precondition(start >= 0 && start <= elements.count, "Index out of bounds")
+ precondition(end >= 0 && end <= elements.count, "Index out of bounds")
+ precondition(start <= end, "start index must be less than or equal to end index")
+ _span = elements
+ _start = start
+ _count = end &- start
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(&self)
+ @_lifetime(self: copy self)
+ @_transparent
+ public mutating func nextSpan_(maxCount: Int) -> Span {
+ let c = Swift.min(maxCount, _count)
+ defer {
+ _start &+= c
+ _count &-= c
+ }
+ return _span.extracting(droppingFirst: _start).extracting(first: c)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(self: copy self)
+ public mutating func skip_(by offset: Int) -> Int {
+ let c = Swift.min(offset, _count)
+ defer {
+ _start &+= c
+ _count &-= c
+ }
+ return c
+ }
+ }
+}
+#endif
diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Copy.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Copy.swift
similarity index 98%
rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Copy.swift
rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Copy.swift
index 73007d3a..9831a128 100644
--- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Copy.swift
+++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Copy.swift
@@ -14,7 +14,7 @@
#if compiler(>=6.4) && UnstableContainersPreview
@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_
+extension BorrowingIteratorProtocol_
where
Self: ~Copyable & ~Escapable,
Element_: Copyable
diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+ElementsEqual.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift
similarity index 88%
rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+ElementsEqual.swift
rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift
index 32d14064..d2f57623 100644
--- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+ElementsEqual.swift
+++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+ElementsEqual.swift
@@ -17,7 +17,7 @@ import InternalCollectionsUtilities
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension Iterable_
where
Self: ~Copyable & ~Escapable, Element_: Equatable,
@@ -31,13 +31,13 @@ where
) throws(Failure_) -> Bool
where Other.Element_: ~Copyable
{
- let it1 = self.makeIterableIterator_()
- let it2 = other.makeIterableIterator_()
+ let it1 = self.makeBorrowingIterator_()
+ let it2 = other.makeBorrowingIterator_()
return try it1.elementsEqual(it2)
}
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension Iterable_
where
Self: ~Copyable & ~Escapable,
@@ -73,21 +73,21 @@ where
) throws(Failure_) -> Bool
where Other.Element_: ~Copyable, Other.Failure_ == Failure_
{
- let it1 = self.makeIterableIterator_()
- let it2 = other.makeIterableIterator_()
+ let it1 = self.makeBorrowingIterator_()
+ let it2 = other.makeBorrowingIterator_()
return try it1.elementsEqual(it2, by: areEquivalent)
}
}
-@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_
+@available(SwiftStdlib 6.4, *)
+extension BorrowingIteratorProtocol_
where
Self: ~Copyable & ~Escapable,
Element_: ~Copyable & Equatable
{
@inlinable
package consuming func elementsEqual<
- Other: IterableIteratorProtocol_ & ~Copyable & ~Escapable
+ Other: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable
>(
_ other: consuming Other,
) throws(Failure_) -> Bool
@@ -113,7 +113,7 @@ where
@inlinable
package consuming func _directElementsEqual<
- Other: IterableIteratorProtocol_ & ~Copyable & ~Escapable
+ Other: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable
>(
_ other: consuming Other,
) throws(Failure_) -> Bool
@@ -123,7 +123,7 @@ where
// Note: This is the less efficient implementation of elementsEqual. The
// variant in the #else branch would be preferable, but it doesn't work yet.
// (It lets the two iterators run at their native speeds, with no artificial
- // maximumCounts.)
+ // maxCounts.)
while true {
let a = try self.nextSpan_()
var i = 0
@@ -131,7 +131,7 @@ where
return try other.nextSpan_().isEmpty
}
while i < a.count {
- let b = try other.nextSpan_(maximumCount: a.count - i)
+ let b = try other.nextSpan_(maxCount: a.count - i)
if b.isEmpty {
return false
}
@@ -173,15 +173,15 @@ where
}
}
-@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_
+@available(SwiftStdlib 6.4, *)
+extension BorrowingIteratorProtocol_
where
Self: ~Copyable & ~Escapable,
Element_: ~Copyable
{
@inlinable
package consuming func elementsEqual<
- Other: IterableIteratorProtocol_ & ~Copyable & ~Escapable
+ Other: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable
>(
_ other: consuming Other,
by areEquivalent: (borrowing Element_, borrowing Other.Element_) throws(Failure_) -> Bool
diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Filter.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Filter.swift
similarity index 86%
rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Filter.swift
rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Filter.swift
index f42c869d..c5cc3d96 100644
--- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Filter.swift
+++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Filter.swift
@@ -14,7 +14,7 @@
#if compiler(>=6.4) && UnstableContainersPreview
@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_
+extension BorrowingIteratorProtocol_
where
Self: ~Copyable & ~Escapable,
Element_: ~Copyable
@@ -30,7 +30,7 @@ where
@available(SwiftStdlib 5.0, *)
public struct BorrowingFilter<
- Base: IterableIteratorProtocol_ & ~Copyable & ~Escapable
+ Base: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable
>: ~Copyable, ~Escapable
where Base.Element_: ~Copyable {
public typealias Element_ = Base.Element_
@@ -56,13 +56,13 @@ where Base.Element_: ~Copyable {
// FIXME: Sendable
@available(SwiftStdlib 5.0, *)
-extension BorrowingFilter: IterableIteratorProtocol_
+extension BorrowingFilter: BorrowingIteratorProtocol_
where Base: ~Copyable & ~Escapable, Base.Element_: ~Copyable {
@_lifetime(&self)
- public mutating func nextSpan_(maximumCount: Int) throws(Failure) -> Span {
+ public mutating func nextSpan_(maxCount: Int) throws(Failure) -> Span {
// FIXME: This is quite inefficient compared to Container's filter
while true {
- let span = try _base.nextSpan_(maximumCount: 1)
+ let span = try _base.nextSpan_(maxCount: 1)
if span.isEmpty { return span }
precondition(span.count == 1, "Invalid BorrowingIterator")
if try _isIncluded(span[unchecked: 0]) { return span }
diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Map.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift
similarity index 77%
rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Map.swift
rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift
index 07d7acd1..35d6fd4f 100644
--- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Map.swift
+++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Map.swift
@@ -14,7 +14,7 @@
#if compiler(>=6.4) && UnstableContainersPreview
@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_
+extension BorrowingIteratorProtocol_
where
Self: ~Copyable & ~Escapable,
Element_: ~Copyable
@@ -52,7 +52,7 @@ where
@available(SwiftStdlib 5.0, *)
public struct BorrowingMapProducer<
- Base: IterableIteratorProtocol_ & ~Copyable & ~Escapable,
+ Base: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable,
Element: ~Copyable,
>: ~Copyable, ~Escapable {
@_alwaysEmitIntoClient
@@ -90,7 +90,7 @@ where
@inlinable
@_lifetime(self: copy self)
public mutating func next() throws(Failure) -> Element? {
- let span = try _it.nextSpan_(maximumCount: 1)
+ let span = try _it.nextSpan_(maxCount: 1)
guard !span.isEmpty else { return nil }
return try _transform(span[unchecked: 0])
}
@@ -104,7 +104,7 @@ where
) throws(Failure) -> Bool {
var success = false
while !target.isFull {
- let span = try _it.nextSpan_(maximumCount: target.freeCapacity)
+ let span = try _it.nextSpan_(maxCount: target.freeCapacity)
guard !span.isEmpty else { break }
success = true
var i = 0
@@ -115,6 +115,28 @@ where
}
return success
}
+
+ @inlinable
+ @_lifetime(self: copy self)
+ public mutating func skip(by n: inout Int) throws(Failure) {
+ precondition(n > 0, "Can't skip a negative number of elements")
+ if Failure.self == Never.self {
+ n -= try! _it.skip_(by: n)
+ return
+ }
+#if false
+ // FIXME: Iterator's ill-conceived skip(by:) fails to report the position that triggers errors
+ try _it.skip_(by: &n)
+#else
+ // We have no choice other than skipping items one by one, or allowing
+ // the base to materialize every element. The latter performs better in
+ // the common case of containers, so let's do that.
+ while n > 0 {
+ let span = try _it.nextSpan_(maxCount: n)
+ n -= span.count
+ }
+#endif
+ }
}
#endif
diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+MapError.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+MapError.swift
similarity index 87%
rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+MapError.swift
rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+MapError.swift
index 14d8ed99..292db26e 100644
--- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+MapError.swift
+++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+MapError.swift
@@ -14,7 +14,7 @@
#if compiler(>=6.4) && UnstableContainersPreview
@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_
+extension BorrowingIteratorProtocol_
where
Self: ~Copyable & ~Escapable,
Element_: ~Copyable
@@ -41,7 +41,7 @@ where
@frozen
public struct ErrorMappedIterator<
- Base: IterableIteratorProtocol_ & ~Copyable & ~Escapable,
+ Base: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable,
Failure: Error
>: ~Copyable, ~Escapable
where Base.Element_: ~Copyable {
@@ -62,7 +62,7 @@ where Base.Element_: ~Copyable {
}
}
-extension ErrorMappedIterator: IterableIteratorProtocol_
+extension ErrorMappedIterator: BorrowingIteratorProtocol_
where
Base: ~Copyable & ~Escapable,
Base.Element_: ~Copyable
@@ -73,9 +73,9 @@ where
@inlinable
@_lifetime(&self)
@_lifetime(self: copy self)
- public mutating func nextSpan_(maximumCount: Int) throws(Failure_) -> Span {
+ public mutating func nextSpan_(maxCount: Int) throws(Failure_) -> Span {
do {
- return try _base.nextSpan_(maximumCount: maximumCount)
+ return try _base.nextSpan_(maxCount: maxCount)
} catch {
throw _transform(error)
}
diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Reduce.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Reduce.swift
similarity index 97%
rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Reduce.swift
rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Reduce.swift
index c6526bb8..6f766bb2 100644
--- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+Reduce.swift
+++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+Reduce.swift
@@ -14,7 +14,7 @@
#if compiler(>=6.4) && UnstableContainersPreview
@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_
+extension BorrowingIteratorProtocol_
where
Self: ~Copyable & ~Escapable,
Element_: ~Copyable
diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+SpanwiseZip.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift
similarity index 93%
rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol+SpanwiseZip.swift
rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift
index f84d3ffd..393f2023 100644
--- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol+SpanwiseZip.swift
+++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol+SpanwiseZip.swift
@@ -18,14 +18,14 @@ import InternalCollectionsUtilities
#if compiler(>=6.4) && UnstableContainersPreview
@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_
+extension BorrowingIteratorProtocol_
where
Self: ~Copyable & ~Escapable,
Element_: ~Copyable
{
@inlinable
internal consuming func _spanwiseZip<
- Other: IterableIteratorProtocol_ & ~Copyable & ~Escapable,
+ Other: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable,
State: ~Copyable
>(
state: inout State,
@@ -38,7 +38,7 @@ where
// Note: This is the less efficient implementation of spanwiseZip. The
// variant in the #else branch would be preferable, but it doesn't work yet.
// (It lets the two iterators run at their native speeds, with no artificial
- // maximumCounts.)
+ // maxCounts.)
loop:
while true {
var a = try self.nextSpan_()
@@ -51,7 +51,7 @@ where
return
}
repeat {
- let b = try other.nextSpan_(maximumCount: a.count)
+ let b = try other.nextSpan_(maxCount: a.count)
if b.isEmpty {
guard try process(&state, a, b) else { return }
} else {
diff --git a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol.swift b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift
similarity index 82%
rename from Sources/ContainersPreview/Protocols/IterableIteratorProtocol.swift
rename to Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift
index 3cd13d16..b8009880 100644
--- a/Sources/ContainersPreview/Protocols/IterableIteratorProtocol.swift
+++ b/Sources/ContainersPreview/Protocols/BorrowingIteratorProtocol.swift
@@ -18,7 +18,7 @@ import InternalCollectionsUtilities
#endif
@available(SwiftStdlib 5.0, *)
-public protocol IterableIteratorProtocol_: ~Copyable, ~Escapable {
+public protocol BorrowingIteratorProtocol_: ~Copyable, ~Escapable {
associatedtype Element_: ~Copyable
associatedtype Failure_: Error = Never
@@ -34,10 +34,10 @@ public protocol IterableIteratorProtocol_: ~Copyable, ~Escap
/// 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`
+ /// then this method returns a non-empty span of at most `maxCount`
/// 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
+ /// none). The `maxCount` 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.
///
@@ -70,7 +70,7 @@ public protocol IterableIteratorProtocol_: ~Copyable, ~Escap
/// method may vary between different borrows of the same container.)
@_lifetime(&self)
@_lifetime(self: copy self)
- mutating func nextSpan_(maximumCount: Int) throws(Failure_) -> Span
+ mutating func nextSpan_(maxCount: Int) throws(Failure_) -> Span
/// Advance the position of this iterator by the specified offset, or until
/// the end of the underlying sequence.
@@ -86,47 +86,47 @@ public protocol IterableIteratorProtocol_: ~Copyable, ~Escap
}
@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_
+extension BorrowingIteratorProtocol_
where Self: ~Copyable & ~Escapable, Element_: ~Copyable {
@_lifetime(&self)
@_lifetime(self: copy self)
@_transparent
public mutating func nextSpan_() throws(Failure_) -> Span {
- try nextSpan_(maximumCount: Int.max)
+ try nextSpan_(maxCount: Int.max)
}
}
@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_
+extension BorrowingIteratorProtocol_
where Self: ~Copyable & ~Escapable, Element_: ~Copyable {
@_lifetime(self: copy self)
@inlinable
- public mutating func skip_(by offset: Int) throws(Failure_) -> Int {
- var remainder = offset
+ public mutating func skip_(by maxDistance: Int) throws(Failure_) -> Int {
+ var remainder = maxDistance
while remainder > 0 {
- let span = try nextSpan_(maximumCount: remainder)
+ let span = try nextSpan_(maxCount: remainder)
if span.isEmpty { break }
remainder &-= span.count
}
- return offset &- remainder
+ return maxDistance &- remainder
}
}
@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_ where Self: ~Copyable & ~Escapable {
-#if false // FIXME: This doesn't work, but it should?
+extension BorrowingIteratorProtocol_ where Self: ~Copyable & ~Escapable {
+ @available(SwiftStdlib 6.4, *)
+ @_unsafeNonescapableResult // FIXME: Eep; _overrideLifetime(_:mutating:) doesn't work
@_lifetime(&self)
@_lifetime(self: copy self)
- public mutating func next() -> Ref? {
- let span = nextSpan(maximumCount: 1)
+ public mutating func next() throws(Failure_) -> Ref? {
+ let span = try nextSpan_(maxCount: 1)
guard !span.isEmpty else { return nil }
- return Ref(_borrowing: span[unchecked: 0])
+ return Ref(span[unchecked: 0])
}
-#endif
}
@available(SwiftStdlib 5.0, *)
-extension IterableIteratorProtocol_
+extension BorrowingIteratorProtocol_
where Self: ~Copyable & ~Escapable, Element_: Copyable
{
@_lifetime(self: copy self)
@@ -136,7 +136,7 @@ extension IterableIteratorProtocol_
try target.withUnsafeMutableBufferPointer { (dst, dstCount) throws(Failure_) -> Void in
var tail = dst._extracting(droppingFirst: dstCount)
while !tail.isEmpty {
- let src = try nextSpan_(maximumCount: tail.count)
+ let src = try nextSpan_(maxCount: tail.count)
if src.isEmpty { break }
tail._initializeAndDropPrefix(copying: src)
dstCount += src.count
@@ -145,5 +145,4 @@ extension IterableIteratorProtocol_
}
}
-
#endif
diff --git a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift
index 332c97ff..d3b80be4 100644
--- a/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift
+++ b/Sources/ContainersPreview/Protocols/Container/BidirectionalContainer.swift
@@ -13,142 +13,191 @@
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
public protocol BidirectionalContainer: Container, ~Copyable, ~Escapable
where Element: ~Copyable, Index: Comparable
{
+ override associatedtype Element: ~Copyable
+ override associatedtype Index
+
+ // Note: Some `Container` requirements are redeclared as `override`s to help
+ // associated type inference; others are kept separate with `@_nonoverride`.
+ //
+ // @_nonoverride creates separate witness table entries, allowing divergent
+ // implementations in conditional conformances. This enables conforming types
+ // to provide distinct implementations depending on whether the caller is
+ // generic over `Container` or `BidirectionalContainer`.
+ //
+ // (Unfortunately, neither `override` nor `@_nonoverride` allows callers
+ // that are generic over `Container` to automatically dispatch
+ // to a more constrained bidirectional implementation variant. Still, at least
+ // `@_nonoverride` enables more refined implementations to take effect
+ // when the caller is explicitly generic over `BidirectionalContainer`.)
+ //
+ // `@_nonoverride` should be used on requirements with new semantic
+ // constraints in refining protocols.
+ //
+ // Collection types usually do not come with conditional conformances to
+ // refining collection protocols (as the resulting behavior can be quite
+ // confusing), so the separate witness entries rarely if ever get exercised
+ // in practice. I don't expect things would be different with Container.
+ //
+ // FIXME: Consider avoiding using `@_nonoverride`, reducing witness sizes.
+
func index(before i: Index) -> Index
+
func formIndex(before i: inout Index)
- @_lifetime(borrow self)
- func previousSpan(before index: inout Index, maximumCount: Int) -> Span
+ func spanBoundary(before index: Index) -> (index: Index, distance: Int)
+
+ func spanBoundary(
+ before index: Index, maxDistance: Int, limitedBy limit: Index
+ ) -> (index: Index, distance: Int)
+
+ override func index(after index: Index) -> Index
+
+ override func formIndex(after index: inout Index)
+
+ @_nonoverride func index(_ index: Index, offsetBy n: Int) -> Index
+
+ @_nonoverride func formIndex(
+ _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index
+ )
+
+ @_nonoverride func distance(from start: Index, to end: Index) -> Int
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension BidirectionalContainer
where Self: ~Copyable & ~Escapable, Element: ~Copyable {
- @inlinable
+ @_alwaysEmitIntoClient
+ @_transparent
+ public func spanBoundary(
+ before index: Index
+ ) -> (index: Index, distance: Int) {
+ self.spanBoundary(
+ before: index,
+ maxDistance: Int.max,
+ limitedBy: self.endIndex)
+ }
+
+ @_alwaysEmitIntoClient
+ @_transparent
+ public func spanBoundary(
+ before index: Index,
+ maxDistance: Int
+ ) -> (index: Index, distance: Int) {
+ self.spanBoundary(
+ before: index,
+ maxDistance: maxDistance,
+ limitedBy: self.endIndex)
+ }
+
+ @_alwaysEmitIntoClient
+ @_transparent
+ @_lifetime(borrow self)
+ public func previousSpan(
+ before index: inout Index,
+ maxCount: Int = Int.max
+ ) -> Span {
+ self.previousSpan(
+ before: &index,
+ maxCount: maxCount,
+ limitedBy: self.endIndex)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func previousSpan(
+ before index: inout Index,
+ maxCount: Int = Int.max,
+ limitedBy limit: Index
+ ) -> Span {
+ let (i, d) = spanBoundary(before: index, maxDistance: maxCount, limitedBy: limit)
+ if d == 0 { return .init() }
+ var j = i
+ let span = nextSpan(after: &j, limitedBy: index)
+ precondition(j == index && span.count <= maxCount, "Invalid BidirectionalContainer")
+ index = i
+ return span
+ }
+}
+
+@available(SwiftStdlib 6.4, *)
+extension BidirectionalContainer
+where Self: ~Copyable & ~Escapable, Element: ~Copyable {
+ @_alwaysEmitIntoClient
+ public func index(before i: Index) -> Index {
+ self.spanBoundary(before: i, maxDistance: 1).index
+ }
+
+ @_alwaysEmitIntoClient
public func formIndex(before i: inout Index) {
i = self.index(before: i)
}
- @inlinable
- @_lifetime(borrow self)
- public func previousSpan(before index: inout Index) -> Span {
- previousSpan(before: &index, maximumCount: Int.max)
- }
-
- @inlinable
- public func distance(from start: Index, to end: Index) -> Int {
- var i = self.index(alignedDown: start)
- let end = self.index(alignedDown: end)
- var d = 0
- if start <= end {
- // FIXME: Use bulk iteration here, with binary search within the final chunk.
- while i != end {
- self.formIndex(after: &i)
- d += 1
- }
- } else {
- // FIXME: Use bulk iteration here, with binary search within the final chunk.
- while i != end {
- self.formIndex(before: &i)
- d -= 1
- }
- }
- return d
- }
-
- @inlinable
+ @_alwaysEmitIntoClient
public func index(_ index: Index, offsetBy n: Int) -> Index {
- var index = self.index(alignedDown: index)
+ var index = index
var n = n
+ let end = self.endIndex
if n >= 0 {
while n > 0 {
- let span = self.nextSpan(after: &index, maximumCount: n)
- precondition(
- !span.isEmpty,
- "Cannot advance index beyond the end of the container")
- n &-= span.count
- }
- } else {
- n = -n
- while n > 0 {
- let span = self.previousSpan(before: &index, maximumCount: n)
- precondition(
- !span.isEmpty,
- "Cannot advance index beyond the end of the container")
- n &-= span.count
+ let c = self.nextSpan(after: &index, maxCount: n, limitedBy: end).count
+ precondition(c > 0, "Cannot advance index beyond the end of the container")
+ n &-= c
}
+ return index
+ }
+ n = -n
+ while n > 0 {
+ let r = self.spanBoundary(before: index, maxDistance: n, limitedBy: end)
+ index = r.index
+ n &-= r.distance
}
return index
}
- @inlinable
+ @_alwaysEmitIntoClient
public func formIndex(
_ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index
) {
- index = self.index(alignedDown: index)
var n = n
- let limit = self.index(alignedDown: limit)
if n >= 0 {
- if index > limit {
- index = self.index(index, offsetBy: n)
- n = 0
- return
- }
- // Skip forward until we find our target or overshoot the limit.
while n > 0 {
- var j = index
- let span = self.nextSpan(after: &j, maximumCount: n)
- precondition(
- !span.isEmpty,
- "Cannot advance index beyond the end of the container")
- if j > limit {
- break
- }
- index = j
- n &-= span.count
- }
- // Step through to find the precise target when we hit the limit.
- // FIXME: Figure out a way to use binary search here (with `index(_:offsetBy:)`)
- while n != 0 {
- if index == limit {
- return
- }
- formIndex(after: &index)
- n &-= 1
+ let c = self.nextSpan(after: &index, maxCount: n, limitedBy: limit).count
+ precondition(c <= n, "Invalid container")
+ guard c > 0 else { break }
+ n &-= c
}
return
}
- // n < 0
- if index < limit {
- index = self.index(index, offsetBy: n)
- n = 0
- return
- }
- // Skip backward until we find our target or overshoot the limit.
- while n < 0 {
- var j = index
- let span = self.previousSpan(before: &j, maximumCount: -n)
- precondition(
- !span.isEmpty,
- "Cannot move index before the start of the container")
- if j < limit {
- break
- }
- index = j
- n &+= span.count
- }
- // Step through to find the precise target when we hit the limit.
- // FIXME: Figure out a way to use binary search here (with `index(_:offsetBy:)`)
- while n != 0 {
- if index == limit {
+ n = -n
+ while n > 0 {
+ let r = self.spanBoundary(before: index, maxDistance: n, limitedBy: limit)
+ if r.distance == 0 {
+ // We hit the limit (or the start)
return
}
- formIndex(before: &index)
- n &+= 1
+ n &+= r.distance
+ index = r.index
}
}
+
+ @_alwaysEmitIntoClient
+ public func index(
+ _ index: Index, offsetBy n: Int, limitedBy limit: Index
+ ) -> Index? {
+ var index = index
+ var n = n
+ self.formIndex(&index, offsetBy: &n, limitedBy: limit)
+ if n != 0 { return nil }
+ return index
+ }
+
+ // Note: `distance(from:to:)` comes from `Container where Index: Comparable`.
}
+
+// FIXME: Add ambiguity resolvers against BidirectionCollection algorithms.
+
#endif
diff --git a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift
index 85563c04..5968aa33 100644
--- a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift
+++ b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift
@@ -19,6 +19,7 @@ import InternalCollectionsUtilities
@available(SwiftStdlib 6.4, *)
extension Container where Self: ~Copyable /*& ~Escapable*/, Element: ~Copyable {
+ @_alwaysEmitIntoClient
@_lifetime(borrow self)
public func _filter(
_ isIncluded: @escaping (borrowing Element) -> Bool
@@ -29,6 +30,7 @@ extension Container where Self: ~Copyable /*& ~Escapable*/, Element: ~Copyable {
@available(SwiftStdlib 6.4, *)
extension ContainerIterator where Base.Element: ~Copyable {
+ @_alwaysEmitIntoClient
@_lifetime(copy self)
public func filter(
_ isIncluded: @escaping (borrowing Element) -> Bool
@@ -57,7 +59,7 @@ where Base.Element: ~Copyable
@_alwaysEmitIntoClient
public var _remainder: Span
- @inlinable
+ @_alwaysEmitIntoClient
@_lifetime(copy _base)
internal init(
_base: Ref,
@@ -70,7 +72,7 @@ where Base.Element: ~Copyable
self._remainder = .init()
}
- @inlinable
+ @_alwaysEmitIntoClient
@_lifetime(borrow _base)
internal init(
_base: borrowing Base,
@@ -86,12 +88,12 @@ where Base.Element: ~Copyable
// FIXME: Sendable
@available(SwiftStdlib 6.4, *)
-extension ContainerFilter: IterableIteratorProtocol_ where Element: ~Copyable {
+extension ContainerFilter: BorrowingIteratorProtocol_ where Element: ~Copyable {
public typealias Element_ = Base.Element
@_lifetime(&self) // FIXME: This should be `@_lifetime(copy self)`
- public mutating func nextSpan_(maximumCount: Int) -> Span {
- precondition(maximumCount > 0)
+ public mutating func nextSpan_(maxCount: Int) -> Span {
+ precondition(maxCount > 0)
while true {
// Drop filtered out items from prefix of _remainder
var i = 0
@@ -100,7 +102,7 @@ extension ContainerFilter: IterableIteratorProtocol_ where Element: ~Copyable {
}
_remainder = _remainder.extracting(droppingFirst: i)
if !_remainder.isEmpty {
- let c = Swift.min(_remainder.count, maximumCount)
+ let c = Swift.min(_remainder.count, maxCount)
i = 1
while i < c, _isIncluded(_remainder[unchecked: i]) {
i &+= 1
diff --git a/Sources/ContainersPreview/Protocols/Container/Container+SpanwiseZip.swift b/Sources/ContainersPreview/Protocols/Container/Container+SpanwiseZip.swift
index 32e53ebd..e5e46726 100644
--- a/Sources/ContainersPreview/Protocols/Container/Container+SpanwiseZip.swift
+++ b/Sources/ContainersPreview/Protocols/Container/Container+SpanwiseZip.swift
@@ -17,7 +17,7 @@ import InternalCollectionsUtilities
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
@_alwaysEmitIntoClient
internal func _spanwiseZip(
diff --git a/Sources/ContainersPreview/Protocols/Container/Container.swift b/Sources/ContainersPreview/Protocols/Container/Container.swift
index 199aa591..51c8e534 100644
--- a/Sources/ContainersPreview/Protocols/Container/Container.swift
+++ b/Sources/ContainersPreview/Protocols/Container/Container.swift
@@ -13,13 +13,26 @@
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+/// An `Iterable` that holds its elements in memory, so that we can form
+/// references to them that aren't dependent on iteration state.
+/// The contents of a container can be traversed multiple times,
+/// nondestructively, and efficiently accessed.
+@available(SwiftStdlib 6.4, *)
public protocol Container:
Iterable_, ~Copyable, ~Escapable
where Element: ~Copyable, Element == Element_, Failure_ == Never
{
- associatedtype Element: ~Copyable
- associatedtype Index: Equatable
+ override associatedtype Element: ~Copyable
+
+ /// Indices are expected to implement `==` and `hash(into:)` with
+ /// constant complexity.
+ associatedtype Index: Equatable, Hashable
+
+ // FIXME: We need Container to define a default value for BorrowingIterator,
+ // but we can only do that once ContainerIterator can support a
+ // nonescapable Base.
+ //associatedtype BorrowingIterator = ContainerIterator
+
// FIXME: Ideally Index should also be required to be Hashable.
// FIXME: If we discard the separate BorrowingSequence abstraction, then we
// should consider dropping Comparable and just having Equatable indices, so
@@ -29,182 +42,28 @@ public protocol Container:
// somewhere -- `RandomAccessContainer` or `BidirectionalContainer` would be
// the obvious candidates.
+ /// - Complexity: Recommended to be O(1); conforming types must clearly
+ /// document deviations from this expectation.
+ @_lifetime(borrow self)
+ func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator_
+
+ /// - Complexity: Recommended to be O(1); conforming types must clearly
+ /// document deviations from this expectation.
+ func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index
+
+ /// Complexity: O(1)
var isEmpty: Bool { get }
+
+ /// Complexity: O(1)
var count: Int { get }
+ /// - Complexity: Recommended to be O(1); conforming types must clearly
+ /// document deviations from this expectation.
var startIndex: Index { get }
+
+ /// Complexity: Must be O(1) on all container types.
var endIndex: Index { get }
-
- /// Returns the position immediately after the given index.
- ///
- /// - Parameter index: A valid index of the container. `i` must be less
- /// than `endIndex`.
- /// - Returns: The index immediately following `i`.
- func index(after index: Index) -> Index
-
- /// Replaces the given index with its successor.
- ///
- /// - Parameter index: A valid index of the container. `i` must be less
- /// than `endIndex`.
- func formIndex(after index: inout Index)
- /// Returns an index that is the specified distance from the given index.
- ///
- /// The value passed as `n` must not offset `index` beyond the bounds of the
- /// container.
- ///
- /// - Parameter index: A valid index of the container.
- /// - Parameter n: The distance by which to offset `index`.
- /// - Returns: An index offset by distance from `index`. If `n` is positive,
- /// this is the same value as the result of `n` calls to `index(after:)`.
- /// If `n` is negative, this is the same value as the result of `abs(n)`
- /// calls to `index(before:)`.
- func index(_ index: Index, offsetBy n: Int) -> Index
-
- /// Offsets the given index by the specified distance, but no further than
- /// the given limiting index.
- ///
- /// If the operation was able to offset `index` by exactly the requested
- /// number of steps without hitting `limit`, then on return `n` is set to `0`,
- /// and `index` is set to the adjusted index.
- ///
- /// If the operation hits the limit before it can take the requested number
- /// of steps, then on return `index` is set to `limit`, and `n` is set
- /// to the number of steps that couldn't be taken.
- ///
- /// The value passed as `n` must not offset `index` beyond the bounds of the
- /// container, unless the index passed as `limit` prevents offsetting beyond
- /// those bounds.
- ///
- /// - Parameter index: A valid index of the container.
- /// - Parameter n: The distance to offset `index`. `n` must not be negative
- /// unless the container conforms to the `BidirectionalContainer` protocol.
- /// - Parameter limit: A valid index of the container to use as a limit.
- /// If `n > 0`, a limit that is less than `index` has no effect.
- /// Likewise, if `n < 0`, a limit that is greater than `index` has no
- /// effect.
- func formIndex(
- _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index
- )
-
- /// Returns the distance between two indices.
- ///
- /// - Parameter start: A valid index of the collection.
- /// - Parameter end: Another valid index of the collection. If end is equal
- /// to start, the result is zero.
- /// - Returns: The distance between `start` and `end`.
- 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, but no more than `maximumCount` items.
- ///
- /// 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, maximumCount: 4)
- /// if span.isEmpty { break }
- /// // Process items in `span`
- /// }
- ///
- /// The `maximumCount` argument gives the caller control over the number of
- /// items it receives from the iterator. This lets the caller avoid getting
- /// more elements than it would be able to immediately process, which would
- /// significantly complicate container use.
- ///
- /// If the caller is able to process any number available items, it can signal
- /// that by passing `Int.max` as the `maximumCount`, or simply by calling the
- /// `nexSpan(after:)` method, which does precisely that. This is frequently
- /// the case when the caller simply wants to iterate over the entire
- /// container in a single loop.
- ///
- /// `maximumCount` sets an upper bound. To read a specific number of items,
- /// the caller usually needs to invoke `nextSpan` in a loop:
- ///
- /// var items: some Container
- /// var index = items.startIndex
- /// var remainder = numberOfItemsToRead
- /// while remainder > 0 {
- /// let next = items.nextSpan(after: &index, maximumCount: remainder)
- /// guard !next.isEmpty else {
- /// // Container does not have enough items
- /// break
- /// }
- /// remainder -= next.count
- /// // Process items in `next`
- /// }
- ///
- /// - 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.
- /// - Parameter maximumCount: The maximum number of items the caller is able
- /// to process immediately. `maximumCount` must be greater than zero.
- /// If you are able to process an arbitrary number of items, set
- /// `maximumCount` to `Int.max`, or call the `nextSpan(after:)` method.
- /// - 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
-
- // subscript(index: Index) -> Element { borrow }
-
- /// Return the nearest valid index in this container less than or equal to
- /// the given index value, which must be valid in at least one view of self.
- ///
- /// This operation is important for container types that provide multiple
- /// alternative projections (or "views") over the same underlying
- /// representation, with each view conforming to `Container`, and sharing
- /// the same `Index`. (Like `String` does with its UTF-8, UTF-16,
- /// Unicode ccalar and character views in the `Collection` world.)
- /// This rounding operation enables clients to convert/normalize valid index
- /// values in one container view into valid indices in another, allowing them
- /// to (easily) decide whether two (potentially misaligned) index values
- /// address the same element.
- ///
- /// The default implementation of this operation simply returns `index`.
- func index(alignedDown index: Index) -> Index
-
- /// Return the nearest valid index in this container greater than or equal to
- /// the given index value, which must be valid in at least one view of self.
- ///
- /// This operation is important for container types that provide multiple
- /// alternative projections (or "views") over the same underlying
- /// representation, with each view conforming to `Container`, and sharing
- /// the same `Index`. (Like `String` does with its UTF-8, UTF-16,
- /// Unicode ccalar and character views in the `Collection` world.)
- /// This rounding operation enables clients to convert/normalize valid index
- /// values in one container view into valid indices in another, allowing them
- /// to (easily) decide whether two (potentially misaligned) index values
- /// address the same element.
- ///
- /// The default implementation of this operation simply returns `index`.
- func index(alignedUp index: Index) -> Index
-
- func _customIndexOfEquatableElement(_ element: borrowing Element) -> Index??
- func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index??
-}
-
-@available(SwiftStdlib 5.0, *)
-extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
/// 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
@@ -239,169 +98,309 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
/// 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.
- @inlinable
@_lifetime(borrow self)
- public func nextSpan(after index: inout Index) -> Span {
- nextSpan(after: &index, maximumCount: Int.max)
- }
+ func nextSpan(after index: inout Index) -> Span
-// @inlinable
-// @_lifetime(borrow self)
-// public func nextSpan(after index: inout Index, maximumCount: Int) -> Span {
-// 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
-// }
+ /// 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, but no more than `maxCount` items, and no further than
+ /// the given limiting index (if any).
+ ///
+ /// On return, the index is updated to address the item following the
+ /// last element 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,
+ /// maxCount: 4,
+ /// limitedBy: items.endIndex)
+ /// if span.isEmpty { break }
+ /// // Process items in `span`
+ /// }
+ ///
+ /// The `maxCount` argument gives the caller control over the number of
+ /// items it receives from the iterator. This lets the caller avoid getting
+ /// more elements than it would be able to immediately process, which would
+ /// significantly complicate container use.
+ ///
+ /// If the caller is able to process any number available items, it can signal
+ /// that by passing `Int.max` as the `maxCount`, or simply by calling the
+ /// `nextSpan(after:)` method, which does precisely that. This is frequently
+ /// the case when the caller simply wants to iterate over the entire
+ /// container in a single loop.
+ ///
+ /// `maxCount` sets an upper bound. To read a specific number of items,
+ /// the caller usually needs to invoke `nextSpan` in a loop:
+ ///
+ /// var items: some Container
+ /// var index = items.startIndex
+ /// var remainder = numberOfItemsToRead
+ /// while remainder > 0 {
+ /// let next = items.nextSpan(after: &index, maxCount: remainder)
+ /// guard !next.isEmpty else {
+ /// // Container does not have enough items
+ /// break
+ /// }
+ /// remainder -= next.count
+ /// // Process items in `next`
+ /// }
+ ///
+ /// - 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.
+ /// - Parameter maxCount: The maximum number of items the caller is ready
+ /// to process. `maxCount` must be greater than zero.
+ /// If the client is able to process an arbitrary number of items, then
+ /// this can be signalled by setting `maxCount` to `Int.max`; calling
+ /// the `nextSpan(after:)` method is a more direct way to express the same.
+ /// - Parameter limit: A valid index of the container to use as a limit.
+ /// A limit that precedes `index` has no effect. Otherwise the method
+ /// stops before exceeding `limit`. If you don't have a specific limiting
+ /// index to use, you can set this to `endIndex` to allow the method to
+ /// traverse the entire container.
+ /// - Returns: A span over contiguous storage that starts at the given index.
+ /// If the input index is equal to the end index or `limit`, then this
+ /// returns an empty span.
+ /// Otherwise the result is non-empty, with its first element matching the
+ /// element at the input index.
+ /// - Complexity: Recommended to be O(1). Conforming types must clearly
+ /// document deviations from this expectation.
+ @_lifetime(borrow self)
+ func nextSpan(
+ after index: inout Index,
+ maxCount: Int,
+ limitedBy limit: Index
+ ) -> Span
+
+ /// Accesses the element at the specified position.
+ ///
+ /// You can subscript a collection with any valid index other than the
+ /// collection’s end index. The end index refers to the position one past the
+ /// last element of a collection, so it doesn’t correspond with an element.
+ ///
+ /// - Parameter position: The position of the element to access.
+ /// `position` must be a valid index of the container that is not equal
+ /// to the `endIndex` property.
+ /// - Complexity: O(1). This is a hard requirement.
+ subscript(index: Index) -> Element { borrow }
+
+ /// Returns the position immediately after the given index.
+ ///
+ /// - Parameter index: A valid index of the container. `i` must be less
+ /// than `endIndex`.
+ /// - Returns: The index immediately following `i`.
+ /// - Complexity: Recommended to be O(1); conforming types must clearly
+ /// document deviations from this expectation.
+ func index(after index: Index) -> Index
+
+ /// Replaces the given index with its successor.
+ ///
+ /// - Parameter index: A valid index of the container. `i` must be less
+ /// than `endIndex`.
+ /// - Complexity: Recommended to be O(1); conforming types must clearly
+ /// document deviations from this expectation.
+ func formIndex(after index: inout Index)
+
+ /// Returns an index that is the specified distance from the given index.
+ ///
+ /// The value passed as `n` must not offset `index` beyond the bounds of the
+ /// container.
+ ///
+ /// - Parameter index: A valid index of the container.
+ /// - Parameter n: The distance by which to offset `index`.
+ /// - Returns: An index offset by distance from `index`. If `n` is positive,
+ /// this is the same value as the result of `n` calls to `index(after:)`.
+ /// If `n` is negative, this is the same value as the result of `abs(n)`
+ /// calls to `index(before:)`.
+ /// - Complexity: Recommended to be O(`n`); conforming types must clearly
+ /// document deviations from this expectation.
+ func index(_ index: Index, offsetBy n: Int) -> Index
+
+ /// Offsets the given index by the specified distance, but no further than
+ /// the given limiting index.
+ ///
+ /// If the operation was able to offset `index` by exactly the requested
+ /// number of steps without hitting `limit`, then on return `n` is set to `0`,
+ /// and `index` is set to the adjusted index.
+ ///
+ /// If the operation hits the limit before it can take the requested number
+ /// of steps, then on return `index` is set to `limit`, and `n` is set
+ /// to the number of steps that couldn't be taken.
+ ///
+ /// The value passed as `n` must not offset `index` beyond the bounds of the
+ /// container, unless the index passed as `limit` prevents offsetting beyond
+ /// those bounds.
+ ///
+ /// - Parameter index: A valid index of the container.
+ /// - Parameter n: The distance to offset `index`. `n` must not be negative
+ /// unless the container conforms to the `BidirectionalContainer` protocol.
+ /// - Parameter limit: A valid index of the container to use as a limit.
+ /// If `n > 0`, a limit that is less than `index` has no effect.
+ /// Likewise, if `n < 0`, a limit that is greater than `index` has no
+ /// effect.
+ /// - Complexity: Recommended to be O(n); conforming types must clearly
+ /// document deviations from this expectation.
+ func formIndex(
+ _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index
+ )
+
+ /// Returns the distance between two indices.
+ ///
+ /// - Parameter start: A valid index of the collection.
+ /// - Parameter end: Another valid index of the collection. If end is equal
+ /// to start, the result is zero.
+ /// - Returns: The distance between `start` and `end`.
+ /// - Complexity: Recommended to be O(*d*), where *d* is the resulting
+ /// distance. Conforming types must clearly document deviations from this
+ /// expectation.
+ func distance(from start: Index, to end: Index) -> Int
+
+ func _customIndexOfEquatableElement(_ element: borrowing Element) -> Index??
+ func _customLastIndexOfEquatableElement(_ element: borrowing Element) -> Index??
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
- @inlinable
- public var isEmpty: Bool {
- startIndex == endIndex
+ @_alwaysEmitIntoClient
+ @_transparent
+ public var underestimatedCount_: Int { count }
+
+ @_alwaysEmitIntoClient
+ @_transparent
+ @_lifetime(borrow self)
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ self.makeBorrowingIterator(from: self.startIndex, to: self.endIndex)
}
- @inlinable
+ @_alwaysEmitIntoClient
+ @_transparent
+ @_lifetime(borrow self)
+ public func makeBorrowingIterator_(from start: Index) -> BorrowingIterator_ {
+ self.makeBorrowingIterator(from: start, to: self.endIndex)
+ }
+}
+
+@available(SwiftStdlib 6.4, *)
+extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
+ @_alwaysEmitIntoClient
+ @_transparent
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Index
+ ) -> Span {
+ self.nextSpan(after: &index, maxCount: Int.max, limitedBy: self.endIndex)
+ }
+
+ @_alwaysEmitIntoClient
+ @_transparent
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Index,
+ maxCount: Int
+ ) -> Span {
+ self.nextSpan(after: &index, maxCount: maxCount, limitedBy: self.endIndex)
+ }
+
+ @_alwaysEmitIntoClient
+ @_transparent
+ @_lifetime(borrow self)
+ public func nextSpan(
+ after index: inout Index,
+ limitedBy limit: Index
+ ) -> Span {
+ self.nextSpan(after: &index, maxCount: Int.max, limitedBy: limit)
+ }
+}
+
+@available(SwiftStdlib 6.4, *)
+extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
+ @_alwaysEmitIntoClient
+ public var isEmpty: Bool {
+ count == 0
+ }
+
+#if false // count is required to be O(1), so it cannot have this default implementation
+ @_alwaysEmitIntoClient
public var count: Int {
distance(from: startIndex, to: endIndex)
}
+#endif
- @inlinable
+ @_alwaysEmitIntoClient
+ public func index(after index: Index) -> Index {
+ let end = self.endIndex
+ var index = index
+ let c = self.nextSpan(after: &index, maxCount: 1, limitedBy: end).count
+ precondition(c == 1, "Can't advance beyond endIndex")
+ return index
+ }
+
+ @_alwaysEmitIntoClient
public func formIndex(after index: inout Index) {
index = self.index(after: index)
}
- @inlinable
+ @_alwaysEmitIntoClient
public func index(_ index: Index, offsetBy n: Int) -> Index {
- precondition(
- n >= 0,
- "Only BidirectionalContainers can be advanced by a negative amount")
-
- var index = self.index(alignedDown: index)
+ var index = index
var n = n
-
-#if true // with nextSpan(after:maximumCount:)
+ let end = self.endIndex
while n > 0 {
- let span = self.nextSpan(after: &index, maximumCount: n)
- precondition(
- !span.isEmpty,
- "Cannot advance index beyond the end of the container")
- n &-= span.count
+ let c = self.nextSpan(after: &index, maxCount: n, limitedBy: end).count
+ precondition(c > 0, "Cannot advance index beyond the end of the container")
+ n &-= c
}
return index
-#else // without nextSpan(after:maximumCount:)
- // FIXME: This implementation can be wasteful for piecewise contiguous
- // containers, as iterating over spans will tend to overshoot the target.
-
- // 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,
- "Cannot 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
+ @_alwaysEmitIntoClient
public func formIndex(
_ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index
) {
precondition(
n >= 0,
"Only BidirectionalContainers can be advanced by a negative amount")
-
- index = self.index(alignedDown: index)
- let limit = self.index(alignedDown: limit)
-
- // Note: with Index not conforming to `Comparable`, we cannot do bulk
- // iteration here, as we have no way to decide if we stepped over `limit`.
- while n > 0, index != limit {
- self.formIndex(after: &index)
- n &-= 1
+ while n > 0 {
+ let c = self.nextSpan(after: &index, maxCount: n, limitedBy: limit).count
+ precondition(c <= n, "Invalid container")
+ guard c > 0 else { break }
+ n &-= c
}
}
- @inlinable
- public func distance(from start: Index, to end: Index) -> Int {
-#if true
- // This variant does not require that `start` precede `end`, but it's
- // slower/larger.
- // FIXME: Linked lists may require an even slower implementation
- // to avoid looping (turtle/hare cycle detection).
- let start = self.index(alignedDown: start)
- let end = self.index(alignedDown: end)
- let limit = self.endIndex
- var a = start
- var b = end
- var d = 0
- while true {
- if a == end { return d }
- if b == start { return -d }
- if a == limit {
- while b != end {
- self.formIndex(after: &b)
- d += 1
- }
- return -d
- }
- if b == limit {
- while a != end {
- self.formIndex(after: &a)
- d += 1
- }
- return d
- }
- self.formIndex(after: &a)
- self.formIndex(after: &b)
- d += 1
- }
-#else
- // This variant requires that `start` precede `end`, but we cannot ensure
- // that with a quick check, so we need to compare against the `endIndex` to
- // avoid looping indefinitely.
- // FIXME: Linked lists may require an even slower implementation
- // to avoid looping (turtle/hare cycle detection).
- let i = self.index(alignedDown: start)
- let target = self.index(alignedDown: end)
- let limit = self.endIndex
- var count = 0
- while i != target {
- self.formIndex(after: &i)
- precondition(i != limit, "Only BidirectionalContainers can have end come before start")
- count += 1
- }
- return count
-#endif
+ @_alwaysEmitIntoClient
+ public func index(
+ _ index: Index, offsetBy n: Int, limitedBy limit: Index
+ ) -> Index? {
+ var index = index
+ var n = n
+ self.formIndex(&index, offsetBy: &n, limitedBy: limit)
+ if n != 0 { return nil }
+ return index
}
- @inlinable
- public func index(alignedDown index: Index) -> Index { index }
-
- @inlinable
- public func index(alignedUp index: Index) -> Index { index }
-
- @inlinable
+ @_alwaysEmitIntoClient
public func _customIndexOfEquatableElement(_: borrowing Element) -> Index?? {
nil
}
- @inlinable
+ @_alwaysEmitIntoClient
public func _customLastIndexOfEquatableElement(
_ element: borrowing Element
) -> Index?? {
@@ -409,12 +408,72 @@ extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
}
}
-
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable {
- @_transparent
- public var underestimatedCount_: Int { count }
+ @_alwaysEmitIntoClient
+ public func distance(from start: Index, to end: Index) -> Int {
+#if true
+ // This variant allows start to follow end, but as indices aren't
+ // comparable, we have to measure distances from both ends.
+ var d1 = 0
+ var d2 = 0
+ var i1 = start
+ var i2 = end
+ var forward = true
+ var backward = true
+ while forward || backward {
+ if forward {
+ let c = self.nextSpan(after: &i1, limitedBy: end).count
+ d1 += c
+ if i1 == end { return d1 }
+ if c == 0 { forward = false }
+ }
+ if backward {
+ let c = self.nextSpan(after: &i2, limitedBy: start).count
+ d2 -= c
+ if i2 == start { return d2 }
+ if c == 0 { backward = false }
+ }
+ }
+ fatalError("Invalid Container")
+#else
+ // Worse variant: this requires start <= end, but it has no way to quickly
+ // validate it. Furthermore, the restriction conflicts with Collection's
+ // more flexible implementation.
+ var i = start
+ var d = 0
+ while true {
+ let c = self.nextSpan(after: &i, limitedBy: j).count
+ d += c
+ if i == end { break }
+ precondition(c > 0, "Invalid Container or 'start' does not precede 'end'")
+ }
+ return d
+#endif
+ }
}
-#endif
+@available(SwiftStdlib 6.4, *)
+extension Container
+where
+ Self: ~Copyable & ~Escapable,
+ Element: ~Copyable,
+ Index: Comparable
+{
+ @_alwaysEmitIntoClient
+ public func distance(from start: Index, to end: Index) -> Int {
+ var (i, j, forward): (Index, Index, Bool) = (start <= end
+ ? (start, end, true)
+ : (end, start, false))
+ var d = 0
+ while i < j {
+ let span = self.nextSpan(after: &i, limitedBy: j)
+ d += span.count
+ }
+ return forward ? d : -d
+ }
+}
+// FIXME: Add ambiguity resolvers against Collection's algorithms.
+
+#endif
diff --git a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift
index d44b67ed..ca71c43f 100644
--- a/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift
+++ b/Sources/ContainersPreview/Protocols/Container/ContainerIterator.swift
@@ -18,11 +18,26 @@ extension Container
where
Self: ~Copyable /*FIXME: & ~Escapable*/,
Element: ~Copyable,
- IterableIterator_ == ContainerIterator
+ BorrowingIterator_ == ContainerIterator
{
+ @_alwaysEmitIntoClient
@_lifetime(borrow self)
- public func makeIterableIterator_() -> IterableIterator_ {
- ContainerIterator(_borrowing: self, from: self.startIndex)
+ public func makeBorrowingIterator_() -> BorrowingIterator_ {
+ ContainerIterator(
+ _borrowing: self,
+ from: self.startIndex,
+ to: self.endIndex)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(borrow self)
+ public func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator_ {
+ ContainerIterator(_borrowing: self, from: start, to: end)
+ }
+
+ @_alwaysEmitIntoClient
+ public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index {
+ iterator._position
}
}
@@ -33,31 +48,45 @@ public struct ContainerIterator<
where Base.Element: ~Copyable
{
public typealias Element = Base.Element
-
- let _base: Ref // FIXME: This doesn't support nonescapable Bases
- var _position: Base.Index
+ @_alwaysEmitIntoClient
+ package let _base: Ref // FIXME: This doesn't support nonescapable Bases
+
+ @_alwaysEmitIntoClient
+ package let _end: Base.Index
+
+ @_alwaysEmitIntoClient
+ package var _position: Base.Index
+
+ @_alwaysEmitIntoClient
@_lifetime(borrow base)
- init(_borrowing base: borrowing @_addressable Base, from position: Base.Index) {
+ package init(_borrowing base: borrowing Base, from start: Base.Index, to end: Base.Index) {
self._base = Ref(base)
- self._position = position
+ self._end = end
+ self._position = start
}
}
@available(SwiftStdlib 6.4, *)
-extension ContainerIterator: IterableIteratorProtocol_
+extension ContainerIterator: BorrowingIteratorProtocol_
where
Base: ~Copyable /*FIXME: & ~Escapable*/,
Base.Element: ~Copyable
{
public typealias Element_ = Base.Element
+ @_alwaysEmitIntoClient
@_unsafeNonescapableResult // FIXME: we cannot convert from a borrow to an inout dependence?!
@_lifetime(&self)
- public mutating func nextSpan_(maximumCount: Int) -> Span {
- _base.value.nextSpan(after: &self._position, maximumCount: maximumCount)
+ public mutating func nextSpan_(maxCount: Int) -> Span {
+ _base.value
+ .nextSpan(
+ after: &self._position,
+ maxCount: maxCount,
+ limitedBy: self._end)
}
+ @_alwaysEmitIntoClient
@_lifetime(self: copy self)
public mutating func skip_(by maximumOffset: Int) -> Int {
// FIXME: If we aren't modeling bidirectional iterators, then this should
diff --git a/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift b/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift
index 389f3153..08b2b425 100644
--- a/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift
+++ b/Sources/ContainersPreview/Protocols/Container/DynamicContainer.swift
@@ -13,7 +13,7 @@
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
public protocol DynamicContainer: RangeReplaceableContainer, ~Copyable
where Element: ~Copyable
{
@@ -22,17 +22,33 @@ where Element: ~Copyable
mutating func reserveCapacity(_ minimumCapacity: Int)
+ /// The number of items that can be added to the container without forcing
+ /// it to allocate extra storage. This is primarily intended to serve as a
+ /// hint for the batch size of appends, to allow bulk operation even if
+ /// the number of items to be appended is not known in advance.
+ ///
+ /// If the container does not have simple, predictable allocation behavior,
+ /// then this should return the size of the container's primitive allocation
+ /// unit. For example, in a balanced rope that organizes its contents into a
+ /// tree of fixed-capacity nodes, it may be a good choice to use the maximum
+ /// node size as the (constant) free capacity, even though it may not
+ /// correlate exactly with actual allocation behavior.
+ ///
+ /// If a container always reports a free capacity of 0, then appending a
+ /// sequence of items of an unknown size may run slower than expected.
+ ///
+ /// - Complexity: O(1)
var freeCapacity: Int { get }
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension DynamicContainer where Self: ~Copyable, Element: ~Copyable {
- @inlinable
+ @_alwaysEmitIntoClient
public init() {
self.init(minimumCapacity: 0)
}
- @inlinable
+ @_alwaysEmitIntoClient
public init(
minimumCapacity: Int,
initializingWith initializer: (inout OutputSpan) throws(E) -> Void
@@ -41,7 +57,7 @@ extension DynamicContainer where Self: ~Copyable, Element: ~Copyable {
try self.append(addingCount: minimumCapacity, initializingWith: initializer)
}
- @inlinable
+ @_alwaysEmitIntoClient
public init<
E: Error,
P: Producer & ~Copyable & ~Escapable
@@ -55,7 +71,7 @@ extension DynamicContainer where Self: ~Copyable, Element: ~Copyable {
try self.append(from: producer)
}
- @inlinable
+ @_alwaysEmitIntoClient
public mutating func append<
E: Error,
P: Producer & ~Copyable & ~Escapable
@@ -66,24 +82,31 @@ extension DynamicContainer where Self: ~Copyable, Element: ~Copyable {
{
while true {
let c = Swift.max(producer.underestimatedCount, self.freeCapacity)
- try self.append(addingCount: c) { target throws(E) in
- while !target.isFull {
- guard try producer.generate(into: &target) else { return }
+ if c > 0 {
+ try self.append(addingCount: c) { target throws(E) in
+ while !target.isFull {
+ guard try producer.generate(into: &target) else { return }
+ }
}
}
- // Nudge the container to resize itself, providing more `freeCapacity` in
- // the next iteration. Doing this separately avoids forcing the container
- // to unnecessarily reallocate itself when the producer is already
- // complete. (In exchange, we have to move a handful of items twice.)
+ // Nudge the container to resize itself, hopefully providing more
+ // `freeCapacity` in the next iteration. Doing this separately avoids
+ // forcing the container to unnecessarily reallocate itself when the
+ // producer is already complete.
+ //
+ // In exchange, when neither the producer nor the container provides
+ // a nonzero count/capacity, then every single item will be added
+ // individually, resulting in appending all items one by one, but with
+ // additional overhead spent on the repeared property invocations.
guard let next = try producer.next() else { return }
self.append(next)
}
}
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension DynamicContainer where Self: ~Copyable, Element: Copyable {
- @inlinable
+ @_alwaysEmitIntoClient
public init(repeating repeatedValue: Element, count: Int) {
var c = count
self.init(minimumCapacity: count) { target in
diff --git a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift
index 06516f54..9c200bf4 100644
--- a/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift
+++ b/Sources/ContainersPreview/Protocols/Container/MutableContainer.swift
@@ -13,33 +13,160 @@
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
public protocol MutableContainer:
PermutableContainer, ~Copyable, ~Escapable
where
Element: ~Copyable
{
- // subscript(index: Index) -> Element { borrow mutate }
+ /// Accesses the element at the specified position.
+ ///
+ /// - Parameter position: The position of the element to access.
+ /// `position` must be a valid index of the container that is not equal
+ /// to the `endIndex` property.
+ /// - Complexity: O(1)
+ subscript(index: Index) -> Element { borrow mutate }
+ @_lifetime(&self)
+ mutating func nextMutableSpan(after index: inout Index) -> MutableSpan
+
+ /// Return a mutable 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, but no more than `maxCount` items.
+ ///
+ /// 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 {
+ /// var span = items.nextMutableSpan(after: &index, maxCount: 4)
+ /// if span.isEmpty { break }
+ /// // Process items in `span`
+ /// }
+ ///
+ /// The `maxCount` argument gives the caller control over the number of
+ /// items it receives from the iterator. This lets the caller avoid getting
+ /// more elements than it would be able to immediately process, which would
+ /// significantly complicate container use.
+ ///
+ /// If the caller is able to process any number available items, it can signal
+ /// that by passing `Int.max` as the `maxCount`, or simply by calling the
+ /// `nexSpan(after:)` method, which does precisely that. This is frequently
+ /// the case when the caller simply wants to iterate over the entire
+ /// container in a single loop.
+ ///
+ /// `maxCount` sets an upper bound. To read a specific number of items,
+ /// the caller usually needs to invoke `nextSpan` in a loop:
+ ///
+ /// var items: some MutableContainer
+ /// var index = items.startIndex
+ /// var remainder = numberOfItemsToRead
+ /// while remainder > 0 {
+ /// let next = items.nextMutableSpan(after: &index, maxCount: remainder)
+ /// guard !next.isEmpty else {
+ /// // Container does not have enough items
+ /// break
+ /// }
+ /// remainder -= next.count
+ /// // Process items in `next`
+ /// }
+ ///
+ /// - 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.
+ /// - Parameter maxCount: The maximum number of items the caller is able
+ /// to process immediately. `maxCount` must be greater than zero.
+ /// If you are able to process an arbitrary number of items, set
+ /// `maxCount` to `Int.max`, or call the `nextSpan(after:)` method.
+ /// - Returns: A mutable 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(&self)
mutating func nextMutableSpan(
after index: inout Index,
- maximumCount: Int
+ maxCount: Int,
+ limitedBy limit: Index
) -> MutableSpan
-
- // FIXME: What about previousMutableSpan?
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension MutableContainer
where Self: ~Copyable & ~Escapable, Element: ~Copyable
{
- @inlinable
+ @_alwaysEmitIntoClient
@_lifetime(&self)
- mutating func nextMutableSpan(
- after index: inout Index,
+ public mutating func nextMutableSpan(
+ after index: inout Index
) -> MutableSpan {
- nextMutableSpan(after: &index, maximumCount: Int.max)
+ nextMutableSpan(after: &index, maxCount: Int.max, limitedBy: self.endIndex)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(&self)
+ public mutating func nextMutableSpan(
+ after index: inout Index,
+ limitedBy limit: Index
+ ) -> MutableSpan {
+ nextMutableSpan(after: &index, maxCount: Int.max, limitedBy: limit)
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(&self)
+ public mutating func nextMutableSpan(
+ after index: inout Index,
+ maxCount: Int
+ ) -> MutableSpan {
+ nextMutableSpan(after: &index, maxCount: maxCount, limitedBy: self.endIndex)
+ }
+}
+
+@available(SwiftStdlib 6.4, *)
+extension MutableContainer
+where
+ Self: BidirectionalContainer & ~Copyable & ~Escapable,
+ Element: ~Copyable
+{
+ @_alwaysEmitIntoClient
+ @_lifetime(&self)
+ public mutating func previousMutableSpan(
+ before index: inout Index
+ ) -> MutableSpan {
+ let start = self.spanBoundary(before: index).index
+ var i = start
+ let span = self.nextMutableSpan(after: &i, limitedBy: index)
+ precondition(i == index, "Invalid BidirectionalContainer")
+ return span
+ }
+
+ @_alwaysEmitIntoClient
+ @_lifetime(&self)
+ public mutating func previousMutableSpan(
+ before index: inout Index,
+ maxCount: Int,
+ limitedBy limit: Index
+ ) -> MutableSpan {
+ let start = self.spanBoundary(
+ before: index,
+ maxDistance: maxCount,
+ limitedBy: limit
+ ).index
+ var i = start
+ let span = self.nextMutableSpan(after: &i, limitedBy: index)
+ precondition(i == index, "Invalid BidirectionalContainer")
+ index = start
+ return span
}
}
diff --git a/Sources/ContainersPreview/Protocols/Container/PermutableContainer.swift b/Sources/ContainersPreview/Protocols/Container/PermutableContainer.swift
index 8cfe7224..cf96d0e9 100644
--- a/Sources/ContainersPreview/Protocols/Container/PermutableContainer.swift
+++ b/Sources/ContainersPreview/Protocols/Container/PermutableContainer.swift
@@ -13,7 +13,7 @@
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
public protocol PermutableContainer: Container, ~Copyable, ~Escapable
where Element: ~Copyable
{
diff --git a/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift b/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift
index 08acb559..35979738 100644
--- a/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift
+++ b/Sources/ContainersPreview/Protocols/Container/RandomAccessContainer.swift
@@ -13,11 +13,47 @@
#if compiler(>=6.4) && UnstableContainersPreview
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
public protocol RandomAccessContainer
: BidirectionalContainer, ~Copyable, ~Escapable
-where Element: ~Copyable {}
+where Element: ~Copyable, Index: Comparable {
+ // Note: Some requirements are redeclared to help associated type inference;
+ // others are kept separate with `@_nonoverride`.
+ //
+ // See more detailed discussion on `BidirectionalContainer`.
+ //
+ // `RandomAccessContainer` should technically redeclare single-steppers
+ // like `index(after:)` as `@_nonoverride`, as the protocol adds a semantic
+ // requirement for O(1) complexity. However, we emulate
+ // `RandomAccessCollection`'s (not necessarily well-justified) decision to
+ // leave these marked as overrides, forcing all types to have a single
+ // implementation that fulfills the (unique) requirement. (I haven't seen a
+ // case where these steppers would need to vary their implementation, while
+ // offsetting/distance calculations do sometimes want that, at least in
+ // theory. Not so much in practice though -- see e.g. `ZipSequence`'s lack of
+ // a conditional (random-access) collection conformance.)
+ //
+ // FIXME: Consider avoiding using `@_nonoverride`, reducing witness sizes.
+ override associatedtype Element: ~Copyable
+ override associatedtype Index
+
+ override func index(after index: Index) -> Index
+ override func index(before index: Index) -> Index
+
+ override func formIndex(after index: inout Index)
+ override func formIndex(before index: inout Index)
+
+ @_nonoverride func index(_ index: Index, offsetBy n: Int) -> Index
+
+ @_nonoverride func formIndex(
+ _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index
+ )
+
+ @_nonoverride func distance(from start: Index, to end: Index) -> Int
+}
+
+@available(SwiftStdlib 5.0, *)
extension RandomAccessCollection {
@inlinable
public func formIndex(
@@ -34,53 +70,124 @@ extension RandomAccessCollection {
}
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension RandomAccessContainer
-where Self: ~Copyable & ~Escapable, Index: Strideable, Index.Stride == Int
+where
+ Self: ~Copyable & ~Escapable,
+ Element: ~Copyable,
+ Index: Strideable,
+ Index.Stride == Int
{
- @inlinable
+ @_alwaysEmitIntoClient
public var isEmpty: Bool { startIndex == endIndex }
- @inlinable
+ @_alwaysEmitIntoClient
public var count: Int { startIndex.distance(to: endIndex) }
- @inlinable
+ @_alwaysEmitIntoClient
public func index(after index: Index) -> Index {
// Note: Range checks are deferred until element access.
index.advanced(by: 1)
}
- @inlinable
+ @_alwaysEmitIntoClient
public func index(before index: Index) -> Index {
// Note: Range checks are deferred until element access.
index.advanced(by: -1)
}
- @inlinable
+ @_alwaysEmitIntoClient
public func formIndex(after index: inout Index) {
// Note: Range checks are deferred until element access.
index = index.advanced(by: 1)
}
- @inlinable
+ @_alwaysEmitIntoClient
public func formIndex(before index: inout Index) {
// Note: Range checks are deferred until element access.
index = index.advanced(by: -1)
}
- @inlinable
+ @_alwaysEmitIntoClient
public func distance(from start: Index, to end: Index) -> Int {
// Note: Range checks are deferred until element access.
start.distance(to: end)
}
- @inlinable
+ @_alwaysEmitIntoClient
public func index(_ index: Index, offsetBy n: Int) -> Index {
// Note: Range checks are deferred until element access.
index.advanced(by: n)
}
- @inlinable
+ @_alwaysEmitIntoClient
+ public func formIndex(
+ _ index: inout Index, offsetBy distance: inout Index.Stride, limitedBy limit: Index
+ ) {
+ // Note: Range checks are deferred until element access.
+ index.advance(by: &distance, limitedBy: limit)
+ }
+}
+
+@available(SwiftStdlib 6.4, *)
+extension RandomAccessContainer
+where
+ Self: ~Copyable & ~Escapable,
+ Element: ~Copyable,
+ Index == Int
+{
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public var isEmpty: Bool { startIndex == endIndex }
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public var count: Int { endIndex - startIndex }
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public func index(after index: Index) -> Index {
+ // Note: Range checks are deferred until element access.
+ index + 1
+ }
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public func index(before index: Index) -> Index {
+ // Note: Range checks are deferred until element access.
+ index - 1
+ }
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public func formIndex(after index: inout Index) {
+ // Note: Range checks are deferred until element access.
+ index += 1
+ }
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public func formIndex(before index: inout Index) {
+ // Note: Range checks are deferred until element access.
+ index -= 1
+ }
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public func distance(from start: Index, to end: Index) -> Int {
+ // Note: Range checks are deferred until element access.
+ end - start
+ }
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public func index(_ index: Index, offsetBy n: Int) -> Index {
+ // Note: Range checks are deferred until element access.
+ index + n
+ }
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
public func formIndex(
_ index: inout Index, offsetBy distance: inout Index.Stride, limitedBy limit: Index
) {
@@ -91,7 +198,7 @@ where Self: ~Copyable & ~Escapable, Index: Strideable, Index.Stride == Int
// Disambiguate parallel extensions on RandomAccessContainer and RandomAccessCollection
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension RandomAccessCollection
where
Self: RandomAccessContainer,
@@ -99,47 +206,56 @@ where
Index.Stride == Int,
Indices == Range
{
- @inlinable
+ @_alwaysEmitIntoClient
public var isEmpty: Bool { startIndex == endIndex }
- @inlinable
+ @_alwaysEmitIntoClient
public var count: Int { endIndex - startIndex }
- @inlinable
+ @_alwaysEmitIntoClient
public func index(after index: Index) -> Index {
// Note: Range checks are deferred until element access.
index.advanced(by: 1)
}
- @inlinable
+ @_alwaysEmitIntoClient
public func index(before index: Index) -> Index {
// Note: Range checks are deferred until element access.
index.advanced(by: -1)
}
- @inlinable
+ @_alwaysEmitIntoClient
public func formIndex(after index: inout Index) {
// Note: Range checks are deferred until element access.
index = index.advanced(by: 1)
}
- @inlinable
+ @_alwaysEmitIntoClient
public func formIndex(before index: inout Index) {
// Note: Range checks are deferred until element access.
index = index.advanced(by: -1)
}
- @inlinable
+ @_alwaysEmitIntoClient
public func distance(from start: Index, to end: Index) -> Int {
// Note: Range checks are deferred until element access.
start.distance(to: end)
}
- @inlinable
+ @_alwaysEmitIntoClient
public func index(_ index: Index, offsetBy n: Int) -> Index {
// Note: Range checks are deferred until element access.
index.advanced(by: n)
}
+
+ @_alwaysEmitIntoClient
+ @inline(__always)
+ public func formIndex(
+ _ index: inout Index, offsetBy distance: inout Index.Stride, limitedBy limit: Index
+ ) {
+ // Note: Range checks are deferred until element access.
+ index.advance(by: &distance, limitedBy: limit)
+ }
}
#endif
diff --git a/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift b/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift
index 2814339b..84c61e8d 100644
--- a/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift
+++ b/Sources/ContainersPreview/Protocols/Container/RangeExpression2.swift
@@ -15,18 +15,18 @@
// FIXME: Figure out if it would be possible to add the container-based
// `relative(to:)` to the existing `RangeExpression`.
-@available(SwiftStdlib 5.0, *)
-public protocol RangeExpression2 {
- associatedtype Bound: Comparable
+@available(SwiftStdlib 6.4, *)
+public protocol RangeExpression2: RangeExpression {
+ override associatedtype Bound: Comparable
func relative(
to container: borrowing C
) -> Range where C.Index == Bound, C.Element: ~Copyable
- func contains(_ element: Bound) -> Bool
+ override func contains(_ element: Bound) -> Bool
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension Range: RangeExpression2 {
@inlinable
public func relative(
@@ -36,7 +36,7 @@ extension Range: RangeExpression2 {
}
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension ClosedRange: RangeExpression2 {
@inlinable
public func relative(
@@ -47,7 +47,7 @@ extension ClosedRange: RangeExpression2 {
}
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension PartialRangeFrom: RangeExpression2 {
@inlinable
public func relative(
@@ -57,7 +57,7 @@ extension PartialRangeFrom: RangeExpression2 {
}
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension PartialRangeUpTo: RangeExpression2 {
@inlinable
public func relative(
@@ -67,7 +67,7 @@ extension PartialRangeUpTo: RangeExpression2 {
}
}
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension PartialRangeThrough: RangeExpression2 {
@inlinable
public func relative(
diff --git a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift
index 10ba9f42..dd032b47 100644
--- a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift
+++ b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift
@@ -19,14 +19,14 @@ import InternalCollectionsUtilities
//MARK: - Protocol Definition
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
public protocol RangeReplaceableContainer
: Container, ~Copyable, ~Escapable
where
Element: ~Copyable,
Index: Comparable // For `Range`
{
- // Core requirements
+ // MARK: Core requirements
var freeCapacity: Int { get }
@@ -42,11 +42,15 @@ where
@_lifetime(&self)
mutating func consume(_ subrange: Range) -> SubrangeConsumer
- // Requirements with default implementations
+ // MARK: Requirements with default implementations
mutating func remove(at index: Index) -> Element
mutating func removeSubrange(_ bounds: Range)
mutating func removeAll()
+ mutating func removeFirst() -> Element
+ mutating func removeFirst(_ n: Int)
+ mutating func _customRemoveLast() -> Element?
+ mutating func _customRemoveLast(_ n: Int) -> Bool
mutating func insert(
addingCount newItemCount: Int,
@@ -66,11 +70,11 @@ where
//MARK: - Default Implementations
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension RangeReplaceableContainer
where Self: ~Copyable & ~Escapable, Element: ~Copyable
{
- @inlinable
+ @_alwaysEmitIntoClient
public mutating func remove(at index: Index) -> Element {
let range = Range(uncheckedBounds: (index, self.index(after: index)))
var result: Element?
@@ -83,7 +87,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
return result
}
- @inlinable
+ @_alwaysEmitIntoClient
public mutating func removeSubrange(_ bounds: Range) {
replace(
removing: bounds,
@@ -92,12 +96,39 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
initializingWith: { _ in })
}
- @inlinable
- public mutating func removeAll() {
- removeSubrange(startIndex ..< endIndex)
+ @_alwaysEmitIntoClient
+ public mutating func removeFirst() -> Element {
+ precondition(
+ !isEmpty,
+ "Can't remove first element from an empty container")
+ return self.remove(at: self.startIndex)
}
- @inlinable
+ @_alwaysEmitIntoClient
+ public mutating func removeFirst(_ n: Int) {
+ if n == 0 { return }
+ precondition(n >= 0, "Number of elements to remove should be non-negative")
+ let start = self.startIndex
+ guard
+ let end = self.index(start, offsetBy: n, limitedBy: endIndex)
+ else {
+ preconditionFailure(
+ "Can't remove more items from a container than it has")
+ }
+ removeSubrange(start ..< end)
+ }
+
+ @_alwaysEmitIntoClient
+ public mutating func _customRemoveLast() -> Element? {
+ nil
+ }
+
+ @_alwaysEmitIntoClient
+ public mutating func _customRemoveLast(_ n: Int) -> Bool {
+ false
+ }
+
+ @_alwaysEmitIntoClient
public mutating func insert(
addingCount newItemCount: Int,
at index: Index,
@@ -110,7 +141,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
initializingWith: initializer)
}
- @inlinable
+ @_alwaysEmitIntoClient
public mutating func insert(
_ item: consuming Element, at index: Index
) {
@@ -120,7 +151,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
}
}
- @inlinable
+ @_alwaysEmitIntoClient
public mutating func append(
addingCount newItemCount: Int,
initializingWith initializer: (inout OutputSpan) throws(E) -> Void
@@ -131,7 +162,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
initializingWith: initializer)
}
- @inlinable
+ @_alwaysEmitIntoClient
public mutating func append(_ item: consuming Element) {
insert(item, at: endIndex)
}
@@ -139,11 +170,11 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
//MARK: - Standard Extensions
-@available(SwiftStdlib 5.0, *)
+@available(SwiftStdlib 6.4, *)
extension RangeReplaceableContainer
where Self: ~Copyable & ~Escapable, Element: ~Copyable
{
- @inlinable
+ @_alwaysEmitIntoClient
public mutating func replace<
E: Error,
P: Producer & ~Copyable & ~Escapable
@@ -164,7 +195,24 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable
})
}
- @inlinable
+ @_alwaysEmitIntoClient
+ public mutating func replace<
+ E: Error,
+ P: CountedProducer & ~Copyable & ~Escapable
+ >(
+ removing subrange: some RangeExpression2,
+ addingFrom producer: consuming P
+ ) throws(P.Failure)
+ where P.Element: ~Copyable
+ {
+ try replace(
+ removing: subrange,
+ addingCount: producer.count,
+ from: &producer)
+ try producer._expectEnd("Invalid Container")
+ }
+
+ @_alwaysEmitIntoClient
public mutating func replace(
removing subrange: some RangeExpression2