diff --git a/Documentation/Container-design.md b/Documentation/Container-design.md new file mode 100644 index 00000000..a2e5acbe --- /dev/null +++ b/Documentation/Container-design.md @@ -0,0 +1,1061 @@ +# An Ownership-Aware Container Model for Swift + +* Author: [Karoy Lorentey](https://github.com/lorentey) +* Version history: + - 0.1 (2026-07-21): Initial draft, describing `Container`. + +## Table of Contents + + * [Introduction](#introduction) + * [Making Sense of the Design Space](#making-sense-of-the-design-space) + * ["Elementwise Iteration" vs "Bulk Iteration"](#elementwise-iteration-vs-bulk-iteration) + * ["Iteration by Borrowing" vs "Iteration by Taking"](#iteration-by-borrowing-vs-iteration-by-taking) + * ["Generative" vs "Visitative Iteration"](#generative-vs-visitative-iteration) + * [Failability](#failability) + * [Read\-Only Container Model](#read-only-container-model) + * [Counting Elements](#counting-elements) + * [Container Indices](#container-indices) + * [Visitative Iteration](#visitative-iteration) + * [Subscripting](#subscripting) + * [Interaction with Iterable](#interaction-with-iterable) + * [ContainerIterator](#containeriterator) + * [Conversions Between Indices and Iterators](#conversions-between-indices-and-iterators) + * [Default Implementations of Iterable requirements](#default-implementations-of-iterable-requirements) + * [Optional Lookup Hooks](#optional-lookup-hooks) + * [Performance Requirements](#performance-requirements) + * [Conforming to Container](#conforming-to-container) + * [Bidirectional Containers](#bidirectional-containers) + * [Random\-Access Containers](#random-access-containers) + * [Mutable Containers](#mutable-containers) + * [protocol PermutableContainer](#protocol-permutablecontainer) + * [protocol MutableContainer](#protocol-mutablecontainer) + * [Producers](#producers) + * [In\-Place Consumption](#in-place-consumption) + * [struct InputSpan](#struct-inputspan) + * [protocol Drain](#protocol-drain) + * [Range\-Replaceable Containers](#range-replaceable-containers) + * [Index Ranges and Range Expressions](#index-ranges-and-range-expressions) + * [Adding Elements to a Container](#adding-elements-to-a-container) + * [Replacing Subranges](#replacing-subranges) + * [Consuming Subranges](#consuming-subranges) + * [Removing Subranges](#removing-subranges) + * [Dynamic Containers](#dynamic-containers) + * [Rejected Directions](#rejected-directions) + * [Cursors](#cursors) + * [Index Rounding Operations](#index-rounding-operations) + * [Potential Future Directions](#potential-future-directions) + * [Support for Nonescapable Element Types](#support-for-nonescapable-element-types) + * [Factoring Indexing Out of Containers](#factoring-indexing-out-of-containers) + * [A Protocol for Directly Initializing Storage](#a-protocol-for-directly-initializing-storage) + +## Introduction + +Over the last several years, we've been [gradually][BorrowingConsuming] [building][NoncopyableTypes] [up][NoncopyableGenerics] [an][PartialConsumption] [ownership][PatternMatching] [model][NonescapableTypes] [for][SuppressedAssociatedTypes] [Swift][BorrowAndMutate], to simplify the creation of safe high-performance Swift code. Our goal is to fulfill Swift's mandate to become a high-performance systems programming language, suitable for use in all computing tasks, from the smallest microcontrollers to the largest supercomputers. As many of the target environments need to operate within strict performance constraints, developers who specialize in them expect to have precise, predictable control over runtime behavior, even at the cost of some coding flexibility. + +[BorrowingConsuming]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0377-parameter-ownership-modifiers.md +[NoncopyableTypes]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0390-noncopyable-structs-and-enums.md +[NoncopyableGenerics]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0427-noncopyable-generics.md +[PartialConsumption]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0429-partial-consumption.md +[PatternMatching]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0432-noncopyable-switch.md +[NonescapableTypes]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0446-non-escapable.md +[SuppressedAssociatedTypes]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0503-suppressed-associated-types.md +[BorrowAndMutate]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0507-borrow-accessors.md +[YieldingAccessors]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0474-yielding-accessors.md +[TypedThrows]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0413-typed-throws.md + +Crucially, Swift needs to satisfy this need without resorting to unsafe interfaces: our aim is to build constructs that can match (or exceed) the performance of legacy systems programming languages, while also avoiding undefined behavior if the interfaces get misused. + +As of Swift 6.4, we have implemented a small but quickly growing list of useful data structures that follow these new design priorities: + +- Members of the nonescapable span family provide safe, direct access to "somebody else's" contiguous pieces of memory. + - [`Span`][Span], a read-only reference to fully initialized memory + - [`MutableSpan`][MutableSpan], a mutable reference to fully initialized memory + - [`OutputSpan`][OutputSpan], a safe reference to a fixed-capacity buffer of initializable memory + - (in swift-collections) [`InputSpan`][InputSpan], a safe reference to a fixed-capacity buffer of consumable memory +- We also have ownership-aware implementations of some basic data structures. + - [`InlineArray`][InlineArray] is a homogeneous tuple/vector type + - [`UniqueArray`][UniqueArray] is a dynamically resizing array type + - (in swift-collections) [`RigidArray`][RigidArray] is a fixed-capacity array type + - (in swift-collections) [`RigidDeque`][RigidDeque] and [`UniqueDeque`][UniqueDeque] implement ring buffers + - (in swift-collections) [`RigidSet`][RigidSet] and [`UniqueSet`][UniqueSet] are hashed sets of unique items + - (in swift-collections) [`RigidDictionary`][RigidDictionary] and [`UniqueDictionary`][UniqueDictionary] are hashed dictionary types + +[Span]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0447-span-access-shared-contiguous-storage.md +[InlineArray]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0453-vector.md +[MutableSpan]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0467-MutableSpan.md +[OutputSpan]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0485-outputspan.md +[Iterable]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0516-borrowing-sequence.md +[RefAndMutableRef]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0519-ref-mutableref-types.md +[UniqueArray]: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0527-rigidarray-uniquearray.md +[InputSpan]: https://github.com/apple/swift-collections/blob/main/Sources/ContainersPreview/Types/InputSpan.swift +[RigidArray]: https://swiftpackageindex.com/apple/swift-collections/main/documentation/basiccontainers/rigidarray +[RigidSet]: https://github.com/apple/swift-collections/tree/main/Sources/BasicContainers/RigidSet +[UniqueSet]: https://github.com/apple/swift-collections/tree/main/Sources/BasicContainers/UniqueSet +[RigidDictionary]: https://github.com/apple/swift-collections/tree/main/Sources/BasicContainers/RigidDictionary +[UniqueDictionary]: https://github.com/apple/swift-collections/tree/main/Sources/BasicContainers/UniqueDictionary +[RigidDeque]: https://swiftpackageindex.com/apple/swift-collections/main/documentation/dequemodule/rigiddeque +[UniqueDeque]: https://swiftpackageindex.com/apple/swift-collections/main/documentation/dequemodule/uniquedeque + +[BitSet]: https://swiftpackageindex.com/apple/swift-collections/main/documentation/bitcollections/bitset +[BitArray]: https://swiftpackageindex.com/apple/swift-collections/main/documentation/bitcollections/bitarray + +At first glance, these types have the basic shape of a Swift `Collection`: + +- They have a generic `Element` type +- They have the concept of an `Index`, modeling an abstract position within their storage +- They come with `subscript` operations that provide access to the element at a specific index +- They provide familiar operations for advancing an index to the next logical position, calculating distances between indices and similar tasks. + +However, unlike `Collection`s, these types can contain noncopyable elements, and most of them are noncopyable and/or nonescapable types themselves. These are significant complications, as our classic `Collection` protocols have been built upon the assumption of universal copyability and escapability, and it isn't feasible to factor out these assumptions without breaking the protocols. (The `SubSequence` and `Indices` associated types are particularly problematic.) + +## Making Sense of the Design Space + +Swift 6.4 introduced [protocol `Iterable`][Iterable] to enable borrowing for-in loops over these new types. The new protocol made several notable choices in the design space of ownership-aware iteration; it is crucial that we identify them so that we can carefully examine the purpose and consequences of each one, and so that we are able to analyze alternative choices. Each specific choice defines a particular design axis; we'll give them names that reflect their purpose. + +We do this not to criticize the design of `Iterable`, but to understand the use cases for which it is best suited, and to allow us to explore the full design space with intention. Identifying design axes allows us to derive a full set of potential abstractions almost mechanically, so that we can analyze them and develop the ones that seem most useful into concrete protocols in the rest of this document. + +We list the four axes we are considering below. The rest of this introductory section will define each of these in detail, but their names already give us a hint of their purpose: + +1. **Elementwise** versus **bulk** iteration -- iteration may expose a single element at a time, or it may give access to multiple elements all at once. +2. Iteration by **borrowing elements** vs iteration by **taking elements** -- whether iteration transfers ownership of the elements it traverses to the client. +3. **Generative** vs **visitative** iteration -- conforming types may be allowed to materialize their contents on the fly, or iteration may require to merely visit preexisting elements. +4. **Failable** and **non-failable** iteration -- whether iteration is allowed to throw an error. + +Under these terms, our classic `Sequence` models _non-failable, generative, elementwise iteration by taking elements_.
+The new `Iterable` protocol models _failable, generative, bulk iteration by borrowing elements_. + +In the rest of this document, we'll define three additional core protocols, `Container`, `Producer` and `Drain` (as well as a number of auxiliary protocols refining them). The four core protocols have the following properties and relationships: + +| Protocol | Elementwise/bulk | Borrowing/taking | Generative/Visitative | Failable | +| :--- | :--- | :---: | :---: | :---: | +| [`Iterable`][Iterable] | bulk (`Span`-based) | borrowing | generative | failable | +| `└╴`[`Container`](#read-only-container-model) | bulk (`Span`-based) | borrowing | visitative | -- | +| [`Producer`](#producers) | bulk (`OutputSpan`-based) | taking | generative | failable | +| `└╴`[`Drain`](#protocol-drain) | bulk (`InputSpan`-based) | taking | visitative | -- | + +We can already use this table to gain some interesting observations: + +- Our proposed new protocols all have a strong preference towards bulk (rather than elementwise) iteration. +- "Iteration by borrowing" and "iteration by taking" are independent abstractions; they are both useful enough to deserve their separate protocol hierarchies. +- The design indicates that the generative iteration model is a "wider" or "weaker" abstraction than the "narrower"/"stronger" visitative one; both visitative protocols refine their generative counterparts. This is, to some extent, intuitively understandable: a protocol that only works with preexisting elements can also implement an interface that allows them to be generated on the fly. In exchange, the visitative protocols can provide richer, more specialized abstractions. +- This design also strongly correlates failability with generative iteration. Neither of our proposed "visitative" protocols is failable. This too follows from the fact that visitative iteration merely accesses elements that already exist; there isn't much possibility for these accesses to fail. + +Let's now explore this design space a little further, by looking at the benefits and consequences of each decision. + +### "Elementwise Iteration" vs "Bulk Iteration" + +The classic `Sequence` models iteration by exposing elements one by one, through its iterator's `next()` method. + +```swift + mutating func next() -> Element? +``` + +This model of **elementwise iteration** is extremely straightforward to understand, and with a little practice we can write a rich variety of elementwise algorithms (almost) without thinking. However, it is not necessarily the most efficient way to iterate over things -- especially not over containers that organize their elements into piecewise contiguous storage chunks. + +In elementwise iteration, we need to call a protocol's customizable entry point for each and every item we traverse. The entry point needs to load the iteration's current state, and find (or generate) the next element to visit -- precisely what that means varies wildly between each type we want to iterate over. + +This makes it much harder for the compiler to reliably reason about and optimize code using `Sequence` types; this is especially difficult for sequences whose definitions are hidden behind a resilience boundary. In classic Swift, it isn't uncommon to see performance drop by a factor of hundreds as an operation's implementation moves across resilient module boundaries. As library evolution is a crucial feature of the language, this is rather unfortunate. + +The new `Iterable` protocol resolves this issue by introducing the idea of **bulk iteration**, where each primitive iteration step exposes multiple items all at once to the client, batched up into a `Span` instance. + +```swift + mutating func nextSpan(maxCount: Int) throws(Failure) -> Span +``` + +`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, consumingWith consumer: (inout InputSpan) -> Void, @@ -178,7 +226,21 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable initializingWith: initializer) } - @inlinable + // This unavailable default implementation of the protocol requirement + // prevents incomplete RangeReplaceableContainer implementations from + // satisfying the protocol through the use of the generic algorithm above. + @available(*, unavailable) + @_alwaysEmitIntoClient + public mutating func replace( + removing subrange: Range, + consumingWith consumer: (inout InputSpan) -> Void, + addingCount newItemCount: Int, + initializingWith initializer: (inout OutputSpan) throws(E) -> Void + ) throws(E) { + fatalError() + } + + @_alwaysEmitIntoClient public mutating func replace( removing subrange: some RangeExpression2, addingCount newItemCount: Int, @@ -191,29 +253,48 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable initializingWith: initializer) } - @inlinable + @_alwaysEmitIntoClient + public mutating func replace< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + removing targetSubrange: some RangeExpression2, + moving source: inout C + ) where C.Element: ~Copyable { + replace(removing: targetSubrange, addingFrom: source.consumeAll()) + } + + @_alwaysEmitIntoClient public mutating func replace< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( removing targetSubrange: some RangeExpression2, moving sourceSubrange: some RangeExpression2, from source: inout C - ) { + ) where C.Element: ~Copyable { let sourceSubrange = sourceSubrange.relative(to: source) let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) var producer = source.consume(sourceSubrange) let targetSubrange = targetSubrange.relative(to: self) self.replace(removing: targetSubrange, addingCount: c, from: &producer) - if !producer._isAtEnd() { - preconditionFailure("Invalid Container") - } + producer._expectEnd("Invalid Container") } + + @_alwaysEmitIntoClient + public mutating func replace< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + removing targetSubrange: some RangeExpression2, + consuming source: consuming C + ) where C.Element: ~Copyable { + replace(removing: targetSubrange, addingFrom: source.consumeAll()) + } + } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + @_alwaysEmitIntoClient public mutating func consume( _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void @@ -227,13 +308,13 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { }) } - @inlinable + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consumeAll() -> SubrangeConsumer { consume(startIndex ..< endIndex) } - @inlinable + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consume( _ subrange: some RangeExpression2 @@ -241,7 +322,17 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { consume(subrange.relative(to: self)) } - @inlinable + // This unavailable default implementation of the protocol requirement + // prevents incomplete RangeReplaceableContainer implementations from + // satisfying the protocol through the use of the generic algorithm above. + @available(*, unavailable) + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func consume(_ subrange: Range) -> SubrangeConsumer { + fatalError() + } + + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consume( _ subrange: UnboundedRange @@ -249,7 +340,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { consume(startIndex ..< endIndex) } - @inlinable + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consumeFirst(_ n: Int) -> SubrangeConsumer { precondition(n >= 0, "Count of elements to consume is out of bounds") @@ -262,14 +353,14 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: BidirectionalContainer, Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + @_alwaysEmitIntoClient @_lifetime(&self) public mutating func consumeLast(_ n: Int) -> SubrangeConsumer { precondition(n >= 0, "Count of elements to consume is out of bounds") @@ -282,18 +373,23 @@ where } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + @_alwaysEmitIntoClient + public mutating func removeAll() { + removeSubrange(startIndex ..< endIndex) + } + + @_alwaysEmitIntoClient public mutating func removeSubrange( _ bounds: some RangeExpression2 ) { removeSubrange(bounds.relative(to: self)) } - @inlinable + @_alwaysEmitIntoClient public mutating func removeSubrange( _ bounds: UnboundedRange ) { @@ -301,49 +397,184 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) +extension RangeReplaceableContainer +where Self: BidirectionalContainer & ~Copyable & ~Escapable, Element: ~Copyable +{ + @_alwaysEmitIntoClient + public mutating func removeLast() -> Element { + precondition( + !self.isEmpty, + "Can't remove last element from an empty container") + if let result = self._customRemoveLast() { return result } + return self.remove(at: self.index(before: self.endIndex)) + } + + @_alwaysEmitIntoClient + public mutating func removeLast(_ n: Int) { + if n == 0 { return } + precondition(n >= 0, "Number of elements to remove should be non-negative") + if self._customRemoveLast(n) { + return + } + let end = self.endIndex + guard let start = self.index(end, offsetBy: -n, limitedBy: self.startIndex) + else { + preconditionFailure( + "Can't remove more items from a collection than it contains") + } + self.removeSubrange(start ..< end) + } +} + +@available(SwiftStdlib 6.4, *) +extension RangeReplaceableContainer +where Self: BidirectionalContainer & ~Copyable & ~Escapable, Element: ~Copyable +{ + @_alwaysEmitIntoClient + public mutating func popLast() -> Element? { + if self.isEmpty { return nil } + if let result = self._customRemoveLast() { return result } + return self.remove(at: self.index(before: self.endIndex)) + } +} + +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + /// Inserts at most `newItemCount` items generated by a producer into this + /// container, starting at the given index. + /// + /// The target container must be able to accommodate the specified number + /// of new items. + /// + /// 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 it, then extra items remain available after this method returns. + /// + /// If the operation ends up inserting fewer than `newItemCount` items, then + /// it may leave a gap that needs to be closed (e.g., by compacting storage) + /// to restore invariants before the function returns. This may add some + /// overhead compared to adding exactly as many items as promised. + /// + /// - Parameters: + /// - newItemCount: The maximum number of items to insert into the container. + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the container. + /// - producer: A producer that generates the items to append. + @_alwaysEmitIntoClient public mutating func insert< E: Error, P: Producer & ~Copyable & ~Escapable >( addingCount newItemCount: Int, - at index: Index, - from producer: inout P + from producer: inout P, + at index: Index ) throws(E) where P.Element: ~Copyable { try self.insert(addingCount: newItemCount, at: index) { target throws(E) in while !target.isFull, try producer.generate(into: &target) { + // Do nothing } } } - @inlinable + /// Inserts all items generated by a producer into this container, + /// starting at the given index. + /// + /// The target container must be able to accommodate every item that the + /// producer generates. + /// + /// This operation inserts as many items as the producer can generate before + /// hitting its end, or throwing an error. + /// + /// If the producer throws an error, then the operation preserves all items + /// that it previously managed to insert before rethrowing the error. + /// If this happens, then the failed insertions may leave a gap that needs to + /// be carefully closed (e.g., by compacting storage) to restore invariants + /// before the function returns. This may add some overhead compared to adding + /// exactly as many items as promised. + /// + /// - Parameters: + /// - index: The position at which to insert the new items. + /// `index` must be a valid index in the container. + /// - producer: A producer that generates the items to append. + @_alwaysEmitIntoClient + public mutating func insert< + E: Error, + P: CountedProducer & ~Copyable & ~Escapable + >( + from producer: consuming P, + at index: Index + ) throws(E) + where P.Element: ~Copyable + { + let c = producer.count + try self.insert(addingCount: c, at: index) { target throws(E) in + while !target.isFull, try producer.generate(into: &target) { + } + } + try producer._expectEnd("Invalid Container") + } + + @_alwaysEmitIntoClient + public mutating func insert< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + moving source: inout C, + at index: Index + ) where C.Element: ~Copyable { + self.insert(from: source.consumeAll(), at: index) + } + + @_alwaysEmitIntoClient public mutating func insert< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( - at index: Index, moving sourceSubrange: some RangeExpression2, - from source: inout C - ) { + from source: inout C, + at index: Index + ) where C.Element: ~Copyable { let sourceSubrange = sourceSubrange.relative(to: source) let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) var producer = source.consume(sourceSubrange) - self.insert(addingCount: c, at: index, from: &producer) - if !producer._isAtEnd() { - preconditionFailure("Invalid Container") - } + self.insert(addingCount: c, from: &producer, at: index) + producer._expectEnd("Invalid Container") + } + + @_alwaysEmitIntoClient + public mutating func insert< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + consuming source: consuming C, + at index: Index + ) where C.Element: ~Copyable { + self.insert(from: source.consumeAll(), at: index) } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - @inlinable + /// Appends at most `newItemCount` items generated by a producer to the end of + /// this container. + /// + /// The container must be able to accommodate the specified number of new + /// items. + /// + /// This operation appends as many items as the producer can generate before + /// either reaching its end, 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 number of items to append to the container. + /// - producer: A producer that generates the items to append. + @_alwaysEmitIntoClient public mutating func append< E: Error, P: Producer & ~Copyable & ~Escapable @@ -353,35 +584,92 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { ) throws(E) where P.Element: ~Copyable { - try insert(addingCount: newItemCount, at: endIndex, from: &producer) + try insert(addingCount: newItemCount, from: &producer, at: endIndex) } - @inlinable + /// Appends all items generated by the given producer to the end of + /// this container. + /// + /// The container must be able to accommodate all items. + /// + /// This operation appends all items the producer generates before reaching + /// its end or throwing an error. If the producer throws an error, the + /// operation preserves all previously appended items before rethrowing the + /// error. + /// + /// - Parameters: + /// - producer: A producer that generates the items to append. + @_alwaysEmitIntoClient + public mutating func append< + E: Error, + P: CountedProducer & ~Copyable & ~Escapable + >( + from producer: consuming P + ) throws(E) + where P.Element: ~Copyable + { + try append(addingCount: producer.count, from: &producer) + try producer._expectEnd("Invalid Container") + } + + /// Moves the elements of a given container into the end of this one, leaving + /// the source container empty. + /// + /// The target container must be able to accommodate all items in the source + /// container. + /// + /// - Parameters: + /// - items: A container whose contents to move into this container. + @_alwaysEmitIntoClient + public mutating func append< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + moving items: inout C + ) where C.Element: ~Copyable { + self.append(from: items.consumeAll()) + } + + @_alwaysEmitIntoClient public mutating func append< C: RangeReplaceableContainer & ~Copyable & ~Escapable >( moving sourceSubrange: some RangeExpression2, from source: inout C - ) { + ) where C.Element: ~Copyable { let sourceSubrange = sourceSubrange.relative(to: source) let c = source.distance(from: sourceSubrange.lowerBound, to: sourceSubrange.upperBound) var producer = source.consume(sourceSubrange) self.append(addingCount: c, from: &producer) - if !producer._isAtEnd() { - preconditionFailure("Invalid Container") - } + producer._expectEnd("Invalid Container") + } + + /// Appends the elements of a given container to the end of this one by + /// consuming the source container. + /// + /// The target container must be able to accommodate all items in the source + /// container. + /// + /// - Parameters: + /// - items: A container whose contents to move into this container. + @_alwaysEmitIntoClient + public mutating func append< + C: RangeReplaceableContainer & ~Copyable & ~Escapable + >( + consuming items: consuming C + ) where C.Element: ~Copyable { + self.append(from: items.consumeAll()) } } //MARK: - Standard Extensions Requiring Copyability -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension RangeReplaceableContainer where Self: ~Copyable & ~Escapable, Element: Copyable { - @inlinable + @_alwaysEmitIntoClient public mutating func replace & ~Copyable & ~Escapable>( removing subrange: Range, copying items: borrowing C @@ -389,31 +677,129 @@ where var c = items.count var i = items.startIndex self.replace(removing: subrange, addingCount: c) { target in - let source = items.nextSpan(after: &i, maximumCount: target.freeCapacity) + let source = items.nextSpan(after: &i, maxCount: target.freeCapacity) target._append(copying: source) c -= source.count } precondition(c == 0, "Invalid RangeReplaceableContainer") } - @inlinable + @_alwaysEmitIntoClient + internal mutating func _insertContainer< + C: Container & ~Copyable & ~Escapable + >( + addingCount newCount: Int, + copying items: borrowing C, + at index: Index + ) { + var it = items.makeBorrowingIterator_() + insert(addingCount: newCount, at: index) { target in + while !target.isFull { + let source = it.nextSpan_(maxCount: target.freeCapacity) + precondition(!source.isEmpty, "Broken container: mismatching count") + target._append(copying: source) + } + } + precondition(it.nextSpan_().isEmpty, "Broken container: mismatching count") + } + + @_alwaysEmitIntoClient + package mutating func _insertCollection( + addingCount newCount: Int, + copying items: some Collection, + at index: Index + ) { + 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) + } + } + if done != nil { return } + 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") + } + + /// Copies the elements of a source container into this container, starting + /// at the specified target position. + /// + /// The new elements are inserted before the element currently at the + /// specified index in `self`. If you pass the target's `endIndex` as + /// the `index` parameter, then the new elements are appended to the end. + /// + /// The target container must be able to accommodate all items in the source + /// container. + /// + /// - Parameters: + /// - items: The new elements to insert into the container. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + @_alwaysEmitIntoClient + @inline(__always) public mutating func insert< C: Container & ~Copyable & ~Escapable >( copying items: borrowing C, at index: Index ) { - var c = items.count - var i = items.startIndex - insert(addingCount: c, at: index) { target in - let source = items.nextSpan(after: &i, maximumCount: target.freeCapacity) - c -= source.count - target._append(copying: source) - } - precondition(c == 0, "Invalid RangeReplaceableContainer") + _insertContainer( + addingCount: items.count, copying: items, at: index) } - @inlinable + /// Copies the elements of a collection into this container at the specified + /// position. + /// + /// The new elements are inserted before the element currently at the + /// specified index. If you pass the container's `endIndex` as the `index` + /// parameter, then the new elements are appended to the end. + /// + /// The target container must be able to accommodate all items in the source + /// container. + /// + /// - Parameters: + /// - items: The new elements to insert into the container. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert( + copying items: some Collection, at index: Index + ) { + _insertCollection(addingCount: items.count, copying: items, at: index) + } + + /// Copies the elements of a source container into this container, starting + /// at the specified target position. + /// + /// The new elements are inserted before the element currently at the + /// specified index in `self`. If you pass the target's `endIndex` as + /// the `index` parameter, then the new elements are appended to the end. + /// + /// The target container must be able to accommodate all items in the source + /// container. + /// + /// - Parameters: + /// - items: The new elements to insert into the container. + /// - index: The position at which to insert the new elements. It must be + /// a valid index of `self`. + @_alwaysEmitIntoClient + @inline(__always) + public mutating func insert< + C: Container & Collection + >( + copying items: borrowing C, at index: Index + ) { + _insertContainer( + addingCount: items.count, copying: items, at: index) + } + + @_alwaysEmitIntoClient public mutating func append( copying items: Span ) { @@ -425,20 +811,65 @@ where precondition(items.isEmpty, "Invalid RangeReplaceableContainer") } - @inlinable - public mutating func append< + @_alwaysEmitIntoClient + package mutating func _appendIterable< S: Iterable_ & ~Copyable & ~Escapable >( 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 } self.append(copying: span) } } + + @_alwaysEmitIntoClient + public mutating func append< + S: Iterable_ & ~Copyable & ~Escapable + >( + copying items: borrowing S + ) throws(S.Failure_) + where S.Element_ == Element { + try _appendIterable(copying: items) + } + + /// Copies the elements of a sequence to the end of this container. + /// + /// The container must be able to accommodate all items in the sequence. + /// + /// - Parameters: + /// - newElements: The new elements to copy into the container. + @_alwaysEmitIntoClient + public mutating func append(copying newElements: some Sequence) { + let done: Void? = newElements.withContiguousStorageIfAvailable { buffer in + unsafe self.append(copying: buffer) + return + } + if done != nil { return } + + for item in newElements { + self.append(item) + } + } + + /// Copies the elements of an iterable to the end of this container. + /// + /// The container must be able to accommodate all items in the iterable. + /// + /// - Parameters: + /// - newElements: The new elements to copy into the container. + @_alwaysEmitIntoClient + public mutating func append< + Source: Iterable_ & Sequence + >( + copying newElements: Source + ) throws(Source.Failure_) + where Source.Element_ == Element { + try self._appendIterable(copying: newElements) + } } #endif diff --git a/Sources/ContainersPreview/Protocols/Container/Strideable+Limits.swift b/Sources/ContainersPreview/Protocols/Container/Strideable+Limits.swift index 0e090a09..ff29f1e0 100644 --- a/Sources/ContainersPreview/Protocols/Container/Strideable+Limits.swift +++ b/Sources/ContainersPreview/Protocols/Container/Strideable+Limits.swift @@ -11,6 +11,34 @@ // //===----------------------------------------------------------------------===// +extension Strideable { + @_alwaysEmitIntoClient + package func _clampedUp( + towards boundary: Self, maxDistance: Stride, limitedBy limit: Self + ) -> Self { + assert(self <= boundary) + assert(maxDistance >= 0) + let limit = (limit >= self ? Swift.min(limit, boundary) : boundary) + if limit.distance(to: self) <= maxDistance { + return limit + } + return self.advanced(by: maxDistance) + } + + @_alwaysEmitIntoClient + package func _clampedDown( + towards boundary: Self, maxDistance: Stride, limitedBy limit: Self + ) -> Self { + assert(self >= boundary) + assert(maxDistance >= 0) + let limit = (limit <= self ? Swift.max(limit, boundary) : boundary) + if self.distance(to: limit) <= maxDistance { + return limit + } + return self.advanced(by: -maxDistance) + } +} + extension Strideable { @inlinable package mutating func _advance( diff --git a/Sources/ContainersPreview/Protocols/CountedProducer.swift b/Sources/ContainersPreview/Protocols/CountedProducer.swift new file mode 100644 index 00000000..26d9601f --- /dev/null +++ b/Sources/ContainersPreview/Protocols/CountedProducer.swift @@ -0,0 +1,32 @@ +//===----------------------------------------------------------------------===// +// +// 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 + +/// A producer with an exact count. +@available(SwiftStdlib 5.0, *) +public protocol CountedProducer: ~Copyable, ~Escapable, Producer +where Element: ~Copyable +{ + var count: Int { get } +} + +@available(SwiftStdlib 5.0, *) +extension CountedProducer where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @_alwaysEmitIntoClient + @inline(__always) + public var underestimatedCount: Int { + count + } +} +#endif diff --git a/Sources/ContainersPreview/Protocols/Drain+Map.swift b/Sources/ContainersPreview/Protocols/Drain+Map.swift index 319091b8..9d041903 100644 --- a/Sources/ContainersPreview/Protocols/Drain+Map.swift +++ b/Sources/ContainersPreview/Protocols/Drain+Map.swift @@ -48,7 +48,7 @@ public struct DrainMapProducer< } @available(SwiftStdlib 5.0, *) -extension DrainMapProducer +extension DrainMapProducer: Producer where Base: ~Copyable & ~Escapable, Element: ~Copyable @@ -70,10 +70,10 @@ where @_lifetime(self: copy self) public mutating func generate( into target: inout OutputSpan - ) throws(Error) -> Bool { + ) throws(Failure) -> Bool { var success = false while !target.isFull { - var source = _base.drainNext(maximumCount: target.freeCapacity) + var source = _base.drainNext(maxCount: target.freeCapacity) if source.isEmpty { break } success = true while !source.isEmpty { @@ -82,6 +82,12 @@ where } return success } + + @inlinable + @_lifetime(self: copy self) + public mutating func skip(by n: inout Int) throws(Failure) { + _base.skip(by: &n) + } } #endif diff --git a/Sources/ContainersPreview/Protocols/Drain.swift b/Sources/ContainersPreview/Protocols/Drain.swift index 79ec964a..427151ab 100644 --- a/Sources/ContainersPreview/Protocols/Drain.swift +++ b/Sources/ContainersPreview/Protocols/Drain.swift @@ -22,11 +22,11 @@ /// moving their consumable contents to the client-supplied series of /// output spans. @available(SwiftStdlib 5.0, *) -public protocol Drain: Producer, ~Copyable, ~Escapable +public protocol Drain: CountedProducer, ~Copyable, ~Escapable where Element: ~Copyable, Failure == Never { /// Returns the next span of consumable items in the sequence underlying this - /// drain, of at most the specified maximum count. A `maximumCount` of nil + /// drain, of at most the specified maximum count. A `maxCount` of nil /// indicates no limit, meaning that the client is able to process an /// arbitrarily large number of elements. /// @@ -36,7 +36,7 @@ where Element: ~Copyable, Failure == Never /// /// While the returned input spans exist, they continue to mutate the drain, /// extending the exclusive access initiated by the call to - /// `drainNext(maximumCount:)`. To call this (or any other) method again, the + /// `drainNext(maxCount:)`. To call this (or any other) method again, the /// returned input span needs to be consumed or otherwise destroyed. /// /// Once this method returns, the contents of the resulting input span are @@ -47,7 +47,7 @@ where Element: ~Copyable, Failure == Never /// temporary location and later reinserting them into the underlying /// construct through some type-specific operations. /// - /// - Parameter maximumCount: The maximum number of items that the client + /// - Parameter maxCount: The maximum number of items that the client /// is prepared to consume, or nil if the client is able to process an /// arbitrary number of elements. If this is non-nil, then it must be a /// positive integer. @@ -57,7 +57,7 @@ where Element: ~Copyable, Failure == Never /// the end of the sequence. @_lifetime(&self) @_lifetime(self: copy self) - mutating func drainNext(maximumCount: Int) -> InputSpan + mutating func drainNext(maxCount: Int) -> InputSpan // TODO: The primary use case does not need this to throw; do we need to allow that? // Note: making this failable is not entirely straightforward, as there is no // easy way to signal partial success -- conforming implementations @@ -75,7 +75,7 @@ where Element: ~Copyable, Failure == Never // ) throws(E) -> R // // This would allow partial consumption, eliminating the need for - // `maximumCount`, but at the cost of having to deal with closures -- + // `maxCount`, but at the cost of having to deal with closures -- // it can be tricky to elegantly flow data/control in & out higher-order // functions. Allowing the function argument to throw also precludes // the drain itself from throwing, unless they are both required @@ -93,7 +93,7 @@ extension Drain where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// /// While the returned input spans exist, they continue to mutate the drain, /// extending the exclusive access initiated by the call to - /// `drain(maximumCount:)`. To call this (or any other) method again, the + /// `drain(maxCount:)`. To call this (or any other) method again, the /// returned input span needs to be consumed or otherwise destroyed. /// /// Once this method returns, the contents of the resulting input span are @@ -111,7 +111,7 @@ extension Drain where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_lifetime(self: copy self) @_transparent public mutating func drainNext() -> InputSpan { - drainNext(maximumCount: Int.max) + drainNext(maxCount: Int.max) } /// Generate the next batch of items into the supplied output span instance, @@ -165,52 +165,52 @@ extension Drain where Self: ~Copyable & ~Escapable, Element: ~Copyable { public mutating func generate( into target: inout OutputSpan ) throws(Never) -> Bool { - var source = self.drainNext(maximumCount: target.freeCapacity) + var source = self.drainNext(maxCount: target.freeCapacity) if source.isEmpty { return false } target._append(moving: &source) return true } - /// Skip at most the given number items in the underlying generative sequence, - /// decreasing it by the number of items successfully skipped. + /// Skip the given number items in the underlying generative sequence, + /// decreasing it by the number of items successfully skipped before hitting + /// the end of the sequence or an error. /// /// This is equivalent to generating the same number of items then immediately /// discarding them, except it may avoid the overhead of actually - /// materializing them. + /// materializing the elements. /// /// As soon as the producer has run out of items, all subsequent calls to - /// this method stop decrementing `remainder` and return false. + /// this method stop decrementing `n` and return false. /// - /// The default implementation of this method calls `generate(into:)` with - /// a small temporary buffer, immediately discarding all generated items. - /// Conforming types are encouraged to replace this default approach - /// with a more efficient implementation whenever it is possible to do so. + /// The default implementation of this method repeatedly calls + /// `generate(into:)` with a small temporary buffer, immediately discarding + /// all generated items. Conforming types are encouraged to replace this + /// default approach with a more efficient implementation whenever it is + /// possible to do so. /// /// ### Error handling /// /// This method throws an error to indicate a failure while trying to skip - /// the upcoming next item in the sequence. Failure may happen midway through - /// skipping a batch of items, in which case the `remainder` will still be + /// an upcoming item in the sequence. Failure may happen midway through + /// skipping a batch of items, in which case `n` will still be /// decremented by the number of elements that were successfully skipped - /// before encountering the problem. + /// before encountering the problem. This can be used to precisely track + /// the current position of the failed producer, allowing better diagnostics, + /// and allowing iteration to continue if the failure is resolvable. /// - /// - Parameter remainder: The maximum number of items remaining to skip. - /// This method decrements this value by the number of items it + /// - Parameter n: The number of items to skip. This must be greater than + /// zero. This method decrements this value by the number of items it /// successfully skipped before returning. - /// - Returns: A boolean value indicating whether the operation was able to - /// satisfy the request at least partially without hitting the end of the - /// underlying consumable sequence. @inlinable @_lifetime(self: copy self) - public mutating func skip( - upTo n: inout Int - ) -> Bool { // FIXME: Compiler crash when this declares throws(Failure) + public mutating func skip(by n: inout Int) { + // FIXME: Compiler crash when this declares throws(Failure) precondition(n >= 0, "Cannot skip a negative number of elements") - guard n > 0 else { return true } - let span = drainNext(maximumCount: n) - let success = span.count > 0 - n &-= span.count - return success + while n > 0 { + let span = drainNext(maxCount: n) + guard !span.isEmpty else { return } + n &-= span.count + } } } diff --git a/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift b/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift index 96b7f807..01780d9c 100644 --- a/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Algorithms.swift @@ -13,7 +13,7 @@ #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { @@ -23,7 +23,7 @@ extension Iterable_ _ nextPartialResult: (_ partialResult: consuming Result, borrowing Element_) throws(Failure_) -> Result ) throws(Failure_) -> Result { - try makeIterableIterator_().reduce(initialResult, nextPartialResult) + try makeBorrowingIterator_().reduce(initialResult, nextPartialResult) } @inlinable @@ -32,19 +32,19 @@ extension Iterable_ _ updateAccumulatingResult: (_ partialResult: inout Result, borrowing Element_) throws(Failure_) -> () ) throws(Failure_) -> Result { - try makeIterableIterator_().reduce(into: initialResult, updateAccumulatingResult) + try makeBorrowingIterator_().reduce(into: initialResult, updateAccumulatingResult) } } // Ambiguity breakers -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Sequence where Self: Iterable_ { public func reduce( _ initialResult: consuming Result, _ nextPartialResult: (_ partialResult: consuming Result, borrowing Element_) throws(Failure_) -> Result ) throws(Failure_) -> Result { - try makeIterableIterator_().reduce(initialResult, nextPartialResult) + try makeBorrowingIterator_().reduce(initialResult, nextPartialResult) } @inlinable @@ -53,11 +53,11 @@ extension Sequence where Self: Iterable_ { _ updateAccumulatingResult: (_ partialResult: inout Result, borrowing Element_) throws(Failure_) -> () ) throws(Failure_) -> Result { - try makeIterableIterator_().reduce(into: initialResult, updateAccumulatingResult) + try makeBorrowingIterator_().reduce(into: initialResult, updateAccumulatingResult) } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable { @@ -69,19 +69,19 @@ extension Iterable_ where OtherSequence: ~Copyable & ~Escapable, OtherSequence.Element_: ~Copyable, OtherSequence.Failure_ == Failure_ { // FIXME: Forward to the iterator's implementation of same - var iter1 = makeIterableIterator_() - var iter2 = other.makeIterableIterator_() + var iter1 = makeBorrowingIterator_() + var iter2 = other.makeBorrowingIterator_() while true { var el1 = try iter1.nextSpan_() if el1.isEmpty { // LHS is empty - sequences are equal iff RHS is also empty - let el2 = try iter2.nextSpan_(maximumCount: 1) + let el2 = try iter2.nextSpan_(maxCount: 1) return el2.isEmpty } while el1.count > 0 { - let el2 = try iter2.nextSpan_(maximumCount: el1.count) + let el2 = try iter2.nextSpan_(maxCount: el1.count) if el2.isEmpty { return false } for i in 0..=6.4) && UnstableContainersPreview - -@available(SwiftStdlib 5.0, *) -extension Span: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = SpanIterator - public typealias Element_ = Element - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeIterableIterator_() -> SpanIterator { - SpanIterator(self) - } -} - -@available(SwiftStdlib 5.0, *) -extension MutableSpan: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = SpanIterator - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeIterableIterator_() -> SpanIterator { - // 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? - SpanIterator(self.span) - } -} - -@available(SwiftStdlib 5.0, *) -extension OutputSpan: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = SpanIterator - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeIterableIterator_() -> IterableIterator_ { - SpanIterator(self.span) - } -} - -@available(SwiftStdlib 5.0, *) -extension InputSpan: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = SpanIterator - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeIterableIterator_() -> IterableIterator_ { - SpanIterator(self.span) - } -} - -@available(SwiftStdlib 6.2, *) -extension Array: Iterable_ { - public typealias IterableIterator_ = SpanIterator - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeIterableIterator_() -> IterableIterator_ { - SpanIterator(self.span) - } -} - -@available(SwiftStdlib 6.2, *) -extension InlineArray: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = SpanIterator - - @inlinable - public var underestimatedCount_: Int { count } - - @_lifetime(borrow self) - @inlinable - public func makeIterableIterator_() -> SpanIterator { - // 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? - SpanIterator(self.span) - } -} - -@available(SwiftStdlib 6.2, *) -extension Range: Iterable_ -where Bound: Strideable, Bound.Stride: SignedInteger -{ - public typealias Element = Bound - - @frozen - public struct IterableIterator_: IterableIteratorProtocol_, ~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_(maximumCount: 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 - } - } - - @_alwaysEmitIntoClient - @_transparent - package var _borrowingUnderestimatedCount: Int { - guard let count = Int(exactly: lowerBound.distance(to: upperBound)) else { - return 0 - } - return count - } - - @inlinable - public var underestimatedCount_: Int { _borrowingUnderestimatedCount } - - @inlinable - public func makeIterableIterator_() -> IterableIterator_ { - IterableIterator_(self) - } -} - -@available(SwiftStdlib 6.2, *) -extension ClosedRange: Iterable_ -where Bound: Strideable, Bound.Stride: SignedInteger -{ - public typealias Element = Bound - - @frozen - public struct IterableIterator_: IterableIteratorProtocol_, ~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_(maximumCount: 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 - } - } - - @_alwaysEmitIntoClient - @_transparent - package var _borrowingUnderestimatedCount: 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 var underestimatedCount_: Int { _borrowingUnderestimatedCount } - - @inlinable - public func makeIterableIterator_() -> IterableIterator_ { - IterableIterator_(self) - } -} - -#endif diff --git a/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift b/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift index c6734a32..b1f4de7a 100644 --- a/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift +++ b/Sources/ContainersPreview/Protocols/Iterable+Utilities.swift @@ -17,16 +17,16 @@ import InternalCollectionsUtilities #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: Copyable { @inlinable package func _copyContents( intoPrefixOf buffer: UnsafeMutableBufferPointer ) throws(Failure_) -> Int { var target = buffer - var it = self.makeIterableIterator_() + var it = self.makeBorrowingIterator_() while target.count != 0 { - let span = try it.nextSpan_(maximumCount: target.count) + let span = try it.nextSpan_(maxCount: target.count) if span.isEmpty { return buffer.count - target.count } diff --git a/Sources/ContainersPreview/Protocols/Iterable.swift b/Sources/ContainersPreview/Protocols/Iterable.swift index 359239fd..e6c97554 100644 --- a/Sources/ContainersPreview/Protocols/Iterable.swift +++ b/Sources/ContainersPreview/Protocols/Iterable.swift @@ -13,24 +13,30 @@ #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public protocol Iterable_: ~Copyable, ~Escapable { + // FIXME: None of these names should not have trailing underscores, but that + // would clash with the stdlib's versions: + // error: 'BorrowingIterator' is ambiguous for type lookup in this context + // + // This is likely best resolved by removing these definitions as soon as they + // appear in the stdlib. associatedtype Element_: ~Copyable associatedtype Failure_: Error = Never - associatedtype IterableIterator_: IterableIteratorProtocol_ & ~Copyable & ~Escapable + associatedtype BorrowingIterator_: BorrowingIteratorProtocol_ & ~Copyable & ~Escapable var underestimatedCount_: Int { get } @_lifetime(borrow self) - borrowing func makeIterableIterator_() -> IterableIterator_ + borrowing func makeBorrowingIterator_() -> BorrowingIterator_ func _customContainsEquatableElement_( _ element: borrowing Element_ ) -> Bool? } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: ~Copyable @@ -44,36 +50,15 @@ where } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: Sequence { + @inlinable + public var underestimatedCount_: Int { 0 } + @inlinable public func _customContainsEquatableElement_(_ element: borrowing Element) -> Bool? { nil } } -@available(SwiftStdlib 5.0, *) -extension Iterable_ -where - Self: ~Copyable & ~Escapable, - Element_: ~Copyable -{ - /// Implementation demo of what borrowing for-in loops would need to expand into. - @inlinable - public func _borrowingForEach( - _ body: (borrowing Element_) throws(Failure_) -> Void - ) throws(Failure_) -> Void { - var it = makeIterableIterator_() - while true { - let span = try it.nextSpan_() - if span.isEmpty { break } - var i = 0 - while i < span.count { - try body(span[unchecked: i]) - i &+= 1 - } - } - } -} - #endif diff --git a/Sources/ContainersPreview/Protocols/Producer+Collect.swift b/Sources/ContainersPreview/Protocols/Producer+Collect.swift index a1d169dd..da3caf38 100644 --- a/Sources/ContainersPreview/Protocols/Producer+Collect.swift +++ b/Sources/ContainersPreview/Protocols/Producer+Collect.swift @@ -15,6 +15,7 @@ @available(SwiftStdlib 5.0, *) extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @available(SwiftStdlib 6.4, *) @inlinable public consuming func collect< R: DynamicContainer & ~Copyable @@ -27,6 +28,7 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// Collect all items generated by this producer into the provided /// range-replaceable container instance, which must be able to accommodate /// every new element. + @available(SwiftStdlib 6.4, *) @inlinable public consuming func collect( into container: inout some RangeReplaceableContainer & ~Copyable & ~Escapable @@ -49,6 +51,7 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { /// Collect all items generated by this producer into the provided /// dynamic container instance, resizing it if necessary. + @available(SwiftStdlib 6.4, *) @inlinable public consuming func collect( into container: inout some DynamicContainer & ~Copyable diff --git a/Sources/ContainersPreview/Protocols/Producer+Filter.swift b/Sources/ContainersPreview/Protocols/Producer+Filter.swift index cec00ff5..e801694b 100644 --- a/Sources/ContainersPreview/Protocols/Producer+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Producer+Filter.swift @@ -11,6 +11,10 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) @@ -97,6 +101,8 @@ where } while target.count == startCount return target.count > startCount } + + // Note: We can't implement skip(by:) a better way than the default algorithm. } #endif diff --git a/Sources/ContainersPreview/Protocols/Producer+Map.swift b/Sources/ContainersPreview/Protocols/Producer+Map.swift index 05bba6be..7d120eff 100644 --- a/Sources/ContainersPreview/Protocols/Producer+Map.swift +++ b/Sources/ContainersPreview/Protocols/Producer+Map.swift @@ -11,6 +11,10 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) @@ -97,6 +101,12 @@ extension ConsumingMapProducer: Producer where Base: ~Copyable & ~Escapable { return result } } + + @inlinable + @_lifetime(self: copy self) + public mutating func skip(by n: inout Int) throws(Failure) { + try _base.skip(by: &n) + } } #endif diff --git a/Sources/ContainersPreview/Protocols/Producer+Reduce.swift b/Sources/ContainersPreview/Protocols/Producer+Reduce.swift index 1807dd18..89782a66 100644 --- a/Sources/ContainersPreview/Protocols/Producer+Reduce.swift +++ b/Sources/ContainersPreview/Protocols/Producer+Reduce.swift @@ -11,6 +11,10 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) @@ -23,22 +27,20 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { ) throws(Failure) -> Result ) throws(Failure) -> Result { var initialResult: Optional = initialResult - return try _withUnsafeTemporaryAllocation( + return try withTemporaryAllocation( of: Element.self, capacity: _producerBufferSize ) { buffer throws(Failure) in var done = false - var result = initialResult.take()! - while !done { - var span = OutputSpan(buffer: buffer, initializedCount: 0) - done = try !self.generate(into: &span) - let c = span.finalize(for: buffer) - for i in 0 ..< c { - result = try nextPartialResult( - result, - buffer.moveElement(from: i)) + var result = initialResult.take() + repeat { + done = try !self.generate(into: &buffer) + try buffer._consumeAll { span throws(Failure) in + while let next = span.popFirst() { + result = try nextPartialResult(result.take()!, next) + } } - } - return result + } while !done + return result! } } @@ -49,23 +51,22 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { inout Result, consuming Element ) throws(Failure) -> Void ) throws(Failure) -> Result { - var result = initialResult - try _withUnsafeTemporaryAllocation( + var initialResult: Optional = initialResult + return try withTemporaryAllocation( of: Element.self, capacity: _producerBufferSize ) { buffer throws(Failure) in + var result = initialResult.take()! var done = false - while !done { - var span = OutputSpan(buffer: buffer, initializedCount: 0) - done = try !self.generate(into: &span) - let c = span.finalize(for: buffer) - for i in 0 ..< c { - try updateAccumulatingResult( - &result, - buffer.moveElement(from: i)) + repeat { + done = try !self.generate(into: &buffer) + try buffer._consumeAll { span throws(Failure) in + while let next = span.popFirst() { + try updateAccumulatingResult(&result, next) + } } - } + } while !done + return result } - return result } } diff --git a/Sources/ContainersPreview/Protocols/Producer+Unfold.swift b/Sources/ContainersPreview/Protocols/Producer+Unfold.swift new file mode 100644 index 00000000..d4654537 --- /dev/null +++ b/Sources/ContainersPreview/Protocols/Producer+Unfold.swift @@ -0,0 +1,86 @@ +//===----------------------------------------------------------------------===// +// +// 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 + +@_lifetime(copy state) +public func producer< + State: ~Copyable & ~Escapable, + Failure: Error, + Element: ~Copyable +>( + state: consuming State, + next: @escaping (inout State) throws(Failure) -> Element? +) -> UnfoldProducer { + .init(state: state, next: next) +} + +@frozen +public struct UnfoldProducer< + State: ~Copyable & ~Escapable, + Failure: Error, + Element: ~Copyable +>: ~Copyable, ~Escapable { + @usableFromInline + internal let _next: (inout State) throws(Failure) -> Element? + + @usableFromInline + internal var _state: State + + @inlinable + @_lifetime(copy state) + public init( + state: consuming State, + next: @escaping (inout State) throws(Failure) -> Element? + ) { + self._next = next + self._state = state + } +} + +extension UnfoldProducer: Producer +where + State: ~Copyable & ~Escapable, + Element: ~Copyable +{ + @inlinable + public var underestimatedCount: Int { 0 } + + @inlinable + @discardableResult + @_lifetime(target: copy target) + @_lifetime(self: copy self) + public mutating func generate( + into target: inout OutputSpan + ) throws(Failure) -> Bool { + var c = 0 + while !target.isFull { + guard let next = try _next(&self._state) else { break } + target.append(next) + c += 1 + } + return c > 0 + } + + @inlinable + @_lifetime(self: copy self) + public mutating func next() throws(Failure) -> Element? { + try _next(&_state) + } +} + +#endif diff --git a/Sources/ContainersPreview/Protocols/Producer.swift b/Sources/ContainersPreview/Protocols/Producer.swift index eb848282..384b1697 100644 --- a/Sources/ContainersPreview/Protocols/Producer.swift +++ b/Sources/ContainersPreview/Protocols/Producer.swift @@ -11,6 +11,10 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + #if compiler(>=6.4) && UnstableContainersPreview @_alwaysEmitIntoClient @@ -96,37 +100,38 @@ public protocol Producer: ~Copyable, ~Escapable { into target: inout OutputSpan ) throws(Failure) -> Bool - /// Skip at most the given number items in the underlying generative sequence, - /// decreasing it by the number of items successfully skipped. + /// Skip the given number items in the underlying generative sequence, + /// decreasing it by the number of items successfully skipped before hitting + /// the end of the sequence or an error. /// /// This is equivalent to generating the same number of items then immediately /// discarding them, except it may avoid the overhead of actually - /// materializing them. + /// materializing the elements. /// /// As soon as the producer has run out of items, all subsequent calls to /// this method stop decrementing `n` and return false. /// - /// The default implementation of this method calls `generate(into:)` with - /// a small temporary buffer, immediately discarding all generated items. - /// Conforming types are encouraged to replace this default approach - /// with a more efficient implementation whenever it is possible to do so. + /// The default implementation of this method repeatedly calls + /// `generate(into:)` with a small temporary buffer, immediately discarding + /// all generated items. Conforming types are encouraged to replace this + /// default approach with a more efficient implementation whenever it is + /// possible to do so. /// /// ### Error handling /// /// This method throws an error to indicate a failure while trying to skip - /// the upcoming next item in the sequence. Failure may happen midway through + /// an upcoming item in the sequence. Failure may happen midway through /// skipping a batch of items, in which case `n` will still be /// decremented by the number of elements that were successfully skipped - /// before encountering the problem. + /// before encountering the problem. This can be used to precisely track + /// the current position of the failed producer, allowing better diagnostics, + /// and allowing iteration to continue if the failure is resolvable. /// - /// - Parameter n: The maximum number of items remaining to skip. This - /// must be greater than zero. This method decrements this value by the - /// number of items it successfully skipped before returning. - /// - Returns: A boolean value indicating whether the operation was able to - /// skip at least one item without hitting the end of the underlying - /// sequence. + /// - Parameter n: The number of items to skip. This must be greater than + /// zero. This method decrements this value by the number of items it + /// successfully skipped before returning. @_lifetime(self: copy self) - mutating func skip(by n: inout Int) throws(Failure) -> Bool + mutating func skip(by n: inout Int) throws(Failure) /// Generate and return the next element in the underlying generative /// sequence. @@ -174,48 +179,89 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @inline(__always) public var underestimatedCount: Int { 0 } - /// Skip at most the given number items in the underlying generative sequence, - /// decreasing it by the number of items successfully skipped. + /// Skip the given number items in the underlying generative sequence, + /// decreasing it by the number of items successfully skipped before hitting + /// the end of the sequence or an error. /// /// This is equivalent to generating the same number of items then immediately /// discarding them, except it may avoid the overhead of actually - /// materializing them. + /// materializing the elements. /// /// As soon as the producer has run out of items, all subsequent calls to /// this method stop decrementing `n` and return false. /// - /// The default implementation of this method calls `generate(into:)` with - /// a small temporary buffer, immediately discarding all generated items. - /// Conforming types are encouraged to replace this default approach - /// with a more efficient implementation whenever it is possible to do so. + /// The default implementation of this method repeatedly calls + /// `generate(into:)` with a small temporary buffer, immediately discarding + /// all generated items. Conforming types are encouraged to replace this + /// default approach with a more efficient implementation whenever it is + /// possible to do so. /// /// ### Error handling /// /// This method throws an error to indicate a failure while trying to skip - /// the upcoming next item in the sequence. Failure may happen midway through + /// an upcoming item in the sequence. Failure may happen midway through /// skipping a batch of items, in which case `n` will still be /// decremented by the number of elements that were successfully skipped - /// before encountering the problem. + /// before encountering the problem. This can be used to precisely track + /// the current position of the failed producer, allowing better diagnostics, + /// and allowing iteration to continue if the failure is resolvable. /// - /// - Parameter n: The maximum number of items remaining to skip. This - /// must be greater than zero. This method decrements this value by the - /// number of items it successfully skipped before returning. - /// - Returns: A boolean value indicating whether the operation was able to - /// skip at least one item without hitting the end of the underlying - /// sequence. + /// - Parameter n: The number of items to skip. This must be greater than + /// zero. This method decrements this value by the number of items it + /// successfully skipped before returning. @inlinable @_lifetime(self: copy self) - public mutating func skip(by n: inout Int) throws(Failure) -> Bool { + public mutating func skip(by n: inout Int) throws(Failure) { precondition(n > 0, "Cannot skip fewer than one item") - let maxBufferSize = 8 - return try withTemporaryOutputSpan( - of: Element.self, capacity: Swift.min(maxBufferSize, n) - ) { span throws(Failure) in - defer { n &-= span.count } - return try self.generate(into: &span) + let maxBufferSize = _producerBufferSize + return try withTemporaryAllocation( + of: Element.self, + capacity: Swift.min(maxBufferSize, n) + ) { buffer throws(Failure) in + repeat { + defer { n &-= buffer.count } + guard try self.generate(into: &buffer) else { return } + buffer.removeAll() + } while n > 0 } } + /// Skip the given number items in the underlying generative sequence, + /// returning the number of items successfully skipped before hitting the end + /// of the sequence. + /// + /// This is equivalent to generating the same number of items then immediately + /// discarding them, except it may avoid the overhead of actually + /// materializing the elements. + /// + /// If the producer runs out of items, all subsequent calls to + /// this method return zero without skipping any elements. + /// + /// ### Error handling + /// + /// This method throws an error to indicate a failure while trying to skip + /// an upcoming item in the sequence. Failure may happen midway through + /// skipping a batch of items, in which case this operation has no way to + /// report which item triggered the error. This is not an issue in the common + /// case when the iterator simply gets discarded anyway; however, when losing + /// position is not acceptable, it is recommended to avoid calling this + /// algorithm, and instead call the variant of `skip(by:)` that takes an inout + /// integer value. For example, this applies to use cases that need to report + /// the precise location of errors, and cases that are able to recover some + /// error conditions and want to be able to continue iterating without losing + /// data. + /// + /// - Returns: The number of items successfully skipped. This can be less than + /// `n` if the operation hits the end of the underlying sequence before + /// managing to skip the requested number of elements. + @inlinable + @_lifetime(self: copy self) + public mutating func skip(by n: Int) throws(Failure) -> Int { + var remainder = n + try self.skip(by: &remainder) + return n - remainder + } + /// Generate and return the next element in the underlying generative /// sequence. /// @@ -250,27 +296,27 @@ extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { @inlinable @_lifetime(self: copy self) public mutating func next() throws(Failure) -> Element? { - try _withUnsafeTemporaryAllocation( + try withTemporaryAllocation( of: Element.self, capacity: 1 ) { buffer throws(Failure) in - var span = OutputSpan(buffer: buffer, initializedCount: 0) - guard try self.generate(into: &span) else { return nil } - return span.removeLast() + guard try self.generate(into: &buffer) else { return nil } + return buffer.removeLast() } } } @available(SwiftStdlib 5.0, *) extension Producer where Self: ~Copyable & ~Escapable, Element: ~Copyable { - /// Returns true if the producer has no more elements, consuming it in + /// Triggers a runtime trap if the producer is not at its end, consuming it in /// the process. This is implemented by checking if it is possible to /// skip one item. - /// - /// This is useful in preconditions. @inlinable - public consuming func _isAtEnd() throws(Failure) -> Bool { + public consuming func _expectEnd( + _ message: String = "Invalid Producer" + ) throws(Failure) { var c = 1 - return try !skip(by: &c) + try skip(by: &c) + precondition(c == 0, message) } } diff --git a/Sources/ContainersPreview/Types/InputSpan.swift b/Sources/ContainersPreview/Types/InputSpan.swift index 2f4b6c48..53df7393 100644 --- a/Sources/ContainersPreview/Types/InputSpan.swift +++ b/Sources/ContainersPreview/Types/InputSpan.swift @@ -62,7 +62,7 @@ extension InputSpan where Element: ~Copyable { internal func _start() -> UnsafeMutableRawPointer { unsafe _pointer.unsafelyUnwrapped } - + @unsafe @_alwaysEmitIntoClient @_transparent @@ -177,7 +177,7 @@ extension InputSpan where Element: ~Copyable { capacity = buffer.count _count = initializedCount } - + @unsafe @_alwaysEmitIntoClient @_lifetime(borrow buffer) @@ -237,6 +237,28 @@ extension InputSpan where Element: ~Copyable { unsafe Range(uncheckedBounds: (0, _count)) } +#if compiler(>=6.4) + /// Accesses the element at the specified position. + /// + /// - Parameter index: A valid index into this span. + /// + /// - Complexity: O(1) + @_alwaysEmitIntoClient + public subscript(_ index: Index) -> Element { + @_unsafeSelfDependentResult + borrow { + precondition(indices.contains(index), "Index out of bounds") + return unsafe _unsafeAddressOfElement(uncheckedOffset: index).pointee + } + + @_unsafeSelfDependentResult + @_lifetime(self: copy self) + mutate { + precondition(indices.contains(index), "Index out of bounds") + return unsafe &_unsafeAddressOfElement(uncheckedOffset: index).pointee + } + } +#else /// Accesses the element at the specified position. /// /// - Parameter index: A valid index into this span. @@ -255,7 +277,30 @@ extension InputSpan where Element: ~Copyable { return unsafe _unsafeAddressOfElement(uncheckedOffset: index) } } +#endif +#if compiler(>=6.4) + /// Accesses the element at the specified position. + /// + /// This subscript does not validate `position`; this is an unsafe operation. + /// + /// - Parameter index: A valid index into this span. + /// + /// - Complexity: O(1) + @unsafe + @_alwaysEmitIntoClient + public subscript(unchecked index: Index) -> Element { + @_unsafeSelfDependentResult + borrow { + unsafe _unsafeAddressOfElement(uncheckedOffset: index).pointee + } + @_unsafeSelfDependentResult + @_lifetime(self: copy self) + mutate { + unsafe &_unsafeAddressOfElement(uncheckedOffset: index).pointee + } + } +#else /// Accesses the element at the specified position. /// /// This subscript does not validate `position`; this is an unsafe operation. @@ -274,6 +319,7 @@ extension InputSpan where Element: ~Copyable { unsafe _unsafeAddressOfElement(uncheckedOffset: index) } } +#endif /// Exchange the elements at the two given offsets /// @@ -346,7 +392,7 @@ extension InputSpan where Element: ~Copyable { } _count &-= k } - + /// Removes and returns the first element of this input span, if it exists. /// /// - Returns: The first element of the original span if it wasn't empty; @@ -435,18 +481,39 @@ extension InputSpan /* where Element: Copyable */ { @available(SwiftStdlib 5.0, *) extension InputSpan where Element: ~Copyable { + @inlinable + @unsafe + @_lifetime(borrow self) + internal func _uncheckedSpan(in range: Range) -> Span { + let pointer = unsafe _pointer? + .assumingMemoryBound(to: Element.self) + .advanced(by: capacity &- _count &+ range.lowerBound) + let buffer = unsafe UnsafeBufferPointer(start: pointer, count: range.count) + let span = unsafe Span(_unsafeElements: buffer) + return unsafe _overrideLifetime(span, borrowing: self) + } + + @inlinable + @unsafe + @_lifetime(&self) + internal mutating func _uncheckedMutableSpan(in range: Range) -> MutableSpan { + let pointer = unsafe _pointer? + .assumingMemoryBound(to: Element.self) + .advanced(by: capacity &- _count &+ range.lowerBound) + let buffer = unsafe UnsafeMutableBufferPointer( + start: pointer, count: range.count) + let span = unsafe MutableSpan(_unsafeElements: buffer) + return unsafe _overrideLifetime(span, mutating: &self) + } + /// Borrow the underlying initialized memory for read-only access. @available(SwiftStdlib 5.0, *) @_alwaysEmitIntoClient + @_transparent public var span: Span { @_lifetime(borrow self) borrowing get { - let pointer = unsafe _pointer? - .assumingMemoryBound(to: Element.self) - .advanced(by: capacity &- _count) - let buffer = unsafe UnsafeBufferPointer(start: pointer, count: _count) - let span = unsafe Span(_unsafeElements: buffer) - return unsafe _overrideLifetime(span, borrowing: self) + _uncheckedSpan(in: 0 ..< _count) } } @@ -456,13 +523,7 @@ extension InputSpan where Element: ~Copyable { public var mutableSpan: MutableSpan { @_lifetime(&self) mutating get { - let pointer = unsafe _pointer? - .assumingMemoryBound(to: Element.self) - .advanced(by: capacity &- _count) - let buffer = unsafe UnsafeMutableBufferPointer( - start: pointer, count: _count) - let span = unsafe MutableSpan(_unsafeElements: buffer) - return unsafe _overrideLifetime(span, borrowing: self) + _uncheckedMutableSpan(in: 0 ..< _count) } } } @@ -533,7 +594,7 @@ extension InputSpan where Element: ~Copyable { public mutating func consumePrefix(upTo n: Int) -> InputSpan { precondition(n >= 0, "Cannot consume a negative number of elements") let c = Swift.min(n, self.count) - + let buffer = unsafe _unsafeRawAddressOfSlot( uncheckedOffset: 0 ).withMemoryRebound(to: Element.self, capacity: c) { start in @@ -547,7 +608,7 @@ extension InputSpan where Element: ~Copyable { } @available(SwiftStdlib 5.0, *) -internal func withTemporaryInputSpan( +internal func _withTemporaryInputSpan( of type: Element.Type, capacity: Int, _ body: (inout InputSpan) throws(E) -> R @@ -561,20 +622,14 @@ internal func withTemporaryInputSpan } @available(SwiftStdlib 5.0, *) -extension OutputSpan where Element: ~Copyable { +extension InputSpan where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(self: copy self) package mutating func _consumeAll( consumingWith consumer: (inout InputSpan) -> Void ) { - self.withUnsafeMutableBufferPointer { buffer, count in - var span = InputSpan( - buffer: buffer._extracting(first: count), - initializedCount: count) - consumer(&span) - _ = consume span - count = 0 - } + consumer(&self) + self.removeAll() } } diff --git a/Sources/ContainersPreview/Types/OutputSpan+Helpers.swift b/Sources/ContainersPreview/Types/OutputSpan+Helpers.swift new file mode 100644 index 00000000..2389eb1a --- /dev/null +++ b/Sources/ContainersPreview/Types/OutputSpan+Helpers.swift @@ -0,0 +1,51 @@ +//===----------------------------------------------------------------------===// +// +// 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.2) && UnstableContainersPreview +@available(SwiftStdlib 5.0, *) +extension OutputSpan where Element: ~Copyable { + @_lifetime(source: copy source) + @inlinable + @inline(__always) + @_lifetime(self: copy self) + package mutating func _append(moving source: inout InputSpan) { + // FIXME: This needs to be in the stdlib. + source.withUnsafeMutableBufferPointer { src, srcCount in + let srcItems = src._extracting( + uncheckedFrom: src.count &- srcCount, + to: src.count) + self._append(moving: srcItems) + srcCount = 0 + } + } + + @_alwaysEmitIntoClient + @_lifetime(self: copy self) + package mutating func _consumeAll( + consumingWith consumer: (inout InputSpan) throws(Failure) -> Void + ) throws(Failure) { + try self.withUnsafeMutableBufferPointer { buffer, count throws(Failure) in + var span = InputSpan( + buffer: buffer._extracting(first: count), + initializedCount: count) + try consumer(&span) + _ = consume span + count = 0 + } + } +} +#endif diff --git a/Sources/ContainersPreview/Types/SpanIterator.swift b/Sources/ContainersPreview/Types/SpanIterator.swift deleted file mode 100644 index 0eb1867e..00000000 --- a/Sources/ContainersPreview/Types/SpanIterator.swift +++ /dev/null @@ -1,61 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// 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 - -/// A borrowing iterator that provides access to the elements of a single -/// span through a `BorrowingIteratorProtocol` interface. -@available(SwiftStdlib 5.0, *) -public struct SpanIterator: IterableIteratorProtocol_, ~Copyable, ~Escapable - where Element_: ~Copyable -{ - @usableFromInline - internal var _span: Span - @usableFromInline - internal var _start: Int - @usableFromInline - internal var _count: Int - - @_lifetime(copy elements) - public init(_ elements: Span) { - _span = elements - _start = 0 - _count = elements.count - } - - @_alwaysEmitIntoClient - @_lifetime(&self) - @_lifetime(self: copy self) - @_transparent - public mutating func nextSpan_(maximumCount: Int) -> Span { - let c = Swift.min(maximumCount, _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/Types/UniqueBox.swift b/Sources/ContainersPreview/Types/UniqueBox.swift index 2e646b83..1ef213ad 100644 --- a/Sources/ContainersPreview/Types/UniqueBox.swift +++ b/Sources/ContainersPreview/Types/UniqueBox.swift @@ -28,19 +28,13 @@ public struct UniqueBox: ~Copyable { public typealias T = Value @usableFromInline - internal let _pointer: UnsafeMutablePointer + internal let _pointer: UnsafeMutablePointer @_alwaysEmitIntoClient @_transparent public init(_ value: consuming Value) { fatalError() } - - @_alwaysEmitIntoClient - @inlinable - deinit { - fatalError() - } } #else diff --git a/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift b/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift index 91916abb..db83bd45 100644 --- a/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift +++ b/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift @@ -359,7 +359,7 @@ extension Deque._UnsafeHandle { @inlinable internal func withUnsafeSegment( startingAt start: Int, - maximumCount: Int?, + maxCount: Int?, _ body: (UnsafeBufferPointer) throws -> R ) rethrows -> (end: Int, result: R) { assert(start <= count) @@ -370,7 +370,7 @@ extension Deque._UnsafeHandle { let segmentStart = self.slot(forOffset: start) let segmentEnd = segmentStart < endSlot ? endSlot : limSlot - let count = Swift.min(maximumCount ?? Int.max, segmentEnd.position - segmentStart.position) + let count = Swift.min(maxCount ?? Int.max, segmentEnd.position - segmentStart.position) let result = try body(UnsafeBufferPointer(start: ptr(at: segmentStart), count: count)) return (start + count, result) } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift index 942cd4ed..98193fac 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift @@ -305,18 +305,19 @@ extension RigidDeque /*where Element: Copyable*/ { /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient public mutating func append(copying items: Span) { - unsafe items.withUnsafeBufferPointer { source in + items.withUnsafeBufferPointer { source in unsafe self.append(copying: source) } } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient internal mutating func _append< S: Iterable_ & ~Copyable & ~Escapable >(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_() if span.isEmpty { break } @@ -334,6 +335,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - newElements: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `newElements`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func append( copying newElements: borrowing S @@ -375,6 +377,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. @available(SwiftStdlib 5.0, *) + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func append< S: Iterable_ & Sequence diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift index d7185855..018f6152 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift @@ -167,7 +167,7 @@ extension RigidDeque where Element: ~Copyable { #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: ~Copyable { - @available(SwiftStdlib 6.4, *) + @available(SwiftStdlib 5.0, *) @_alwaysEmitIntoClient @inline(__always) @_lifetime(&self) @@ -178,7 +178,7 @@ extension RigidDeque where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidDeque 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 @@ -221,23 +221,28 @@ extension RigidDeque where Element: ~Copyable { } } -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidDeque.SubrangeConsumer: Drain where Element: ~Copyable { } -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidDeque.SubrangeConsumer where Element: ~Copyable { + @inlinable + public var count: Int { + _buffer1.count + _buffer2.count + } + @inlinable @_lifetime(&self) @_lifetime(self: copy self) - public mutating func drainNext(maximumCount: Int) -> InputSpan { + public mutating func drainNext(maxCount: Int) -> InputSpan { if _buffer1.isEmpty { if _buffer2.isEmpty { return .init() } swap(&_buffer1, &_buffer2) } - let buffer = _buffer1._trim(first: maximumCount) + let buffer = _buffer1._trim(first: maxCount) return _overrideLifetime( InputSpan(buffer: buffer, initializedCount: buffer.count), mutating: &self) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift index 2e7aa125..3cf99daa 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Container.swift @@ -23,7 +23,7 @@ import ContainersPreview extension RigidDeque where Element: ~Copyable { #if compiler(>=6.4) && UnstableContainersPreview @frozen - public struct BorrowingIterator: ~Escapable, IterableIteratorProtocol_ { + public struct BorrowingIterator: ~Escapable, BorrowingIteratorProtocol_ { public typealias Element_ = Element @usableFromInline @@ -31,7 +31,10 @@ extension RigidDeque where Element: ~Copyable { @usableFromInline internal var _nextSegment: Span - + + @usableFromInline + internal var _position: Int + @_alwaysEmitIntoClient @_lifetime(borrow _deque) internal init(_deque: borrowing RigidDeque) { @@ -43,24 +46,47 @@ extension RigidDeque where Element: ~Copyable { Span( _unsafeElements: segments.second ?? UnsafeBufferPointer._empty), borrowing: _deque) + self._position = 0 } - + @_alwaysEmitIntoClient - @_lifetime(&self) // FIXME: This should be `@_lifetime(copy self)` + @_lifetime(borrow _deque) + internal init( + _deque: borrowing RigidDeque, + from start: Int, + to end: Int + ) { + precondition(start >= 0 && start <= _deque.count, "Index out of bounds") + precondition(end >= 0 && end <= _deque.count, "Index out of bounds") + precondition(start <= end, "The start must not be greater than the end") + let segments = _deque._handle.segments(forOffsets: start ..< end) + self._currentSegment = _overrideLifetime( + Span(_unsafeElements: segments.first), + borrowing: _deque) + self._nextSegment = _overrideLifetime( + Span( + _unsafeElements: segments.second ?? UnsafeBufferPointer._empty), + borrowing: _deque) + self._position = start + } + + @_alwaysEmitIntoClient + @_lifetime(&self) @_lifetime(self: copy self) - public mutating func nextSpan_(maximumCount: Int) -> Span { - let result = _currentSegment._trim(first: maximumCount) + public mutating func nextSpan_(maxCount: Int) -> Span { + let result = _currentSegment._trim(first: maxCount) if _currentSegment.isEmpty { _currentSegment = _nextSegment _nextSegment = Span() } + _position &+= result.count return result } } @_alwaysEmitIntoClient @_lifetime(borrow self) - public borrowing func makeIterableIterator_() -> BorrowingIterator { + public borrowing func makeBorrowingIterator_() -> BorrowingIterator { BorrowingIterator(_deque: self) } #endif @@ -68,7 +94,21 @@ extension RigidDeque where Element: ~Copyable { #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension RigidDeque: Container where Element: ~Copyable {} +extension RigidDeque: Container where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator( + from start: Index, to end: Index + ) -> BorrowingIterator_ { + BorrowingIterator(_deque: self, from: start, to: end) + } + + @_alwaysEmitIntoClient + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { + // FIXME: This should validate that the iterator belongs to this deque. + return iterator._position + } +} @available(SwiftStdlib 5.0, *) extension RigidDeque: BidirectionalContainer where Element: ~Copyable {} @@ -77,10 +117,10 @@ extension RigidDeque: BidirectionalContainer where Element: ~Copyable {} extension RigidDeque: RandomAccessContainer where Element: ~Copyable {} #if compiler(>=6.4) -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidDeque: MutableContainer where Element: ~Copyable {} -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension RigidDeque: RangeReplaceableContainer where Element: ~Copyable {} #endif #endif @@ -118,39 +158,79 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan(after index: inout Int, maximumCount: Int) -> Span { + public func nextSpan(after index: inout Int) -> Span { _checkValidIndex(index) - precondition(maximumCount > 0, "maximumCount must be positive") - let segment = self._handle - .nextSegment(after: index) - ._extracting(first: maximumCount) + let segment = self._handle.nextSegment(after: index) index &+= segment.count return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) } + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func nextSpan( + after index: inout Int, maxCount: Int, limitedBy limit: Int + ) -> Span { + _checkValidIndex(index) + _checkValidIndex(limit) + precondition(maxCount > 0, "maxCount must be positive") + let segment = self._handle.nextSegment( + after: &index, maxCount: maxCount, limitedBy: limit) + return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) + } + @_lifetime(&self) public mutating func nextMutableSpan( - after index: inout Int, maximumCount: Int + after index: inout Int ) -> MutableSpan { _checkValidIndex(index) - precondition(maximumCount > 0, "maximumCount must be positive") - let segment = self._handle - .nextSegment(after: index) - ._extracting(first: maximumCount) + let segment = self._handle.nextSegment(after: index) index &+= segment.count return _overrideLifetime( MutableSpan(_unsafeElements: .init(mutating: segment)), mutating: &self) } + @_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 segment = self._handle.nextSegment( + after: &index, maxCount: maxCount, limitedBy: limit) + return _overrideLifetime( + MutableSpan(_unsafeElements: .init(mutating: segment)), + mutating: &self) + } + + @_alwaysEmitIntoClient + public func spanBoundary(before index: Index) -> (index: Index, distance: Int) { + precondition(index >= 0 && index <= count, "Index out of bounds") + let r = self._handle.spanBoundary(before: index) + return (r.offset, r.distance) + } + + @_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 r = self._handle.spanBoundary(before: index, maxDistance: maxDistance, limitedBy: limit) + return (r.offset, r.distance) + } + @_alwaysEmitIntoClient @_lifetime(borrow self) - public func previousSpan(before index: inout Int, maximumCount: Int) -> Span { + public func previousSpan(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 segment = self._handle .previousSegment(before: index) - ._extracting(last: maximumCount) + ._extracting(last: maxCount) index &-= segment.count return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift index c506ba5c..0e94bceb 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift @@ -19,14 +19,18 @@ import ContainersPreview #endif @available(SwiftStdlib 5.0, *) -extension RigidDeque /*: Equatable */ where Element: Equatable /* & ~Copyable */ { +extension RigidDeque where Element: ~Copyable { public func isTriviallyIdentical(to other: borrowing Self) -> Bool { self._handle.isIdentical(to: other._handle) } } +#if compiler(>=6.4) +@available(SwiftStdlib 6.4, *) +extension RigidDeque: Equatable where Element: Equatable & ~Copyable {} + @available(SwiftStdlib 5.0, *) -extension RigidDeque /*: Equatable */ where Element: Equatable /* & ~Copyable */ { +extension RigidDeque where Element: Equatable & ~Copyable { @inlinable public static func ==( left: borrowing Self, @@ -34,16 +38,35 @@ extension RigidDeque /*: Equatable */ where Element: Equatable /* & ~Copyable */ ) -> Bool { guard left.count == right.count else { return false } guard !left.isTriviallyIdentical(to: right) else { return true } - -#if compiler(>=6.4) && UnstableContainersPreview - return left._elementsEqual(right) -#else + +#if UnstableContainersPreview + if #available(anyAppleOS 27, *) { + return left._elementsEqual(right) + } +#endif for i in 0 ..< left.count { guard left[i] == right[i] else { return false } } return true -#endif } } +#else +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: Equatable { + @inlinable + public static func ==( + left: borrowing Self, + right: borrowing Self + ) -> Bool { + guard left.count == right.count else { return false } + guard !left.isTriviallyIdentical(to: right) else { return true } + + for i in 0 ..< left.count { + guard left[i] == right[i] else { return false } + } + return true + } +} +#endif #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift index 1eea2934..5a0dbc46 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift @@ -17,8 +17,13 @@ import InternalCollectionsUtilities #endif +#if compiler(>=6.4) +@available(SwiftStdlib 6.4, *) +extension RigidDeque: Hashable where Element: Hashable & ~Copyable { +} + @available(SwiftStdlib 5.0, *) -extension RigidDeque /*: Hashable */ where Element: Hashable /* & ~Copyable */ { +extension RigidDeque where Element: Hashable & ~Copyable { @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(self.count) @@ -29,5 +34,19 @@ extension RigidDeque /*: Hashable */ where Element: Hashable /* & ~Copyable */ { } } } +#else +@available(SwiftStdlib 5.0, *) +extension RigidDeque where Element: Hashable { + @inlinable + public func hash(into hasher: inout Hasher) { + hasher.combine(self.count) + let segments = self._handle.segments() + segments.first.span._hashContents(into: &hasher) + if let second = segments.second { + second.span._hashContents(into: &hasher) + } + } +} +#endif #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift index fb1a09f8..f5f8bb00 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift @@ -129,6 +129,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - capacity: The storage capacity of the new deque. /// - contents: A sequence whose contents to copy into the new deque. /// The sequence must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init( @@ -183,6 +184,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - capacity: The storage capacity of the new deque. /// - contents: A sequence whose contents to copy into the new deque. /// The sequence must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init>( @@ -193,7 +195,9 @@ extension RigidDeque /*where Element: Copyable*/ { self.init(capacity: capacity) try self._append(copying: contents) } +#endif +#if compiler(>=6.4) && UnstableContainersPreview /// Creates a new deque with the specified capacity, holding a copy /// of the contents of a given collection. /// @@ -203,6 +207,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// than or equal to the count of the collection. /// - contents: A collection whose contents to copy into the new deque. /// The sequence must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init>( diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift index 046e1766..d3c2f951 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift @@ -350,12 +350,13 @@ extension RigidDeque /* where Element: Copyable */ { public mutating func insert( copying items: Span, at index: Int ) { - unsafe items.withUnsafeBufferPointer { + items.withUnsafeBufferPointer { unsafe self.insert(copying: $0, at: index) } } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _insertContainer< C: Container & ~Copyable & ~Escapable @@ -365,7 +366,7 @@ extension RigidDeque /* where Element: Copyable */ { newCount: Int ) { let expectedCount = self.count + newCount - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() insert(addingCount: newCount, at: index) { target in it._copyContents_(into: &target) } @@ -418,6 +419,7 @@ extension RigidDeque /* where Element: Copyable */ { /// a valid index of the deque. /// /// - Complexity: O(`self.count` + `items.count`). + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< @@ -480,6 +482,7 @@ extension RigidDeque /* where Element: Copyable */ { /// a valid index of the deque. /// /// - Complexity: O(`self.count` + `items.count`) + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift index bd67fa8e..7ed7e432 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift @@ -202,7 +202,7 @@ extension RigidDeque where Element: ~Copyable { /// many items as promised. /// /// - Parameters: - /// - maximumCount: The maximum number of items to prepend to the deque, or + /// - maxCount: The maximum number of items to prepend to the deque, or /// nil to use all available capacity. /// - producer: A producer that generates the items to prepend. /// @@ -282,12 +282,13 @@ extension RigidDeque /*where Element: Copyable*/ { @inlinable @_alwaysEmitIntoClient public mutating func prepend(copying items: Span) { - unsafe items.withUnsafeBufferPointer { source in + items.withUnsafeBufferPointer { source in unsafe self.prepend(copying: source) } } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _prepend< S: Iterable_ & ~Copyable & ~Escapable @@ -307,6 +308,7 @@ extension RigidDeque /*where Element: Copyable*/ { _handle.rotate(toStartAtOffset: oldCount) } + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _prepend< S: Iterable_ & ~Copyable & ~Escapable @@ -315,9 +317,9 @@ extension RigidDeque /*where Element: Copyable*/ { exactCount: Int ) throws(S.Failure_) where S.Element_ == Element { - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() try self.prepend(addingCount: exactCount) { (target) throws(S.Failure_) in - let span = try it.nextSpan_(maximumCount: target.freeCapacity) + let span = try it.nextSpan_(maxCount: target.freeCapacity) target._append(copying: span) } } @@ -336,6 +338,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend( copying items: borrowing S @@ -354,6 +357,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(`items.count`) + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & ~Copyable & ~Escapable>( copying items: borrowing C @@ -441,6 +445,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend>( copying items: borrowing S @@ -458,6 +463,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend>( copying items: borrowing S @@ -475,6 +481,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & Sequence>( copying items: borrowing C @@ -491,6 +498,7 @@ extension RigidDeque /*where Element: Copyable*/ { /// - items: The new elements to copy into the deque. /// /// - Complexity: O(*m*), where *m* is the length of `items`. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & Collection>( copying items: borrowing C diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift index 1ce0d2cd..09ef16db 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift @@ -59,7 +59,13 @@ extension RigidDeque where Element: ~Copyable { precondition(!isEmpty, "Cannot remove first element of an empty RigidDeque") return _handle.uncheckedRemoveFirst() } - + + @_alwaysEmitIntoClient + public mutating func _customRemoveLast() -> Element? { + precondition(!isEmpty, "Cannot remove last element of an empty RigidDeque") + return _handle.uncheckedRemoveLast() + } + /// Removes and returns the last element of the deque. /// /// The deque must not be empty. @@ -91,7 +97,15 @@ extension RigidDeque where Element: ~Copyable { precondition(k <= count, "Cannot remove more elements than there are in the container") _handle.uncheckedRemoveFirst(k) } - + + @_alwaysEmitIntoClient + public mutating func _customRemoveLast(_ n: Int) -> Bool { + precondition(n >= 0, "Cannot remove a negative number of elements") + precondition(n <= count, "Cannot remove more elements than there are in the container") + _handle.uncheckedRemoveLast(n) + return true + } + /// Removes and discards the specified number of elements from the end of the /// deque. /// @@ -147,6 +161,8 @@ extension RigidDeque where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient public mutating func popLast() -> Element? { + // FIXME: Remove this algorithm; it is already provided by + // RangeReplaceableContainer, albeit with stricter availability. guard !isEmpty else { return nil } return _handle.uncheckedRemoveLast() } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift index e9d592a4..1e44dcb2 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift @@ -316,7 +316,7 @@ extension RigidDeque where Element: ~Copyable { /// - newItemCount: The maximum number of items to insert into the deque. /// - producer: A producer that generates the items to append. /// - /// - Complexity: O(`self.count` + `maximumCount`) + /// - Complexity: O(`self.count` + `maxCount`) @_alwaysEmitIntoClient public mutating func replace< E: Error, @@ -450,12 +450,13 @@ extension RigidDeque /* where Element: Copyable */ { removing subrange: Range, copying items: Span ) { - unsafe items.withUnsafeBufferPointer { buffer in + items.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 @@ -466,7 +467,7 @@ extension RigidDeque /* where Element: Copyable */ { ) { let expectedCount = self.count - subrange.count + newCount - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() self.replace(removing: subrange, addingCount: newCount) { target in it._copyContents_(into: &target) } @@ -529,6 +530,7 @@ extension RigidDeque /* where Element: Copyable */ { /// - items: The new elements to copy into the collection. /// /// - Complexity: O(`self.count` + `items.count`) + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< @@ -606,6 +608,7 @@ extension RigidDeque /* where Element: Copyable */ { /// /// - Complexity: O(*n* + *m*), where *n* is count of this deque and /// *m* is the count of `items`. + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< diff --git a/Sources/DequeModule/RigidDeque/RigidDeque.swift b/Sources/DequeModule/RigidDeque/RigidDeque.swift index 16c81eb3..95a48a60 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque.swift @@ -260,9 +260,29 @@ extension RigidDeque where Element: ~Copyable { "Index range out of bounds") } +#if compiler(>=6.4) + @_alwaysEmitIntoClient + public subscript(position: Int) -> Element { + @inline(__always) + @_transparent + @_unsafeSelfDependentResult + borrow { + _checkItemIndex(position) + let slot = _handle.slot(forOffset: position) + return _handle.ptr(at: slot).pointee + } + @inline(__always) + @_transparent + @_unsafeSelfDependentResult + mutate { + _checkItemIndex(position) + let slot = _handle.slot(forOffset: position) + return &_handle.mutablePtr(at: slot).pointee + } + } +#else @_alwaysEmitIntoClient public subscript(position: Int) -> Element { - // FIXME: Replace with borrow/mutate accessors @inline(__always) @_transparent unsafeAddress { @@ -278,6 +298,7 @@ extension RigidDeque where Element: ~Copyable { return _handle.mutablePtr(at: slot) } } +#endif } @available(SwiftStdlib 5.0, *) diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift index e5a58033..d4a36811 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift @@ -298,12 +298,13 @@ extension UniqueDeque /*where Element: Copyable*/ { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient internal mutating func _append( 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_() if span.isEmpty { break } @@ -323,6 +324,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items`, when amortized /// over many similar invocations on the same deque + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func append( copying items: borrowing S @@ -374,6 +376,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items`, when /// amortized over many similar invocations over the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func append>( copying items: S diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift index cc3f0d39..ffe09acb 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Consumption.swift @@ -148,7 +148,7 @@ extension UniqueDeque where Element: ~Copyable { } #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension UniqueDeque where Element: ~Copyable { public typealias SubrangeConsumer = RigidDeque.SubrangeConsumer diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift index 3124ebef..dfa485a2 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Container.swift @@ -26,7 +26,7 @@ extension UniqueDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public borrowing func makeIterableIterator_() -> BorrowingIterator { + public borrowing func makeBorrowingIterator_() -> BorrowingIterator { BorrowingIterator(_deque: self._storage) } #endif @@ -34,7 +34,20 @@ extension UniqueDeque where Element: ~Copyable { #if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 5.0, *) -extension UniqueDeque: Container where Element: ~Copyable {} +extension UniqueDeque: Container where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator( + from start: Index, to end: Index + ) -> BorrowingIterator_ { + _storage.makeBorrowingIterator(from: start, to: end) + } + + @_alwaysEmitIntoClient + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { + _storage.currentIndex(of: iterator) + } +} @available(SwiftStdlib 5.0, *) extension UniqueDeque: BidirectionalContainer where Element: ~Copyable {} @@ -46,10 +59,10 @@ extension UniqueDeque: RandomAccessContainer where Element: ~Copyable {} extension UniqueDeque: MutableContainer where Element: ~Copyable {} #if compiler(>=6.4) -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension UniqueDeque: RangeReplaceableContainer where Element: ~Copyable {} -@available(SwiftStdlib 6.4, *) +@available(SwiftStdlib 5.0, *) extension UniqueDeque: DynamicContainer where Element: ~Copyable {} #endif #endif @@ -87,21 +100,51 @@ extension UniqueDeque where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) - public func nextSpan(after index: inout Int, maximumCount: Int) -> Span { - _storage.nextSpan(after: &index, maximumCount: maximumCount) - } - - @_lifetime(&self) - public mutating func nextMutableSpan( - after index: inout Int, maximumCount: Int - ) -> MutableSpan { - _storage.nextMutableSpan(after: &index, maximumCount: maximumCount) + public func nextSpan(after index: inout Int) -> Span { + _storage.nextSpan(after: &index) } @_alwaysEmitIntoClient @_lifetime(borrow self) - public func previousSpan(before index: inout Int, maximumCount: Int) -> Span { - _storage.previousSpan(before: &index, maximumCount: maximumCount) + public func nextSpan( + after index: inout Int, maxCount: Int, limitedBy limit: Int + ) -> Span { + _storage.nextSpan(after: &index, maxCount: maxCount, limitedBy: limit) + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Int + ) -> MutableSpan { + _storage.nextMutableSpan(after: &index) + } + + @_alwaysEmitIntoClient + @_lifetime(&self) + public mutating func nextMutableSpan( + after index: inout Int, maxCount: Int, limitedBy limit: Int + ) -> MutableSpan { + _storage.nextMutableSpan(after: &index, maxCount: maxCount, limitedBy: limit) + } + + @_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, maxCount: Int) -> Span { + // FIXME: Remove this in favor of the BidirectionalContainer algorithm. + _storage.previousSpan(before: &index, maxCount: maxCount) } } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift index 5de7bd43..a133988a 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Equatable.swift @@ -18,7 +18,19 @@ import InternalCollectionsUtilities #endif @available(SwiftStdlib 5.0, *) -extension UniqueDeque /*: Equatable */ where Element: Equatable /* & ~Copyable */ { +extension UniqueDeque where Element: ~Copyable { + public func isTriviallyIdentical(to other: borrowing Self) -> Bool { + self._storage.isTriviallyIdentical(to: other._storage) + } +} + +#if compiler(>=6.4) +@available(SwiftStdlib 6.4, *) +extension UniqueDeque: Equatable where Element: Equatable & ~Copyable { +} + +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: Equatable & ~Copyable { @inlinable public static func ==( left: borrowing Self, @@ -27,5 +39,17 @@ extension UniqueDeque /*: Equatable */ where Element: Equatable /* & ~Copyable * left._storage == right._storage } } +#else +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: Equatable { + @inlinable + public static func ==( + left: borrowing Self, + right: borrowing Self + ) -> Bool { + left._storage == right._storage + } +} +#endif #endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift index 0a4f8b4a..7df61de7 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Hashable.swift @@ -13,12 +13,26 @@ #if compiler(>=6.2) +#if compiler(>=6.4) +@available(SwiftStdlib 6.4, *) +extension UniqueDeque: Hashable where Element: Hashable & ~Copyable { +} + @available(SwiftStdlib 5.0, *) -extension UniqueDeque /*: Hashable */ where Element: Hashable /* & ~Copyable */ { +extension UniqueDeque where Element: Hashable & ~Copyable { @inlinable public func hash(into hasher: inout Hasher) { self._storage.hash(into: &hasher) } } +#else +@available(SwiftStdlib 5.0, *) +extension UniqueDeque where Element: Hashable { + @inlinable + public func hash(into hasher: inout Hasher) { + self._storage.hash(into: &hasher) + } +} +#endif #endif diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Initializers.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Initializers.swift index 17208b06..b1341a12 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Initializers.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Initializers.swift @@ -142,6 +142,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// - capacity: The storage capacity of the new deque, or nil to let the /// deque grow itself as needed to accommodate all items in `contents`. /// - contents: A sequence whose contents to copy into the new deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init( @@ -180,6 +181,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// deque grow itself as needed to accommodate all items in `contents`. /// - contents: A sequence whose contents to copy into the new deque. /// The sequence must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init>( @@ -198,6 +200,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// - capacity: The storage capacity of the new deque. /// - contents: A sequence whose contents to copy into the new deque. /// The sequence must not contain more than `capacity` elements. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public init>( diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift index f7785077..813ddf21 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift @@ -368,12 +368,13 @@ extension UniqueDeque /* where Element: Copyable */ { public mutating func insert( copying items: Span, at index: Int ) { - unsafe items.withUnsafeBufferPointer { + items.withUnsafeBufferPointer { unsafe self.insert(copying: $0, at: index) } } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _insertContainer< C: Container & ~Copyable & ~Escapable @@ -383,7 +384,7 @@ extension UniqueDeque /* where Element: Copyable */ { newCount: Int ) { let expectedCount = self.count + newCount - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() insert(addingCount: newCount, at: index) { target in it._copyContents_(into: &target) } @@ -439,6 +440,7 @@ extension UniqueDeque /* where Element: Copyable */ { /// /// - Complexity: O(`self.count` + `items.count`) when amortized over many /// similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< @@ -505,6 +507,7 @@ extension UniqueDeque /* where Element: Copyable */ { /// /// - Complexity: O(`self.count` + `items.count`) when amortized over many /// similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @inline(__always) public mutating func insert< diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift index 53fb9bbc..45e5da0a 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift @@ -314,12 +314,13 @@ extension UniqueDeque /*where Element: Copyable*/ { @inlinable @_alwaysEmitIntoClient public mutating func prepend(copying items: Span) { - unsafe items.withUnsafeBufferPointer { source in + items.withUnsafeBufferPointer { source in unsafe self.prepend(copying: source) } } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _prepend( copying items: borrowing S @@ -338,15 +339,16 @@ extension UniqueDeque /*where Element: Copyable*/ { _storage._handle.rotate(toStartAtOffset: oldCount) } + @available(SwiftStdlib 6.4, *) @inlinable internal mutating func _prepend( copying items: borrowing S, exactCount: Int ) throws(S.Failure_) where S.Element_ == Element { - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() try self.prepend(addingCount: exactCount) { (target) throws(S.Failure_) in - let span = try it.nextSpan_(maximumCount: target.freeCapacity) + let span = try it.nextSpan_(maxCount: target.freeCapacity) target._append(copying: span) } } @@ -366,6 +368,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items`, as amortized /// over many similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend( copying items: borrowing S @@ -385,6 +388,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & ~Copyable & ~Escapable>( copying items: borrowing C @@ -477,6 +481,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items`, as amortized /// over many similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend>( copying items: borrowing S @@ -495,6 +500,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items` when amortized /// over many similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend>( copying items: borrowing S @@ -513,6 +519,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items` when amortized /// over many similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & Sequence>( copying items: borrowing C @@ -530,6 +537,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// /// - Complexity: O(*m*), where *m* is the length of `items` when amortized /// over many similar invocations on the same deque. + @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient public mutating func prepend & Collection>( copying items: C diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift index a8b3d543..302b0934 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Removals.swift @@ -145,6 +145,8 @@ extension UniqueDeque where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) public mutating func popLast() -> Element? { + // FIXME: Remove this algorithm; it is already provided by + // RangeReplaceableContainer, albeit with stricter availability. _storage.popLast() } } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift index 3546a7df..ca0579ad 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift @@ -459,12 +459,13 @@ extension UniqueDeque /* where Element: Copyable */ { removing subrange: Range, copying items: Span ) { - unsafe items.withUnsafeBufferPointer { buffer in + items.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 @@ -475,7 +476,7 @@ extension UniqueDeque /* where Element: Copyable */ { ) { let expectedCount = self.count - subrange.count + newCount - var it = items.makeIterableIterator_() + var it = items.makeBorrowingIterator_() self.replace(removing: subrange, addingCount: newCount) { target in it._copyContents_(into: &target) } @@ -539,6 +540,7 @@ extension UniqueDeque /* where Element: Copyable */ { /// - items: The new elements to copy into the collection. /// /// - Complexity: O(`self.count` + `items.count`) + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< @@ -618,6 +620,7 @@ extension UniqueDeque /* where Element: Copyable */ { /// /// - Complexity: O(*n* + *m*), where *n* is count of this deque and /// *m* is the count of `items`. + @available(SwiftStdlib 6.4, *) @inlinable @inline(__always) public mutating func replace< diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift index 9f5d8c19..bbf13983 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift @@ -194,6 +194,22 @@ extension UniqueDeque where Element: ~Copyable { @inline(__always) public var indices: Range { unsafe Range(uncheckedBounds: (0, count)) } +#if compiler(>=6.4) + @_alwaysEmitIntoClient + public subscript(position: Int) -> Element { + @inline(__always) + @_transparent + borrow { + _storage[position] + } + @inline(__always) + @_transparent + @_unsafeSelfDependentResult // FIXME: Why is this necessary? + mutate { + &_storage[position] + } + } +#else @_alwaysEmitIntoClient public subscript(position: Int) -> Element { @inline(__always) @@ -211,6 +227,7 @@ extension UniqueDeque where Element: ~Copyable { return _storage._handle.mutablePtr(at: slot) } } +#endif } @available(SwiftStdlib 5.0, *) diff --git a/Sources/DequeModule/_UnsafeDequeHandle.swift b/Sources/DequeModule/_UnsafeDequeHandle.swift index 3281eb17..23769e1a 100644 --- a/Sources/DequeModule/_UnsafeDequeHandle.swift +++ b/Sources/DequeModule/_UnsafeDequeHandle.swift @@ -331,17 +331,17 @@ extension _UnsafeDequeHandle where Element: ~Copyable { extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient internal func nextSegment( - after startOffset: Int + after offset: Int ) -> UnsafeBufferPointer { - assert(startOffset >= 0 && startOffset <= count) + assert(offset >= 0 && offset <= count) guard _buffer.baseAddress != nil else { return .init(._empty) } - let position = startSlot.position &+ startOffset + let position = startSlot.position &+ offset if position < capacity { return UnsafeBufferPointer( start: ptr(at: Slot(at: position)), - count: Swift.min(count &- startOffset, capacity &- position)) + count: Swift.min(count &- offset, capacity &- position)) } // We're after the wrap return UnsafeBufferPointer( @@ -350,23 +350,66 @@ extension _UnsafeDequeHandle where Element: ~Copyable { } @_alwaysEmitIntoClient - internal func previousSegment( - before startOffset: Int + internal func nextSegment( + after offset: inout Int, + maxCount: Int, + limitedBy limit: Int ) -> UnsafeBufferPointer { - assert(startOffset >= 0 && startOffset <= count) + assert(limit >= 0 && limit <= count) + assert(maxCount > 0) + var segment = self.nextSegment(after: offset) + ._extracting(first: maxCount) + if limit >= offset, segment.count > limit &- offset { + segment = segment._extracting(first: limit &- offset) + } + offset &+= segment.count + return segment + } + + @_alwaysEmitIntoClient + internal func previousSegment( + before offset: Int + ) -> UnsafeBufferPointer { + assert(offset >= 0 && offset <= count) guard _buffer.baseAddress != nil else { return .init(._empty) } - let position = startSlot.position &+ startOffset - if position <= capacity { + let slot = startSlot.position &+ offset + if slot <= capacity { return UnsafeBufferPointer( start: ptr(at: startSlot), - count: startOffset) + count: offset) } // We're after the wrap return UnsafeBufferPointer( start: ptr(at: Slot(at: 0)), - count: position - capacity) + count: slot - capacity) + } + + @_alwaysEmitIntoClient + internal func spanBoundary( + before startOffset: Int + ) -> (offset: Int, distance: Int) { + assert(startOffset >= 0 && startOffset <= count) + let wrapOffset = capacity &- startSlot.position + if startOffset <= wrapOffset { + return (0, startOffset) + } + return (wrapOffset, startOffset &- wrapOffset) + } + + @_alwaysEmitIntoClient + internal func spanBoundary( + before startOffset: Int, maxDistance: Int, limitedBy limitOffset: Int + ) -> (offset: Int, distance: Int) { + assert(startOffset >= 0 && startOffset <= count) + assert(limitOffset >= 0 && limitOffset <= count) + let wrapOffset = capacity &- startSlot.position + let p = startOffset._clampedDown( + towards: startOffset <= wrapOffset ? 0 : wrapOffset, + maxDistance: maxDistance, + limitedBy: limitOffset) + return (p, p &- startOffset) } @_alwaysEmitIntoClient diff --git a/Sources/HashTreeCollections/HashNode/_HashNode.swift b/Sources/HashTreeCollections/HashNode/_HashNode.swift index b807aef8..f7fc74f3 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode.swift @@ -103,27 +103,27 @@ extension _HashNode { extension _HashNode { @inlinable internal var isCollisionNode: Bool { - read { $0.isCollisionNode } + self.read { $0.isCollisionNode } } @inlinable internal var collisionHash: _Hash { - read { $0.collisionHash } + self.read { $0.collisionHash } } @inlinable internal var hasSingletonItem: Bool { - read { $0.hasSingletonItem } + self.read { $0.hasSingletonItem } } @inlinable internal var hasSingletonChild: Bool { - read { $0.hasSingletonChild } + self.read { $0.hasSingletonChild } } @inlinable internal var isAtrophied: Bool { - read { $0.isAtrophiedNode } + self.read { $0.isAtrophiedNode } } } diff --git a/Sources/InternalCollectionsUtilities/CMakeLists.txt b/Sources/InternalCollectionsUtilities/CMakeLists.txt index e52b1c50..5a153f94 100644 --- a/Sources/InternalCollectionsUtilities/CMakeLists.txt +++ b/Sources/InternalCollectionsUtilities/CMakeLists.txt @@ -35,11 +35,16 @@ target_sources(${module_name} PRIVATE "Debugging.swift" "Descriptions.swift" "LifetimeOverride.swift" + "Optional+Extras.swift" + "OutputSpan+Extras.swift" "RandomAccessCollection+Offsets.swift" "Span+Extras.swift" "String+Padding.swift" + "TemporaryAllocation.swift" "UnsafeBufferPointer+Extras.swift" "UnsafeMutableBufferPointer+Extras.swift" "UnsafeMutableRawBufferPointer+Extras.swift" "UnsafeRawBufferPointer+Extras.swift" + "UnsafePointer+Extras.swift" + "UnsafeMutablePointer+Extras.swift" ) diff --git a/Sources/InternalCollectionsUtilities/LifetimeOverride.swift b/Sources/InternalCollectionsUtilities/LifetimeOverride.swift index 738ba591..51f3a6c6 100644 --- a/Sources/InternalCollectionsUtilities/LifetimeOverride.swift +++ b/Sources/InternalCollectionsUtilities/LifetimeOverride.swift @@ -22,8 +22,6 @@ package func _unsafeImmortalize( _ dependent: consuming T ) -> T { - // TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence - // should be expressed by a builtin that is hidden within the function body. dependent } @@ -40,8 +38,6 @@ package func _overrideLifetime< >( _ dependent: consuming T, borrowing source: borrowing U ) -> T { - // TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence - // should be expressed by a builtin that is hidden within the function body. dependent } @@ -58,8 +54,6 @@ package func _overrideLifetime< >( _ dependent: consuming T, copying source: borrowing U ) -> T { - // TODO: Remove @_unsafeNonescapableResult. Instead, the unsafe dependence - // should be expressed by a builtin that is hidden within the function body. dependent } @@ -82,4 +76,19 @@ package func _overrideLifetime< // should be expressed by a builtin that is hidden within the function body. dependent } + +/// Unsafely discard any lifetime dependency on the `dependent` inout +/// argument, replacing it with a lifetime dependency on the caller's borrow +/// scope of the `source` argument. +@unsafe +@_unsafeNonescapableResult +@_alwaysEmitIntoClient +@_transparent +@_lifetime(dependent: borrow source) +public func _overrideLifetime< + T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable +>( + _ dependent: inout T, borrowing source: borrowing U +) {} + #endif diff --git a/Sources/ContainersPreview/Extensions/Optional+Extras.swift b/Sources/InternalCollectionsUtilities/Optional+Extras.swift similarity index 100% rename from Sources/ContainersPreview/Extensions/Optional+Extras.swift rename to Sources/InternalCollectionsUtilities/Optional+Extras.swift diff --git a/Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift similarity index 88% rename from Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift rename to Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift index d0df65f4..db015f28 100644 --- a/Sources/ContainersPreview/Extensions/OutputSpan+Extras.swift +++ b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift @@ -13,10 +13,6 @@ #if compiler(>=6.2) -#if !COLLECTIONS_SINGLE_MODULE -import InternalCollectionsUtilities -#endif - @available(SwiftStdlib 5.0, *) @_alwaysEmitIntoClient package func withTemporaryOutputSpan( @@ -70,23 +66,6 @@ extension OutputSpan where Element: ~Copyable { dstCount &+= source.count } } - -#if UnstableContainersPreview - @_lifetime(source: copy source) - @inlinable - @inline(__always) - @_lifetime(self: copy self) - package mutating func _append(moving source: inout InputSpan) { - // FIXME: This needs to be in the stdlib. - source.withUnsafeMutableBufferPointer { src, srcCount in - let srcItems = src._extracting( - uncheckedFrom: src.count &- srcCount, - to: src.count) - self._append(moving: srcItems) - srcCount = 0 - } - } -#endif @_lifetime(source: copy source) @inlinable @@ -117,7 +96,7 @@ extension OutputSpan /*where Element: Copyable*/ { dstCount &+= source.count } } - + @inlinable @_lifetime(self: copy self) package mutating func _append(copying source: Span) { @@ -159,3 +138,4 @@ extension OutputSpan where Element: ~Copyable { } #endif + diff --git a/Sources/InternalCollectionsUtilities/Span+Extras.swift b/Sources/InternalCollectionsUtilities/Span+Extras.swift index c10b26e8..35139dc2 100644 --- a/Sources/InternalCollectionsUtilities/Span+Extras.swift +++ b/Sources/InternalCollectionsUtilities/Span+Extras.swift @@ -38,7 +38,7 @@ extension Span where Element: ~Copyable { } } -#if compiler(>=6.4) && UnstableContainersPreview +#if compiler(>=6.4) @available(SwiftStdlib 5.0, *) extension Span where Element: Equatable & ~Copyable { @_alwaysEmitIntoClient @@ -78,6 +78,22 @@ extension Span where Element: Equatable /* & ~Copyable */ { } #endif +#if compiler(>=6.4) +@available(SwiftStdlib 5.0, *) +extension Span where Element: Hashable & ~Copyable { + @_alwaysEmitIntoClient + package func _hashContents(into hasher: inout Hasher) { + // Note: no discriminating combine call -- caller is expected to do that + // separately when needed. + var i = 0 + while i < self.count { + hasher.combine(self[unchecked: i]) + i &+= 1 + } + + } +} +#else @available(SwiftStdlib 5.0, *) extension Span where Element: Hashable /* & ~Copyable */ { @_alwaysEmitIntoClient @@ -92,5 +108,37 @@ extension Span where Element: Hashable /* & ~Copyable */ { } } +#endif + +#if compiler(>=6.4) +@available(SwiftStdlib 5.0, *) +extension Span where Element: ~Copyable { + @_alwaysEmitIntoClient + @_lifetime(copy self) + package func clamped(to limits: borrowing Self) -> Self { + if self.isEmpty || limits.isEmpty { return .init() } + let buffer = self.withUnsafeBufferPointer { buffer in + limits.withUnsafeBufferPointer { limits in + let start = buffer.baseAddress! + let end = start + buffer.count + let limitStart = limits.baseAddress! + let limitEnd = limitStart + limits.count + + let clampedStart = ( + limitStart > start ? limitStart + : limitEnd < start ? limitEnd + : start) + let clampedEnd = ( + limitEnd < end ? limitEnd + : limitStart > end ? limitStart + : end) + let count = clampedEnd.distance(to: clampedStart) + return UnsafeBufferPointer(start: clampedStart, count: count) + } + } + return _overrideLifetime(Span(_unsafeElements: buffer), copying: self) + } +} +#endif #endif diff --git a/Sources/ContainersPreview/Extensions/TemporaryAllocation.swift b/Sources/InternalCollectionsUtilities/TemporaryAllocation.swift similarity index 100% rename from Sources/ContainersPreview/Extensions/TemporaryAllocation.swift rename to Sources/InternalCollectionsUtilities/TemporaryAllocation.swift diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutablePointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeMutablePointer+Extras.swift new file mode 100644 index 00000000..cd5fee29 --- /dev/null +++ b/Sources/InternalCollectionsUtilities/UnsafeMutablePointer+Extras.swift @@ -0,0 +1,34 @@ +//===----------------------------------------------------------------------===// +// +// 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) +import Builtin + +extension UnsafeMutablePointer where Pointee: ~Copyable { + // FIXME: Remove this once the standard `pointee` has a borrow accessor. + @_alwaysEmitIntoClient + @_transparent + @unsafe + package var _pointee: Pointee { + @_unsafeSelfDependentResult + borrow { + Builtin.borrowAt(self._rawValue) + } + @_unsafeSelfDependentResult + nonmutating mutate { + unsafe &self.pointee + } + } +} + +#endif diff --git a/Sources/InternalCollectionsUtilities/UnsafePointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafePointer+Extras.swift new file mode 100644 index 00000000..f1fc06dc --- /dev/null +++ b/Sources/InternalCollectionsUtilities/UnsafePointer+Extras.swift @@ -0,0 +1,29 @@ +//===----------------------------------------------------------------------===// +// +// 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) +import Builtin + +extension UnsafePointer where Pointee: ~Copyable { + // FIXME: Remove this once the standard `pointee` has a borrow accessor. + @_alwaysEmitIntoClient + @_transparent + @unsafe + package var _pointee: Pointee { + @_unsafeSelfDependentResult + borrow { + Builtin.borrowAt(self._rawValue) + } + } +} +#endif diff --git a/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift b/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift index 2ed4c7f5..1c46ce86 100644 --- a/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift +++ b/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift @@ -50,7 +50,7 @@ extension _HashTable.UnsafeHandle: CustomStringConvertible { extension _HashTable: CustomStringConvertible { @usableFromInline internal var description: String { - read { $0._description(type: "_HashTable") } + self.read { $0._description(type: "_HashTable") } } } diff --git a/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift b/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift index 6d727b5d..00670bac 100644 --- a/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift +++ b/Sources/RopeModule/BigString/Views/BigString+UTF8View.swift @@ -96,7 +96,7 @@ extension BigString.UTF8View.Iterator: IteratorProtocol { } public mutating func next( - maximumCount: Int, + maximumCount: Int, // FIXME: Should be `maxCount` with body: (UnsafeBufferPointer) -> (consumed: Int, result: R) ) -> R { guard _index < _base.endIndex else { diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index dbfe64a9..617a9893 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -74,7 +74,9 @@ class RigidArrayTests: CollectionTestCase { expectEqual(tracker.instances, 2 * layout.count) expectRigidArrayContents(items, equalTo: expected) #if compiler(>=6.4) && UnstableContainersPreview - checkIterable(items, expectedContents: expected) + if #available(SwiftStdlib 6.4, *) { + checkIterable(items, expectedContents: expected) + } #endif } } @@ -1206,6 +1208,7 @@ class RigidArrayTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_insert_copying_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in withEvery("i", in: 0 ... layout.count) { i in @@ -1438,6 +1441,7 @@ class RigidArrayTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_replace_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 5, 10]) { layout in withEveryRange("range", in: 0 ..< layout.count) { range in @@ -1473,7 +1477,7 @@ class RigidArrayTests: CollectionTestCase { func test_borrowing_map() { let c = 100 let items = RigidArray(capacity: c, copying: 0 ..< c) - let transformed = items.makeIterableIterator_() + let transformed = items.makeBorrowingIterator_() .map { 2 * $0 } .collect(into: UniqueArray.self) expectEqual(transformed.count, c) @@ -1487,7 +1491,7 @@ class RigidArrayTests: CollectionTestCase { func test_borrowing_filter() { let c = 100 let items = RigidArray(capacity: c, copying: 0 ..< c) - let transformed = items.makeIterableIterator_() + let transformed = items.makeBorrowingIterator_() .filter { !$0.isMultiple(of: 6) } .copy() .collect(into: UniqueArray.self) @@ -1508,7 +1512,7 @@ class RigidArrayTests: CollectionTestCase { } var consumer = a.consume(0 ..< 2) - let span = consumer.drainNext(maximumCount: .max) + let span = consumer.drainNext(maxCount: .max) expectEqual(span.count, 2) expectEqual(span[0].payload, 0) diff --git a/Tests/BasicContainersTests/RigidDictionaryTests.swift b/Tests/BasicContainersTests/RigidDictionaryTests.swift index eee55a12..13fc9f4b 100644 --- a/Tests/BasicContainersTests/RigidDictionaryTests.swift +++ b/Tests/BasicContainersTests/RigidDictionaryTests.swift @@ -242,6 +242,46 @@ class RigidDictionaryTests: CollectionTestCase { } } + func test_keys() { + typealias Key = LifetimeTracked + typealias Value = LifetimeTracked + withEvery("capacity", in: [0, 1, 2, 10, 100, 1000]) { capacity in + withLifetimeTracking { tracker in + var d = RigidDictionary(capacity: capacity) + withEvery("i", in: 0 ..< capacity) { i in + let key = tracker.instance(for: i) + let value = tracker.instance(for: "\(i)") + d.insertValue(value, forKey: key) + + expectEqual(d.keys.count, i + 1) + expectEqual(d.keys.capacity, capacity) + +#if UnstableContainersPreview + var actual: Set = [] + _with(d.keys) { keys in // FIXME: Sigh, borrow accessors are limited in 6.4 + var it = keys.makeBorrowingIterator_() + while true { + let next = it.nextSpan_() + guard !next.isEmpty else { break } + for i in next.indices { + expectTrue( + actual.insert(next[i].payload).inserted, + "Duplicate value \(next[i].payload)") + } + } + } + expectEqualElements(actual.sorted(), 0 ... i) +#else + for j in 0 ... i { + expectTrue(d.keys.contains(tracker.instance(for: j))) + } +#endif + } + } + } + } + + @available(*, deprecated) func test_withKeys() { typealias Key = LifetimeTracked typealias Value = LifetimeTracked @@ -256,8 +296,8 @@ class RigidDictionaryTests: CollectionTestCase { d.withKeys { keys in expectEqual(keys.count, i + 1) expectEqual(keys.capacity, capacity) -#if compiler(>=6.4) && UnstableContainersPreview - var it = keys.makeIterableIterator_() +#if UnstableContainersPreview + var it = keys.makeBorrowingIterator_() var actual: Set = [] while true { let next = it.nextSpan_() @@ -307,6 +347,7 @@ class RigidDictionaryTests: CollectionTestCase { } } + #if UnstableContainersPreview @available(SwiftStdlib 6.4, *) func test_iteration_indices() { typealias Key = LifetimeTracked @@ -321,7 +362,7 @@ class RigidDictionaryTests: CollectionTestCase { var seen: Set = [] let indices = d.indices - var it = indices.makeIterableIterator_() + var it = indices.makeBorrowingIterator_() while true { let next = it.nextSpan_() if next.isEmpty { break } @@ -342,6 +383,7 @@ class RigidDictionaryTests: CollectionTestCase { } } } + #endif func test_updateValue_with_remove() { typealias Key = LifetimeTracked diff --git a/Tests/BasicContainersTests/RigidSetTests.swift b/Tests/BasicContainersTests/RigidSetTests.swift index 566cf684..bfc8bc44 100644 --- a/Tests/BasicContainersTests/RigidSetTests.swift +++ b/Tests/BasicContainersTests/RigidSetTests.swift @@ -242,7 +242,7 @@ class RigidSetTests: CollectionTestCase { func test_bucketIterator_consistency() { withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 200]) { capacity in - withEvery("maximumCount", in: [1, 2, 3, Int.max]) { maximumCount in + withEvery("maxCount", in: [1, 2, 3, Int.max]) { maxCount in withLifetimeTracking { tracker in var s = RigidSet>(capacity: capacity) withEvery("i", in: 0 ..< capacity) { i in @@ -250,13 +250,13 @@ class RigidSetTests: CollectionTestCase { var it = s._table.makeBucketIterator() var j = s._table.startBucket - while let next = it.nextOccupiedRegion(maximumCount: maximumCount) { + while let next = it.nextOccupiedRegion(maxCount: maxCount) { expectFalse(next.isEmpty, "Empty chunk; j: \(j), next: \(next)") expectLessThanOrEqual( next.upperBound.offset - next.lowerBound.offset, - maximumCount, + maxCount, "Overlong chunk") - if maximumCount == Int.max, j > s._table.startBucket { + if maxCount == Int.max, j > s._table.startBucket { expectGreaterThan( next.lowerBound, j, "Unnecessarily split run of occupied buckets") @@ -294,18 +294,18 @@ class RigidSetTests: CollectionTestCase { #if UnstableContainersPreview func test_borrowing_iterator() { withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 1000]) { capacity in - withEvery("maximumCount", in: [1, 2, 3, Int.max]) { maximumCount in + withEvery("maxCount", in: [1, 2, 3, Int.max]) { maxCount in withLifetimeTracking { tracker in var s = RigidSet>(capacity: capacity) withEvery("i", in: 0 ..< capacity) { i in s.insert(tracker.instance(for: i)) var expected = Set(0 ... i) - var it = s.makeIterableIterator_() + var it = s.makeBorrowingIterator_() while true { - let next = it.nextSpan_(maximumCount: maximumCount) + let next = it.nextSpan_(maxCount: maxCount) guard !next.isEmpty else { break } - expectLessThanOrEqual(next.count, maximumCount) + expectLessThanOrEqual(next.count, maxCount) for j in next.indices { let v = next[j].payload expectEqual(expected.remove(v), v, "Unexpected item \(v)") @@ -401,14 +401,11 @@ class RigidSetTests: CollectionTestCase { withLifetimeTracking { tracker in var s = RigidSet>(capacity: capacity) - var i = 0 var drain = CustomDrain>( - underestimatedCount: 0, + count: count, chunkSize: chunkSize - ) { - guard i < count else { return nil } - defer { i += 1 } - return tracker.instance(for: i) + ) { i in + tracker.instance(for: i) } s.insert(from: &drain) expectConsistentSet(s) @@ -429,7 +426,7 @@ class RigidSetTests: CollectionTestCase { } } - func test_insert_drain_maximumCount() { + func test_insert_drain_maxCount() { withEvery("capacity", in: [5, 10, 100]) { capacity in withEvery("drainLength", in: [0, 1, 2, 4, 10, capacity]) { drainLength in withEvery("maxCount", in: [0, 1, 2, 3, 5]) { maxCount in @@ -437,21 +434,17 @@ class RigidSetTests: CollectionTestCase { withLifetimeTracking { tracker in var s = RigidSet>(capacity: capacity) - var i = 0 var drain = CustomDrain>( - underestimatedCount: 0, + count: drainLength, chunkSize: chunkSize - ) { - guard i < drainLength else { return nil } - defer { i += 1 } - return tracker.instance(for: i) + ) { i in + tracker.instance(for: i) } - s.insert(maximumCount: maxCount, from: &drain) + s.insert(addingCount: maxCount, from: &drain) expectConsistentSet(s) let expectedCount = Swift.min(maxCount, drainLength) expectEqual(s.count, expectedCount) - expectEqual(i, expectedCount) } } } diff --git a/Tests/BasicContainersTests/UniqueArrayTests.swift b/Tests/BasicContainersTests/UniqueArrayTests.swift index d47a48fd..3571c02b 100644 --- a/Tests/BasicContainersTests/UniqueArrayTests.swift +++ b/Tests/BasicContainersTests/UniqueArrayTests.swift @@ -76,7 +76,9 @@ class UniqueArrayTests: CollectionTestCase { expectEqual(tracker.instances, 2 * layout.count) expectUniqueArrayContents(items, equalTo: expected) #if compiler(>=6.4) && UnstableContainersPreview - checkIterable(items, expectedContents: expected) + if #available(SwiftStdlib 6.4, *) { + checkIterable(items, expectedContents: expected) + } #endif } } @@ -130,7 +132,7 @@ class UniqueArrayTests: CollectionTestCase { func test_init_capacity() { do { - let a = UniqueArray(capacity: 0) + let a = UniqueArray(minimumCapacity: 0) expectEqual(a.capacity, 0) expectEqual(a.count, 0) expectEqual(a.freeCapacity, 0) @@ -138,7 +140,7 @@ class UniqueArrayTests: CollectionTestCase { } do { - let a = UniqueArray(capacity: 10) + let a = UniqueArray(minimumCapacity: 10) expectEqual(a.capacity, 10) expectEqual(a.count, 0) expectEqual(a.freeCapacity, 10) diff --git a/Tests/BasicContainersTests/UniqueDictionaryTests.swift b/Tests/BasicContainersTests/UniqueDictionaryTests.swift index a8d686ca..5f8e188c 100644 --- a/Tests/BasicContainersTests/UniqueDictionaryTests.swift +++ b/Tests/BasicContainersTests/UniqueDictionaryTests.swift @@ -129,8 +129,47 @@ class UniqueDictionaryTests: CollectionTestCase { } expectEqual(actual.sorted(), expected) } - - + + func test_keys() { + typealias Key = LifetimeTracked + typealias Value = LifetimeTracked + withEvery("capacity", in: [0, 1, 2, 10, 100, 1000]) { capacity in + withLifetimeTracking { tracker in + var d = RigidDictionary(capacity: capacity) + withEvery("i", in: 0 ..< capacity) { i in + let key = tracker.instance(for: i) + let value = tracker.instance(for: "\(i)") + d.insertValue(value, forKey: key) + + expectEqual(d.keys.count, i + 1) + expectEqual(d.keys.capacity, capacity) + +#if UnstableContainersPreview + var actual: Set = [] + _with(d.keys) { keys in // FIXME: Sigh, borrow accessors are limited in 6.4 + var it = keys.makeBorrowingIterator_() + while true { + let next = it.nextSpan_() + guard !next.isEmpty else { break } + for i in next.indices { + expectTrue( + actual.insert(next[i].payload).inserted, + "Duplicate value \(next[i].payload)") + } + } + } + expectEqualElements(actual.sorted(), 0 ... i) +#else + for j in 0 ... i { + expectTrue(d.keys.contains(tracker.instance(for: j))) + } +#endif + } + } + } + } + + @available(*, deprecated) func test_withKeys() { typealias Key = LifetimeTracked typealias Value = LifetimeTracked @@ -145,8 +184,8 @@ class UniqueDictionaryTests: CollectionTestCase { d.withKeys { keys in expectEqual(keys.count, i + 1) expectEqual(keys.capacity, capacity) -#if compiler(>=6.4) && UnstableContainersPreview - var it = keys.makeIterableIterator_() +#if UnstableContainersPreview + var it = keys.makeBorrowingIterator_() var actual: Set = [] while true { let next = it.nextSpan_() @@ -210,7 +249,7 @@ class UniqueDictionaryTests: CollectionTestCase { var seen: Set = [] let indices = d.indices - var it = indices.makeIterableIterator_() + var it = indices.makeBorrowingIterator_() while true { let next = it.nextSpan_() if next.isEmpty { break } diff --git a/Tests/ContainersTests/BorrowingSequenceTests.swift b/Tests/ContainersTests/BorrowingSequenceTests.swift index 220ed1cd..f89a48fa 100644 --- a/Tests/ContainersTests/BorrowingSequenceTests.swift +++ b/Tests/ContainersTests/BorrowingSequenceTests.swift @@ -22,7 +22,7 @@ import ContainersPreview #if compiler(>=6.4) && UnstableContainersPreview final class IterableTests: XCTestCase { - @available(SwiftStdlib 6.2, *) + @available(SwiftStdlib 6.4, *) func testBasic() { let array = [1, 2, 3, 4, 5, 6, 7, 8] @@ -63,13 +63,13 @@ final class IterableTests: XCTestCase { } } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) extension Iterable_ where Self: ~Copyable & ~Escapable, Element_: Copyable { func collectViaBorrowing() throws(Failure_) -> [Element_] { - var borrowIterator = makeIterableIterator_() + var borrowIterator = makeBorrowingIterator_() var result: [Element_] = [] while true { - let span = try borrowIterator.nextSpan_(maximumCount: .max) + let span = try borrowIterator.nextSpan_(maxCount: .max) if span.isEmpty { break } for i in span.indices { result.append(span[i]) diff --git a/Tests/ContainersTests/MutableRefTests.swift b/Tests/ContainersTests/MutableRefTests.swift index 435c23c1..281aeff2 100644 --- a/Tests/ContainersTests/MutableRefTests.swift +++ b/Tests/ContainersTests/MutableRefTests.swift @@ -15,6 +15,7 @@ import XCTest #if COLLECTIONS_SINGLE_MODULE import Collections #else +import InternalCollectionsUtilities import _CollectionsTestSupport import ContainersPreview #endif @@ -108,7 +109,7 @@ final class MutableRefTests: CollectionTestCase { func test_init_unsafeAddress_mutating() { var x = 789 - let pointer = unsafe withUnsafeMutablePointer(to: &x) { $0 } + let pointer = withUnsafeMutablePointer(to: &x) { $0 } var ref = unsafe _MutableRef(unsafeAddress: pointer, mutating: &x) expectEqual(ref.value, 789) ref.value = 111 @@ -119,7 +120,7 @@ final class MutableRefTests: CollectionTestCase { func test_init_unsafeImmortalAddress() { var x = 555 - let pointer = unsafe withUnsafeMutablePointer(to: &x) { $0 } + let pointer = withUnsafeMutablePointer(to: &x) { $0 } var ref = unsafe _MutableRef(unsafeImmortalAddress: pointer) expectEqual(ref.value, 555) ref.value = 666 diff --git a/Tests/ContainersTests/RefTests.swift b/Tests/ContainersTests/RefTests.swift index b83376d6..5f4222da 100644 --- a/Tests/ContainersTests/RefTests.swift +++ b/Tests/ContainersTests/RefTests.swift @@ -16,6 +16,7 @@ import XCTest #if COLLECTIONS_SINGLE_MODULE import Collections #else +import InternalCollectionsUtilities import _CollectionsTestSupport import ContainersPreview #endif @@ -71,7 +72,7 @@ final class RefTests: CollectionTestCase { @available(SwiftStdlib 6.4, *) func test_init_unsafeAddress_borrowing() { let x = 123 - unsafe withUnsafePointer(to: x) { pointer in + withUnsafePointer(to: x) { pointer in let ref = Ref(unsafeAddress: pointer, borrowing: x) expectEqual(ref.value, 123) } diff --git a/Tests/DequeTests/RigidDequeCrashTests.swift b/Tests/DequeTests/RigidDequeCrashTests.swift index 238869b1..2151213c 100644 --- a/Tests/DequeTests/RigidDequeCrashTests.swift +++ b/Tests/DequeTests/RigidDequeCrashTests.swift @@ -85,26 +85,26 @@ struct RigidDequeCrashTests { await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = -1 - _ = deque.nextMutableSpan(after: &index, maximumCount: 1) + _ = deque.nextMutableSpan(after: &index, maxCount: 1, limitedBy: deque.endIndex) } await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = 4 // valid range is 0...3 (count == 3) - _ = deque.nextMutableSpan(after: &index, maximumCount: 1) + _ = deque.nextMutableSpan(after: &index, maxCount: 1, limitedBy: deque.endIndex) } } - @Test("nextMutableSpan with non-positive maximumCount traps") + @Test("nextMutableSpan with non-positive maxCount traps") func nextMutableSpanNonPositiveMaximumCount() async { await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = 0 - _ = deque.nextMutableSpan(after: &index, maximumCount: 0) + _ = deque.nextMutableSpan(after: &index, maxCount: 0, limitedBy: deque.endIndex) } await #expect(processExitsWith: .failure) { var deque = RigidDeque(copying: [1, 2, 3]) var index = 0 - _ = deque.nextMutableSpan(after: &index, maximumCount: -1) + _ = deque.nextMutableSpan(after: &index, maxCount: -1, limitedBy: deque.endIndex) } } } diff --git a/Tests/DequeTests/RigidDequeTests.swift b/Tests/DequeTests/RigidDequeTests.swift index 3e533725..24cab3bf 100644 --- a/Tests/DequeTests/RigidDequeTests.swift +++ b/Tests/DequeTests/RigidDequeTests.swift @@ -82,16 +82,19 @@ internal func expectRigidDequeContents< line: UInt = #line ) { #if compiler(>=6.4) && UnstableContainersPreview - expectIterableContents( - left, - equivalentTo: right, - by: areEquivalent, - printer: printer, - message(), - trapping: trapping, - file: file, - line: line) -#else + if #available(SwiftStdlib 6.4, *) { + expectIterableContents( + left, + equivalentTo: right, + by: areEquivalent, + printer: printer, + message(), + trapping: trapping, + file: file, + line: line) + return + } +#endif var c = 0 var j = right.startIndex for i in 0 ..< left.count { @@ -106,7 +109,6 @@ internal func expectRigidDequeContents< right.formIndex(after: &j) c += 1 } -#endif } final class RigidDequeTests: CollectionTestCase { @@ -114,7 +116,7 @@ final class RigidDequeTests: CollectionTestCase { let value: Int init(_ value: Int) { self.value = value } } - + func test_testingSPIs() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -130,10 +132,10 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_basicProperties() { var deque = RigidDeque(capacity: 10) - + // Empty deque expectEqual(deque.isEmpty, true) expectEqual(deque.isFull, false) @@ -143,12 +145,12 @@ final class RigidDequeTests: CollectionTestCase { expectEqual(deque.startIndex, 0) expectEqual(deque.endIndex, 0) expectEqual(deque.indices, 0 ..< 0) - + // Add some elements deque.append(1) deque.append(2) deque.append(3) - + expectEqual(deque.isEmpty, false) expectEqual(deque.isFull, false) expectEqual(deque.count, 3) @@ -157,19 +159,19 @@ final class RigidDequeTests: CollectionTestCase { expectEqual(deque.startIndex, 0) expectEqual(deque.endIndex, 3) expectEqual(deque.indices, 0 ..< 3) - + // Fill to capacity for i in 4...10 { deque.append(i) } - + expectEqual(deque.isEmpty, false) expectEqual(deque.isFull, true) expectEqual(deque.count, 10) expectEqual(deque.freeCapacity, 0) expectEqual(deque.indices, 0 ..< 10) } - + func test_subscriptBorrow() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -180,7 +182,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_subscriptMutate() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("i", in: 0 ..< layout.count) { i in @@ -194,7 +196,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_swapAt() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in withEvery("i", in: 0 ..< layout.count) { i in @@ -209,7 +211,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_reallocate() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery( @@ -219,7 +221,7 @@ final class RigidDequeTests: CollectionTestCase { withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) data.deque.reallocate(capacity: newCapacity) - + expectEqual(data.deque.capacity, newCapacity) expectEqual(data.deque.count, layout.count) expectEqual(tracker.instances, layout.count) @@ -228,7 +230,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_reserveCapacity() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery( @@ -238,7 +240,7 @@ final class RigidDequeTests: CollectionTestCase { withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) data.deque.reserveCapacity(newCapacity) - + expectEqual(data.deque.capacity, Swift.max(layout.capacity, newCapacity)) expectEqual(data.deque.count, layout.count) expectEqual(tracker.instances, layout.count) @@ -247,7 +249,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initWithCapacity() { withEvery("capacity", in: [0, 1, 2, 3, 5, 10]) { capacity in let deque = RigidDeque(capacity: capacity) @@ -259,7 +261,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initEmpty() { let deque = RigidDeque() expectEqual(deque.capacity, 0) @@ -267,7 +269,7 @@ final class RigidDequeTests: CollectionTestCase { expectEqual(deque.freeCapacity, 0) expectNil(deque._handle._buffer.baseAddress) // No allocations } - + func test_initWithClosure_Full() { withEvery("capacity", in: 0 ..< 10) { capacity in withLifetimeTracking { tracker in @@ -281,14 +283,14 @@ final class RigidDequeTests: CollectionTestCase { withEvery("i", in: 0 ..< capacity) { i in expectEqual(deque[i].payload, i) } - + expectEqual(tracker.instances, capacity) _ = consume deque expectEqual(tracker.instances, 0) } } } - + func test_initWithClosure_Partial() { withEvery("capacity", in: 0 ..< 10) { capacity in withEvery("count", in: [0, capacity / 2, max(capacity - 1, 0)] as Set) { count in @@ -303,7 +305,7 @@ final class RigidDequeTests: CollectionTestCase { withEvery("i", in: 0 ..< count) { i in expectEqual(deque[i].payload, i) } - + expectEqual(tracker.instances, count) _ = consume deque expectEqual(tracker.instances, 0) @@ -311,7 +313,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initWithClosure_Failing() { withEvery("capacity", in: 1 ..< 10 as Range) { capacity -> Void in withEvery("count", in: [0, capacity / 2, max(capacity - 1, 0)] as Set) { count -> Void in @@ -335,7 +337,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_init_consumingUniqueDeque() { withLifetimeTracking { tracker in let ud = UniqueDeque(copying: tracker.instances(for: 0 ..< 10)) @@ -343,17 +345,17 @@ final class RigidDequeTests: CollectionTestCase { expectEqual(tracker.instances, 10) let buffer = ud._storage._handle._buffer expectNotNil(buffer.baseAddress) - + let rd = RigidDeque(consuming: ud) expectEqual(rd.count, 10) expectEqual(tracker.instances, 10) expectEqual(rd._handle._buffer.baseAddress, buffer.baseAddress) - + _ = consume rd expectEqual(tracker.instances, 0) } } - + #if compiler(>=6.4) && UnstableContainersPreview func test_initFromProducer() { withEvery("count", in: 0 ..< 10) { count in @@ -367,13 +369,13 @@ final class RigidDequeTests: CollectionTestCase { defer { invocations += 1 } return tracker.structInstance(for: invocations) } - + let deque = RigidDeque(capacity: capacity, from: &producer) expectEqual(invocations, count) expectEqual(deque.count, count) expectEqual(tracker.instances, count) expectEqual(invocations, count) - + for i in 0 ..< count { expectEqual(deque[i].payload, i) } @@ -381,7 +383,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initFromThrowingProducer() { withEvery("count", in: 0 ..< 10) { (count: Int) in withLifetimeTracking { tracker in @@ -394,7 +396,7 @@ final class RigidDequeTests: CollectionTestCase { defer { invocations += 1 } return tracker.structInstance(for: invocations) } - + expectThrows { () throws(TestError) in let _ = try RigidDeque(capacity: count + 10, from: &producer) } @@ -406,7 +408,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + func test_initRepeatingValue() { withEvery("c", in: 0 ..< 10) { c in withLifetimeTracking { tracker in @@ -424,17 +426,18 @@ final class RigidDequeTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_initCopyingBorrowingSequence() { withEvery("c", in: 0 ..< 10) { c in withEvery("capacity", in: [c, c + 1]) { capacity in withLifetimeTracking { tracker in let values = RigidArray(copying: tracker.instances(for: 0 ..< c)) let deque = RigidDeque(capacity: capacity, copying: values) - + expectEqual(deque.count, c) expectEqual(deque.capacity, capacity) expectIterablePayloads(deque, equalTo: 0 ..< c) - + expectEqual(tracker.instances, c) _ = consume values expectEqual(tracker.instances, c) @@ -445,7 +448,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + func test_initCopyingSequence() { withEvery("c", in: 0 ..< 10) { c in withEvery("capacity", in: [c, c + 1]) { capacity in @@ -454,13 +457,13 @@ final class RigidDequeTests: CollectionTestCase { let contents = MinimalSequence( elements: values, underestimatedCount: .value(0)) - + let deque = RigidDeque(capacity: capacity, copying: contents) - + expectEqual(deque.count, c) expectEqual(deque.capacity, capacity) expectRigidDequeContents(deque, equalTo: values) - + expectEqual(tracker.instances, c) _ = consume values _ = consume contents @@ -471,20 +474,20 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initCopyingCollection() { withEvery("c", in: 0 ..< 10) { c in withEvery("capacity", in: [c, c + 1]) { capacity in withLifetimeTracking { tracker in let values = tracker.instances(for: 0 ..< c) let contents = MinimalCollection(values) - + let deque = RigidDeque(capacity: capacity, copying: contents) - + expectEqual(deque.count, c) expectEqual(deque.capacity, capacity) expectRigidDequeContents(deque, equalTo: values) - + expectEqual(tracker.instances, c) _ = consume values _ = consume contents @@ -495,34 +498,34 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_initCopyingRange_classic() { // With a deployment target <6.2, this tests the Collection initializer withEvery("c", in: 0 ..< 10) { c in withEvery("capacity", in: [c, c + 1]) { capacity in let deque = RigidDeque(capacity: capacity, copying: 0 ..< c) - + expectEqual(deque.count, c) expectEqual(deque.capacity, capacity) expectRigidDequeContents(deque, equalTo: 0 ..< c) } } } - + @available(SwiftStdlib 6.2, *) func test_initCopyingRange_modern() { // With a deployment target >=6.2, this tests the BorrowingSequence initializer withEvery("c", in: 0 ..< 10) { c in withEvery("capacity", in: [c, c + 1]) { capacity in let deque = RigidDeque(capacity: capacity, copying: 0 ..< c) - + expectEqual(deque.count, c) expectEqual(deque.capacity, capacity) expectRigidDequeContents(deque, equalTo: 0 ..< c) } } } - + func test_popFirst() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -534,7 +537,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_popLast() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -546,7 +549,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -559,7 +562,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in @@ -572,15 +575,15 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_pushFirst() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) let extra = tracker.instance(for: layout.count) - + let result = data.deque.pushFirst(extra) - + if layout.count == layout.capacity { expectEqual(result, extra) expectRigidDequeContents(data.deque, equalTo: data.contents) @@ -591,15 +594,15 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_pushLast() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) let extra = tracker.instance(for: layout.count) - + let result = data.deque.pushLast(extra) - + if layout.count == layout.capacity { expectEqual(result, extra) expectRigidDequeContents(data.deque, equalTo: data.contents) @@ -610,17 +613,17 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_initializingWith_full() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.insert(contentsOf: extras, at: 0) - + var i = 0 data.deque.prepend(addingCount: prependCount) { target in while !target.isFull { @@ -628,23 +631,23 @@ final class RigidDequeTests: CollectionTestCase { i += 1 } } - + expectRigidDequeContents(data.deque, equalTo: data.contents) } } } } - + func test_append_initializingWith_full() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.append(contentsOf: extras) - + var i = 0 data.deque.append(addingCount: prependCount) { target in while !target.isFull { @@ -652,23 +655,23 @@ final class RigidDequeTests: CollectionTestCase { i += 1 } } - + expectRigidDequeContents(data.deque, equalTo: data.contents) } } } } - + func test_prepend_initializingWith_partial() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.insert(contentsOf: extras, at: 0) - + var i = 0 data.deque.prepend(addingCount: layout.freeCapacity) { target in while !target.isFull, i < prependCount { @@ -682,17 +685,17 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_initializingWith_partial() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.append(contentsOf: extras) - + var i = 0 data.deque.append(addingCount: layout.freeCapacity) { target in while !target.isFull, i < prependCount { @@ -706,18 +709,18 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_initializingWith_failing() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in if layout.freeCapacity == 0 { return } withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.insert(contentsOf: extras, at: 0) - + expectThrows { () throws(TestError) in var i = 0 try data.deque.prepend( @@ -740,19 +743,19 @@ final class RigidDequeTests: CollectionTestCase { } } } - - + + func test_append_initializingWith_failing() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in if layout.freeCapacity == 0 { return } withEvery("prependCount", in: 0 ..< layout.freeCapacity) { prependCount in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + prependCount) - + data.contents.append(contentsOf: extras) - + expectThrows { () throws(TestError) in var i = 0 try data.deque.append( @@ -775,23 +778,23 @@ final class RigidDequeTests: CollectionTestCase { } } } - + #if compiler(>=6.4) && UnstableContainersPreview func test_prepend_Producer_full() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in withEvery("producerSize", in: 0 ..< 6) { producerSize in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< producerSize) - + data.contents.insert(contentsOf: extras.prefix(layout.freeCapacity), at: 0) - + var producer = CustomProducer, Never> { guard !extras.isEmpty else { return nil } return extras.removeFirst() } - + data.deque.prepend(from: &producer) expectEqual(extras.count, max(0, producerSize - layout.freeCapacity)) expectRigidDequeContents(data.deque, equalTo: data.contents) @@ -800,23 +803,23 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + #if compiler(>=6.4) && UnstableContainersPreview func test_append_Producer() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in withEvery("producerSize", in: 0 ..< layout.freeCapacity) { producerSize in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< producerSize) - + data.contents.append(contentsOf: extras) - + var producer = CustomProducer, Never> { guard !extras.isEmpty else { return nil } return extras.removeFirst() } - + data.deque.append(from: &producer) expectEqual(extras.count, max(0, producerSize - layout.freeCapacity)) expectRigidDequeContents(data.deque, equalTo: data.contents) @@ -825,7 +828,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + #if compiler(>=6.4) && UnstableContainersPreview func test_prepend_Producer_failing() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in @@ -833,16 +836,16 @@ final class RigidDequeTests: CollectionTestCase { withEvery("producerSize", in: 0 ..< layout.freeCapacity - 1) { producerSize in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< producerSize) - + data.contents.insert(contentsOf: extras, at: 0) - + var producer = CustomProducer, TestError> { () throws(TestError) in guard !extras.isEmpty else { throw TestError(23) } return extras.removeFirst() } - + expectThrows { () throws(TestError) in try data.deque.prepend(from: &producer) } @@ -856,7 +859,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + #if compiler(>=6.4) && UnstableContainersPreview func test_append_Producer_failing() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in @@ -864,16 +867,16 @@ final class RigidDequeTests: CollectionTestCase { withEvery("producerSize", in: 0 ..< layout.freeCapacity - 1) { producerSize in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< producerSize) - + data.contents.append(contentsOf: extras) - + var producer = CustomProducer, TestError> { () throws(TestError) in guard !extras.isEmpty else { throw TestError(23) } return extras.removeFirst() } - + expectThrows { () throws(TestError) in try data.deque.append(from: &producer) } @@ -887,7 +890,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + func test_prepend_MinimalSequence() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -904,7 +907,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_MinimalSequence() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -921,7 +924,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_MinimalCollection() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -936,7 +939,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_MinimalCollection() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -951,7 +954,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_ContiguousArray_asCollection() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -966,7 +969,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_ContiguousArray_asCollection() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in @@ -981,7 +984,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_ContiguousArray_asSequence() { // This calls the Sequence-based `Deque.prepend` overload, even if // `elements` happens to be of a Collection type. @@ -991,7 +994,7 @@ final class RigidDequeTests: CollectionTestCase { ) { deque.prepend(copying: elements) } - + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in withLifetimeTracking { tracker in @@ -1005,7 +1008,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_ContiguousArray_asSequence() { // This calls the Sequence-based `Deque.append` overload, even if // `elements` happens to be of a Collection type. @@ -1015,7 +1018,7 @@ final class RigidDequeTests: CollectionTestCase { ) { deque.append(copying: elements) } - + withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("c", in: 0 ..< layout.freeCapacity) { c in withLifetimeTracking { tracker in @@ -1029,7 +1032,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_prepend_BridgedArray() { // https://github.com/apple/swift-collections/issues/27 withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in @@ -1052,7 +1055,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_append_BridgedArray() { // https://github.com/apple/swift-collections/issues/27 withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in @@ -1075,7 +1078,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_insert() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("offset", in: 0 ... layout.count) { offset in @@ -1097,11 +1100,11 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< layout.freeCapacity) { c in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + c) - + data.contents.insert(contentsOf: extras, at: i) - + var j = 0 data.deque.insert(addingCount: c, at: i) { target in expectLessThanOrEqual(target.count, extras.count - j) @@ -1118,7 +1121,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_insert_initializingWith_partial() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in guard layout.freeCapacity > 0 else { return } @@ -1126,11 +1129,11 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< layout.freeCapacity - 1) { c in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + c) - + data.contents.insert(contentsOf: extras, at: i) - + var j = 0 data.deque.insert(addingCount: layout.freeCapacity, at: i) { target in while !target.isFull, j < c { @@ -1145,7 +1148,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_insert_initializingWith_failing() { withEveryDeque("layout", ofCapacities: [1, 2, 3, 5, 10]) { layout in if layout.freeCapacity == 0 { return } @@ -1153,11 +1156,11 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< layout.freeCapacity - 1) { c in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + let extras = tracker.instances(for: layout.count ..< layout.count + c) - + data.contents.insert(contentsOf: extras, at: i) - + expectThrows { () throws(TestError) in var j = 0 try data.deque.insert( @@ -1190,18 +1193,18 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< 6) { c in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< c) - + data.contents.insert( contentsOf: extras.prefix(layout.freeCapacity), at: i) - + var producer = CustomProducer, Never> { guard !extras.isEmpty else { return nil } return extras.removeFirst() } - + data.deque.insert( addingCount: layout.freeCapacity, from: &producer, @@ -1214,7 +1217,7 @@ final class RigidDequeTests: CollectionTestCase { } } #endif - + #if compiler(>=6.4) && UnstableContainersPreview func test_insert_fromProducer_failing() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5]) { layout in @@ -1223,16 +1226,16 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< layout.freeCapacity - 1) { c in withLifetimeTracking { tracker in var data = tracker.rigidDeque(with: layout) - + var extras = tracker.instances(for: 0 ..< c) - + data.contents.insert(contentsOf: extras, at: i) - + var producer = CustomProducer, TestError> { () throws(TestError) in guard !extras.isEmpty else { throw TestError(23) } return extras.removeFirst() } - + expectThrows { () throws(TestError) in try data.deque.insert( addingCount: layout.freeCapacity, @@ -1274,6 +1277,7 @@ final class RigidDequeTests: CollectionTestCase { } #if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_insert_RigidArray() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("i", in: 0 ... layout.count) { i in @@ -1300,7 +1304,7 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< subrange.count + layout.freeCapacity) { c in withLifetimeTracking { tracker in var a = tracker.rigidDeque(with: layout).consume() - + var i = 0 a.replace(removing: subrange, addingCount: c) { target in while !target.isFull { @@ -1309,12 +1313,12 @@ final class RigidDequeTests: CollectionTestCase { } } expectEqual(i, c) - + var expected = Array(0 ..< layout.count) expected.replaceSubrange( subrange, with: layout.count ..< layout.count + c) - + expectRigidDequeContents( a, equivalentTo: expected, @@ -1334,7 +1338,7 @@ final class RigidDequeTests: CollectionTestCase { withEvery("n", in: 0 ..< c - 1) { n in withLifetimeTracking { tracker in var a = tracker.rigidDeque(with: layout).consume() - + var i = 0 a.replace(removing: subrange, addingCount: c) { target in while !target.isFull, i < n { @@ -1343,12 +1347,12 @@ final class RigidDequeTests: CollectionTestCase { } } expectEqual(i, n) - + var expected = Array(0 ..< layout.count) expected.replaceSubrange( subrange, with: layout.count ..< layout.count + n) - + expectRigidDequeContents( a, equivalentTo: expected, @@ -1368,7 +1372,7 @@ final class RigidDequeTests: CollectionTestCase { withEvery("c", in: 0 ..< subrange.count + layout.freeCapacity) { c in withLifetimeTracking { tracker in var a = tracker.rigidDeque(with: layout).consume() - + var i = subrange.lowerBound var j = 0 a.replace( @@ -1394,7 +1398,7 @@ final class RigidDequeTests: CollectionTestCase { expected.replaceSubrange( subrange, with: layout.count ..< layout.count + c) - + expectRigidDequeContents( a, equivalentTo: expected, @@ -1416,7 +1420,7 @@ final class RigidDequeTests: CollectionTestCase { withEvery("n", in: 0 ..< c - 1) { n in withLifetimeTracking { tracker in var a = tracker.rigidDeque(with: layout).consume() - + var i = subrange.lowerBound var j = 0 a.replace( @@ -1437,12 +1441,12 @@ final class RigidDequeTests: CollectionTestCase { }) expectEqual(i, subrange.upperBound) expectEqual(j, n) - + var expected = Array(0 ..< layout.count) expected.replaceSubrange( subrange, with: layout.count ..< layout.count + n) - + expectRigidDequeContents( a, equivalentTo: expected, @@ -1469,7 +1473,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeSubrange() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEveryRange("range", in: 0 ..< layout.count) { range in @@ -1482,7 +1486,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeLast() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in guard layout.count > 0 else { return } @@ -1495,7 +1499,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeLast_many() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in guard layout.count > 0 else { return } @@ -1509,7 +1513,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeFirst_one() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in guard layout.count > 0 else { return } @@ -1522,7 +1526,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeFirst_many() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in guard layout.count > 0 else { return } @@ -1536,7 +1540,7 @@ final class RigidDequeTests: CollectionTestCase { } } } - + func test_removeAll_keepingCapacity() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in withEvery("isShared", in: [false, true]) { isShared in @@ -1571,17 +1575,20 @@ final class RigidDequeTests: CollectionTestCase { } } - func test_nextMutableSpan() { + func test_nextMutableSpan_maxCount() { withEveryDeque("layout", ofCapacities: [0, 1, 2, 3, 5, 10]) { layout in - withEvery("maximumCount", in: [1, 2, 3, 5, 100]) { maximumCount in + withEvery("maxCount", in: [1, 2, 3, 5, 100]) { maxCount in var deque = RigidDeque(layout: layout, contents: layout.valueRange) var index = deque.startIndex var totalSeen = 0 while index < deque.endIndex { let oldIndex = index - var span = deque.nextMutableSpan(after: &index, maximumCount: maximumCount) + var span = deque.nextMutableSpan( + after: &index, + maxCount: maxCount, + limitedBy: deque.endIndex) expectGreaterThan(span.count, 0) - expectLessThanOrEqual(span.count, maximumCount) + expectLessThanOrEqual(span.count, maxCount) expectEqual(index, oldIndex + span.count) // Overwrite each element with its logical position in the deque. for i in 0 ..< span.count { diff --git a/Tests/DequeTests/UniqueDequeTests.swift b/Tests/DequeTests/UniqueDequeTests.swift index 08774ba3..3df8d6bb 100644 --- a/Tests/DequeTests/UniqueDequeTests.swift +++ b/Tests/DequeTests/UniqueDequeTests.swift @@ -82,16 +82,19 @@ internal func expectUniqueDequeContents< line: UInt = #line ) { #if compiler(>=6.4) && UnstableContainersPreview - expectIterableContents( - left, - equivalentTo: right, - by: areEquivalent, - printer: printer, - message(), - trapping: trapping, - file: file, - line: line) -#else + if #available(SwiftStdlib 6.4, *) { + expectIterableContents( + left, + equivalentTo: right, + by: areEquivalent, + printer: printer, + message(), + trapping: trapping, + file: file, + line: line) + return + } +#endif var c = 0 var j = right.startIndex for i in 0 ..< left.count { @@ -106,7 +109,6 @@ internal func expectUniqueDequeContents< right.formIndex(after: &j) c += 1 } -#endif } final class UniqueDequeTests: CollectionTestCase { diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift index e21df0db..2a7522a5 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions+Containers.swift @@ -124,7 +124,7 @@ public func expectIterableContents< #if compiler(>=6.4) && UnstableContainersPreview /// Check if `left` contains lifetime tracked instances whose payloads equal /// the elements in `right`. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterablePayloads< Payload: Equatable, E1: Iterable_, E> & ~Copyable & ~Escapable, @@ -138,11 +138,11 @@ public func expectIterablePayloads< file: StaticString = #filePath, line: UInt = #line ) throws(E) where E1.Element_: ~Copyable { - var it1 = left.makeIterableIterator_() + var it1 = left.makeBorrowingIterator_() var it2 = right.makeIterator() var i = 0 while true { - let next1 = try it1.nextSpan_(maximumCount: 1) + let next1 = try it1.nextSpan_(maxCount: 1) let next2 = it2.next() switch (next1.isEmpty, next2) { case (true, nil): @@ -172,7 +172,7 @@ public func expectIterablePayloads< /// Check if `left` contains lifetime tracked instances whose payloads equal /// the elements in `right`. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterablePayloads< Payload: Equatable, E1: Iterable_, E> & ~Copyable & ~Escapable, @@ -186,11 +186,11 @@ public func expectIterablePayloads< file: StaticString = #filePath, line: UInt = #line ) throws(E) { - var it1 = left.makeIterableIterator_() + var it1 = left.makeBorrowingIterator_() var it2 = right.makeIterator() var i = 0 while true { - let next1 = try it1.nextSpan_(maximumCount: 1) + let next1 = try it1.nextSpan_(maxCount: 1) let next2 = it2.next() switch (next1.isEmpty, next2) { case (true, nil): @@ -220,7 +220,7 @@ public func expectIterablePayloads< #endif #if compiler(>=6.4) && UnstableContainersPreview -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterablesWithEquivalentElements< S1: Iterable_ & ~Copyable & ~Escapable, S2: Iterable_ & ~Copyable & ~Escapable @@ -245,7 +245,7 @@ where } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterablesWithEqualElements< Element: Equatable, S1: Iterable_ & ~Copyable & ~Escapable, @@ -270,7 +270,7 @@ where } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterableContents< Element: Equatable, S1: Iterable_ & ~Copyable & ~Escapable, @@ -284,7 +284,7 @@ public func expectIterableContents< file: StaticString = #filePath, line: UInt = #line ) throws(E) { - var it1 = left.makeIterableIterator_() + var it1 = left.makeBorrowingIterator_() var it2 = right.makeIterator() while true { let span = try it1.nextSpan_() @@ -313,7 +313,7 @@ public func expectIterableContents< } /// Check if `left` and `right` contain equal elements in the same order. -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) public func expectIterableContents< S1: Iterable_ & ~Copyable & ~Escapable, C2: Collection, @@ -327,7 +327,7 @@ public func expectIterableContents< file: StaticString = #filePath, line: UInt = #line ) throws(S1.Failure_) where S1.Element_: ~Copyable { - var it1 = left.makeIterableIterator_() + var it1 = left.makeBorrowingIterator_() var it2 = right.makeIterator() var offset = 0 while true { diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift index 83b44c76..7f264011 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift @@ -19,7 +19,7 @@ import Collections import ContainersPreview #endif -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) @inlinable public func checkIterable< S: Iterable_ & ~Copyable & ~Escapable, @@ -37,7 +37,7 @@ public func checkIterable< file: file, line: line) } -@available(SwiftStdlib 5.0, *) +@available(SwiftStdlib 6.4, *) @inlinable public func checkIterable< S: Iterable_ & ~Copyable & ~Escapable, @@ -60,7 +60,7 @@ public func checkIterable< let spanShapes: [Range] = try { () throws(S.Failure_) in var r: [Range] = [] var pos = 0 - var it = iterable.makeIterableIterator_() + var it = iterable.makeBorrowingIterator_() while true { let origPos = pos let span = try it.nextSpan_() @@ -79,7 +79,7 @@ public func checkIterable< // Check that the spans have stable sizes and the expected contents. do { var pos = 0 - var it = iterable.makeIterableIterator_() + var it = iterable.makeBorrowingIterator_() var spanIndex = 0 while true { let span = try it.nextSpan_() @@ -100,9 +100,9 @@ public func checkIterable< // Check that we can iterate one by one. do { var pos = 0 - var it = iterable.makeIterableIterator_() + var it = iterable.makeBorrowingIterator_() while true { - let span = try it.nextSpan_(maximumCount: 1) + let span = try it.nextSpan_(maxCount: 1) if span.isEmpty { break } expectEqual(span.count, 1) for i in 0 ..< span.count { @@ -116,10 +116,10 @@ public func checkIterable< // Check that we can iterate with huge maximum counts do { var pos = 0 - var it = iterable.makeIterableIterator_() + var it = iterable.makeBorrowingIterator_() var spanIndex = 0 while true { - let span = try it.nextSpan_(maximumCount: Int.max) + let span = try it.nextSpan_(maxCount: Int.max) if span.isEmpty { break } expectEqual( span.count, spanShapes[spanIndex].count, diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift b/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift index 8fcbd62b..113db813 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/CustomDrain.swift @@ -23,37 +23,41 @@ import ContainersPreview @available(SwiftStdlib 5.0, *) package struct CustomDrain: ~Copyable { - package let underestimatedCount: Int + package let count: Int package let _chunkSize: Int - package let _generator: () -> Element? + package let _generator: (Int) -> Element package var _buffer: RigidArray package var _remainder: Int + package var _position: Int package init( - underestimatedCount: Int = 0, + count: Int = 0, chunkSize: Int, - generatingWith generator: @escaping () -> Element? + generatingWith generator: @escaping (Int) -> Element ) { - self.underestimatedCount = underestimatedCount + self.count = count self._chunkSize = chunkSize self._generator = generator self._buffer = .init(capacity: _chunkSize) self._remainder = _chunkSize + self._position = 0 } } @available(SwiftStdlib 5.0, *) extension CustomDrain: Drain where Element: ~Copyable { @_lifetime(&self) - package mutating func drainNext(maximumCount: Int) -> InputSpan { + package mutating func drainNext(maxCount: Int) -> InputSpan { assert(_buffer.isEmpty) if _remainder == 0 { _remainder = _chunkSize } - let c = Swift.min(maximumCount, _remainder) + let c = Swift.min(maxCount, _remainder) _remainder -= c for _ in 0 ..< c { - guard let next = _generator() else { break } + guard _position < count else { break } + let next = _generator(_position) + _position += 1 _buffer.append(next) } return _buffer._consumeAll() diff --git a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift index 0c891573..243d7db2 100644 --- a/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift +++ b/Tests/_CollectionsTestSupport/MinimalTypes/StaccatoContainer.swift @@ -58,9 +58,9 @@ package struct _StaccatoParameters { internal func endOffset( fromOffset startOffset: Int, - maximumCount: Int + maxCount: Int ) -> Int { - precondition(maximumCount > 0) + precondition(maxCount >= 0) precondition(startOffset >= 0 && startOffset <= _count) var cycleOffset = startOffset % _modulus var i = 0 @@ -71,36 +71,50 @@ package struct _StaccatoParameters { i += 1 } let c = _spanCounts[i] - return Swift.min(_count, startOffset + Swift.min(c - cycleOffset, maximumCount)) + return Swift.min(_count, startOffset + Swift.min(c - cycleOffset, maxCount)) } } @available(SwiftStdlib 5.0, *) -public struct _StaccatoBorrowingIterator: IterableIteratorProtocol_, ~Escapable { +public struct _StaccatoBorrowingIterator: BorrowingIteratorProtocol_, ~Escapable { public typealias Element_ = Element internal let _contents: Span internal let _params: _StaccatoParameters internal var _offset: Int + internal let _end: Int @_lifetime(copy contents) - internal init(contents: Span, params: _StaccatoParameters) { + internal init( + contents: Span, + params: _StaccatoParameters, + start: _StaccatoIndex = .init(_offset: 0), + end: _StaccatoIndex? = nil + ) { + precondition(start._offset >= 0 && start._offset <= params._count) self._contents = contents self._params = params - self._offset = 0 + self._offset = start._offset + self._end = end?._offset ?? params._count } - @_lifetime(&self) // FIXME: Should be `@_lifetime(copy self)` - public mutating func nextSpan_(maximumCount: Int) -> Span { - let endOffset = _params.endOffset(fromOffset: _offset, maximumCount: maximumCount) + @_lifetime(&self) + public mutating func nextSpan_(maxCount: Int) -> Span { + precondition(maxCount > 0) + let maxCount = Swift.min(maxCount, _end - _offset) + let endOffset = _params.endOffset(fromOffset: _offset, maxCount: maxCount) let startOffset = _offset _offset = endOffset return _contents.extracting(startOffset ..< endOffset) } + + public var currentIndex: _StaccatoIndex { + _StaccatoIndex(_offset: _offset) + } } @available(SwiftStdlib 5.0, *) -public struct _StaccatoIndex: Comparable { +public struct _StaccatoIndex: Comparable, Hashable{ var _offset: Int init(_offset: Int) { self._offset = _offset @@ -113,56 +127,71 @@ public struct _StaccatoIndex: Comparable { public static func <(left: Self, right: Self) -> Bool { left._offset < right._offset } + + public func hash(into hasher: inout Hasher) { + hasher.combine(_offset) + } } @available(SwiftStdlib 5.0, *) extension StaccatoContainer: Iterable_ where Element: ~Copyable { - public typealias IterableIterator_ = _StaccatoBorrowingIterator // FIXME rdar://150240032 + public typealias BorrowingIterator_ = _StaccatoBorrowingIterator // FIXME rdar://150240032 public var underestimatedCount_: Int { count } - public func makeIterableIterator_() -> IterableIterator_ { - IterableIterator_(contents: _contents.span, params: _params) + public func makeBorrowingIterator_() -> BorrowingIterator_ { + BorrowingIterator_(contents: _contents.span, params: _params) } } @available(SwiftStdlib 5.0, *) extension StaccatoContainer: Container where Element: ~Copyable { public typealias Index = _StaccatoIndex - - public var isEmpty: Bool { _contents.isEmpty } - public var count: Int { _contents.count } - - + + public var isEmpty: Bool { count == 0 } + public var count: Int { _params._count } + + @_lifetime(borrow self) + public func makeBorrowingIterator(from start: Index, to end: Index) -> BorrowingIterator_ { + BorrowingIterator_(contents: _contents.span, params: _params, start: start, end: end) + } + + public func currentIndex(of iterator: borrowing BorrowingIterator_) -> Index { + iterator.currentIndex + } + package func _isValid(_ index: Index) -> Bool { index._offset >= 0 && index._offset <= count } + package func _isOccupied(_ index: Index) -> Bool { + index._offset >= 0 && index._offset < count + } public var startIndex: Index { Index(_offset: 0) } public var endIndex: Index { Index(_offset: _contents.count) } - + public func index(after index: Index) -> Index { precondition(index._offset >= 0 && index._offset < count) return Index(_offset: index._offset + 1) } - + public func index(before index: Index) -> Index { precondition(index._offset > 0 && index._offset <= count) return Index(_offset: index._offset - 1) } - + public func index(_ index: Index, offsetBy n: Int) -> Index { precondition(index._offset >= 0 && index._offset <= count) let j = index._offset + n precondition(j >= 0 && j <= count) return Index(_offset: j) } - + public func distance(from start: Index, to end: Index) -> Int { precondition(_isValid(start) && _isValid(end)) return end._offset - start._offset } - + public func formIndex( _ index: inout Index, offsetBy n: inout Int, limitedBy limit: Index ) { @@ -170,15 +199,38 @@ extension StaccatoContainer: Container where Element: ~Copyable { index._offset._advance(by: &n, limitedBy: limit._offset) precondition(_isValid(index)) } - + + public subscript(position: Index) -> Element { + borrow { + precondition(_isOccupied(position)) + return _contents[position._offset] + } + } + @_lifetime(borrow self) public func nextSpan( - after index: inout Index, maximumCount: Int + after index: inout Index ) -> Span { precondition(_isValid(index)) let startOffset = index._offset - let endOffset = _params.endOffset(fromOffset: index._offset, maximumCount: maximumCount) - print("\(startOffset) .-> \(endOffset)") + let endOffset = _params.endOffset(fromOffset: index._offset, maxCount: Int.max) + index._offset = endOffset + return _contents.span.extracting(startOffset ..< endOffset) + } + + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index, maxCount: Int, limitedBy limit: Index + ) -> Span { + precondition(_isValid(index)) + precondition(_isValid(limit)) + var limit = limit + if limit < index { limit = endIndex } + + let startOffset = index._offset + let endOffset = _params.endOffset( + fromOffset: index._offset, + maxCount: Swift.min(limit._offset - index._offset, maxCount)) index._offset = endOffset return _contents.span.extracting(startOffset ..< endOffset) } diff --git a/Tests/_CollectionsTestSupport/Utilities/With.swift b/Tests/_CollectionsTestSupport/Utilities/With.swift new file mode 100644 index 00000000..544f8109 --- /dev/null +++ b/Tests/_CollectionsTestSupport/Utilities/With.swift @@ -0,0 +1,38 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2021 - 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) +// FIXME: Properties with borrow accessors cannot initialize locals. +// +// let keys = d.keys // error: `d.keys` is borrowed and cannot be consumed +// +// We'll probably need language support for `borrow` (rather than +// `let`) bindings. Meanwhile, work around this by defining a silly +// `_with(foo) { foo in ... }` that sort of emulates borrow bindings +// in the most unhelpful way... +// +// _with(d.keys) { keys in +// // OK +// } +@inlinable +package func _with< + T: ~Copyable & ~Escapable, + E: Error, + R: ~Copyable +>( + _ value: borrowing T, + do body: (borrowing T) throws(E) -> R +) throws(E) -> R { + try body(value) +} +#endif diff --git a/Xcode/Collections.xcconfig b/Xcode/Collections.xcconfig index 0a17e877..a5d03d3a 100644 --- a/Xcode/Collections.xcconfig +++ b/Xcode/Collections.xcconfig @@ -12,15 +12,21 @@ PRODUCT_NAME = Collections PRODUCT_BUNDLE_IDENTIFIER = org.swift.Collections -SUPPORTED_PLATFORMS = macosx iphoneos iphonesimulator watchos watchsimulator appletvos appletvsimulator +SUPPORTED_PLATFORMS = $(AVAILABLE_PLATFORMS) ARCHS = $(ARCHS_STANDARD) -MACOSX_DEPLOYMENT_TARGET = 12.0 -IPHONEOS_DEPLOYMENT_TARGET = 15.0 -WATCHOS_DEPLOYMENT_TARGET = 8.0 -TVOS_DEPLOYMENT_TARGET = 15.0 +IPHONEOS_DEPLOYMENT_TARGET = $(RECOMMENDED_IPHONEOS_DEPLOYMENT_TARGET) +MACOSX_DEPLOYMENT_TARGET = $(RECOMMENDED_MACOSX_DEPLOYMENT_TARGET) +TVOS_DEPLOYMENT_TARGET = $(RECOMMENDED_TVOS_DEPLOYMENT_TARGET) +WATCHOS_DEPLOYMENT_TARGET = $(RECOMMENDED_WATCHOS_DEPLOYMENT_TARGET) +XROS_DEPLOYMENT_TARGET = $(RECOMMENDED_XROS_DEPLOYMENT_TARGET) +TARGETED_DEVICE_FAMILY = 1,2,3,4,5,6,7 -MARKETING_VERSION = 1.1 +SUPPORTS_MACCATALYST = YES +SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES +SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = YES + +MARKETING_VERSION = 1.7 CURRENT_PROJECT_VERSION = 1 VERSIONING_SYSTEM = apple-generic diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index de63f9df..6712ff1a 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -7,12 +7,18 @@ objects = { /* Begin PBXBuildFile section */ + 7D0DC7BF2FFD929900BEE8B2 /* Array+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7BE2FFD929500BEE8B2 /* Array+Iterable.swift */; }; + 7D0DC7C12FFD92BB00BEE8B2 /* InlineArray+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7C02FFD92B500BEE8B2 /* InlineArray+Iterable.swift */; }; + 7D0DC7C32FFD987800BEE8B2 /* Range+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7C22FFD987400BEE8B2 /* Range+Iterable.swift */; }; + 7D0DC7C52FFD990E00BEE8B2 /* ClosedRange+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7C42FFD990E00BEE8B2 /* ClosedRange+Iterable.swift */; }; + 7D0DC7C72FFDC40900BEE8B2 /* With.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D0DC7C62FFDC40600BEE8B2 /* With.swift */; }; + 7D12E33D2FF5CC2A003050AB /* OutputSpan+Helpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E33C2FF5CC2A003050AB /* OutputSpan+Helpers.swift */; }; + 7D12E33F2FF5DAE4003050AB /* _HTable+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E33E2FF5DADE003050AB /* _HTable+Deprecated.swift */; }; + 7D12E3412FF5DD0B003050AB /* RigidSet+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D12E3402FF5DD07003050AB /* RigidSet+Deprecated.swift */; }; 7D24E3ED2FAD4C37005A55EB /* RigidArray+Formatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D24E3EC2FAD4C37005A55EB /* RigidArray+Formatter.swift */; }; 7D2A77262F27F1D1005780C7 /* Span+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */; }; 7D2A77392F27F1E4005780C7 /* UniqueBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77332F27F1E4005780C7 /* UniqueBox.swift */; }; 7D2A773A2F27F1E4005780C7 /* Drain.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A772F2F27F1E4005780C7 /* Drain.swift */; }; - 7D2A773C2F27F1E4005780C7 /* TemporaryAllocation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77282F27F1E4005780C7 /* TemporaryAllocation.swift */; }; - 7D2A77422F27F1E4005780C7 /* OutputSpan+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77272F27F1E4005780C7 /* OutputSpan+Extras.swift */; }; 7D2A77432F27F1E4005780C7 /* Shared.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77362F27F1E4005780C7 /* Shared.swift */; }; 7D2A77442F27F1E4005780C7 /* InputSpan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77352F27F1E4005780C7 /* InputSpan.swift */; }; 7D2A77452F27F1E4005780C7 /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A77302F27F1E4005780C7 /* Producer.swift */; }; @@ -59,6 +65,7 @@ 7D2A779C2F27F2BF005780C7 /* Deque+ExpressibleByArrayLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A775C2F27F2BF005780C7 /* Deque+ExpressibleByArrayLiteral.swift */; }; 7D2A77A02F27F367005780C7 /* RefTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A779D2F27F367005780C7 /* RefTests.swift */; }; 7D2F598E2FAC229B00D43FE7 /* MutableRefTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2F598D2FAC229B00D43FE7 /* MutableRefTests.swift */; }; + 7D3F1F7B3007177100AD924D /* Producer+Unfold.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D3F1F7A3007176C00AD924D /* Producer+Unfold.swift */; }; 7D479CB02F450E4600A8CB59 /* RigidSet+BorrowingSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CAF2F450E3F00A8CB59 /* RigidSet+BorrowingSequence.swift */; }; 7D479CB32F45296A00A8CB59 /* UniqueSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CB12F45296000A8CB59 /* UniqueSet.swift */; }; 7D479CB52F452D6900A8CB59 /* UniqueSetTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D479CB42F452D6700A8CB59 /* UniqueSetTests.swift */; }; @@ -132,6 +139,13 @@ 7D57EDE72F6491400029D5E3 /* Producer+Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57EDE62F64913C0029D5E3 /* Producer+Filter.swift */; }; 7D57EDEB2F649CF40029D5E3 /* Container+Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57EDEA2F649CEF0029D5E3 /* Container+Filter.swift */; }; 7D57EDED2F649F0F0029D5E3 /* ContainerIterator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57EDEC2F649F0C0029D5E3 /* ContainerIterator.swift */; }; + 7D59D05C2FE48B89005B5097 /* Optional+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D0592FE48B89005B5097 /* Optional+Extras.swift */; }; + 7D59D05D2FE48B89005B5097 /* OutputSpan+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D05A2FE48B89005B5097 /* OutputSpan+Extras.swift */; }; + 7D59D05E2FE48B89005B5097 /* TemporaryAllocation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D05B2FE48B89005B5097 /* TemporaryAllocation.swift */; }; + 7D59D0662FE49C87005B5097 /* Span+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D0642FE49C87005B5097 /* Span+Container.swift */; }; + 7D59D0672FE49C87005B5097 /* InputSpan+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D0612FE49C87005B5097 /* InputSpan+Container.swift */; }; + 7D59D0682FE49C87005B5097 /* MutableSpan+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D0622FE49C87005B5097 /* MutableSpan+Container.swift */; }; + 7D59D0692FE49C87005B5097 /* OutputSpan+Container.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D59D0632FE49C87005B5097 /* OutputSpan+Container.swift */; }; 7D7246872F3D9DDB00112FD0 /* _HTable+Iteration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7246802F3D9DDB00112FD0 /* _HTable+Iteration.swift */; }; 7D7246882F3D9DDB00112FD0 /* RigidDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7246832F3D9DDB00112FD0 /* RigidDictionary.swift */; }; 7D7246892F3D9DDB00112FD0 /* _HTable+Find.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D72467E2F3D9DDB00112FD0 /* _HTable+Find.swift */; }; @@ -145,6 +159,14 @@ 7D72F5982F75E5E6004AB792 /* BorrowingSequenceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D72F5972F75E5E6004AB792 /* BorrowingSequenceTests.swift */; }; 7D7646062FAAA2B9008639E5 /* UniqueBoxTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7646052FAAA2B9008639E5 /* UniqueBoxTests.swift */; }; 7D7646082FAAABE3008639E5 /* UniqueDeque+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7646072FAAABDF008639E5 /* UniqueDeque+Deprecated.swift */; }; + 7D77E6122FCF810E003FA63B /* CountedProducer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6112FCF810E003FA63B /* CountedProducer.swift */; }; + 7D77E6252FD0F880003FA63B /* UnsafePointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6242FD0F87B003FA63B /* UnsafePointer+Extras.swift */; }; + 7D77E6272FD0F94B003FA63B /* UnsafeMutablePointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D77E6262FD0F940003FA63B /* UnsafeMutablePointer+Extras.swift */; }; + 7D945E6B2FF5E0D1001041A6 /* UniqueSet+Deprecations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D945E6A2FF5E0CB001041A6 /* UniqueSet+Deprecations.swift */; }; + 7D945E6D2FF71D76001041A6 /* Span+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D945E6C2FF71D76001041A6 /* Span+Iterable.swift */; }; + 7D945E6F2FF71DFF001041A6 /* MutableSpan+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D945E6E2FF71DF8001041A6 /* MutableSpan+Iterable.swift */; }; + 7D945E712FF71E58001041A6 /* OutputSpan+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D945E702FF71E53001041A6 /* OutputSpan+Iterable.swift */; }; + 7D945E732FF71E8C001041A6 /* InputSpan+Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D945E722FF71E86001041A6 /* InputSpan+Iterable.swift */; }; 7D9748D42E9748930098631A /* BigString+Chunk+UTF16.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D32E9748930098631A /* BigString+Chunk+UTF16.swift */; }; 7D9748D52E9748930098631A /* BigString+Chunk+UnicodeScalar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */; }; 7D9748D62E9748930098631A /* BigString+Chunk+Character.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */; }; @@ -177,7 +199,6 @@ 7DA23F5A2F32C68300E4C03A /* RigidArray+Hashable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F592F32C67D00E4C03A /* RigidArray+Hashable.swift */; }; 7DA23F5C2F32C69100E4C03A /* RigidArray+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA23F5B2F32C68B00E4C03A /* RigidArray+Descriptions.swift */; }; 7DA296012FB79DC5005042B0 /* CollectionsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DA295FF2FB79DC5005042B0 /* CollectionsTests.swift */; }; - 7DACFA122F75FBF100291F2E /* SpanIterator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DACFA112F75FBF100291F2E /* SpanIterator.swift */; }; 7DAD899E2E8B09C300DD5786 /* UInt+first and last set bit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD899C2E8B09C300DD5786 /* UInt+first and last set bit.swift */; }; 7DAD899F2E8B09C300DD5786 /* UInt+reversed.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD899D2E8B09C300DD5786 /* UInt+reversed.swift */; }; 7DAD89A02E8B09C300DD5786 /* FixedWidthInteger+roundUpToPowerOfTwo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD899A2E8B09C300DD5786 /* FixedWidthInteger+roundUpToPowerOfTwo.swift */; }; @@ -195,20 +216,18 @@ 7DAD89B72E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD89AF2E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift */; }; 7DB257A12F58B1AA007B539F /* RigidDictionary+Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB257A02F58B1A3007B539F /* RigidDictionary+Debugging.swift */; }; 7DB257A32F58B1D3007B539F /* UniqueDictionary+Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DB257A22F58B1CC007B539F /* UniqueDictionary+Debugging.swift */; }; - 7DC037B72FE3492D00CF0CB8 /* IterableIteratorProtocol+Copy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B12FE3492D00CF0CB8 /* IterableIteratorProtocol+Copy.swift */; }; + 7DC037B72FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift */; }; 7DC037B82FE3492D00CF0CB8 /* Iterable+Utilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037AF2FE3492D00CF0CB8 /* Iterable+Utilities.swift */; }; - 7DC037B92FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037AE2FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift */; }; - 7DC037BA2FE3492D00CF0CB8 /* IterableIteratorProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B02FE3492D00CF0CB8 /* IterableIteratorProtocol.swift */; }; + 7DC037BA2FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B02FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift */; }; 7DC037BB2FE3492D00CF0CB8 /* Iterable+Algorithms.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037AD2FE3492D00CF0CB8 /* Iterable+Algorithms.swift */; }; - 7DC037BC2FE3492D00CF0CB8 /* IterableIteratorProtocol+Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B32FE3492D00CF0CB8 /* IterableIteratorProtocol+Filter.swift */; }; + 7DC037BC2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B32FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift */; }; 7DC037BD2FE3492D00CF0CB8 /* Iterable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037AC2FE3492D00CF0CB8 /* Iterable.swift */; }; - 7DC037BE2FE3492D00CF0CB8 /* IterableIteratorProtocol+ElementsEqual.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B22FE3492D00CF0CB8 /* IterableIteratorProtocol+ElementsEqual.swift */; }; - 7DC037BF2FE3492D00CF0CB8 /* IterableIteratorProtocol+Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B52FE3492D00CF0CB8 /* IterableIteratorProtocol+Reduce.swift */; }; - 7DC037C02FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B62FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift */; }; - 7DC037C12FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B42FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift */; }; + 7DC037BE2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+ElementsEqual.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B22FE3492D00CF0CB8 /* BorrowingIteratorProtocol+ElementsEqual.swift */; }; + 7DC037BF2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B52FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Reduce.swift */; }; + 7DC037C02FE3492D00CF0CB8 /* BorrowingIteratorProtocol+SpanwiseZip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B62FE3492D00CF0CB8 /* BorrowingIteratorProtocol+SpanwiseZip.swift */; }; + 7DC037C12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037B42FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Map.swift */; }; 7DC037C32FE34B2800CF0CB8 /* Heap+Testing.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C22FE34B2800CF0CB8 /* Heap+Testing.swift */; }; - 7DC037C52FE3717A00CF0CB8 /* IterableIteratorProtocol+MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C42FE3717200CF0CB8 /* IterableIteratorProtocol+MapError.swift */; }; - 7DC037C72FE378B300CF0CB8 /* Optional+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C62FE378B300CF0CB8 /* Optional+Extras.swift */; }; + 7DC037C52FE3717A00CF0CB8 /* BorrowingIteratorProtocol+MapError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C42FE3717200CF0CB8 /* BorrowingIteratorProtocol+MapError.swift */; }; 7DC037C92FE3792300CF0CB8 /* MutableRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC037C82FE3792300CF0CB8 /* MutableRef.swift */; }; 7DC85F8D2F3FDC91004A4E3D /* String+Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC85F8C2F3FDC82004A4E3D /* String+Padding.swift */; }; 7DC85F8F2F43D065004A4E3D /* RigidDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC85F8E2F43D05F004A4E3D /* RigidDictionaryTests.swift */; }; @@ -608,6 +627,14 @@ /* End PBXContainerItemProxy section */ /* Begin PBXFileReference section */ + 7D0DC7BE2FFD929500BEE8B2 /* Array+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Array+Iterable.swift"; sourceTree = ""; }; + 7D0DC7C02FFD92B500BEE8B2 /* InlineArray+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "InlineArray+Iterable.swift"; sourceTree = ""; }; + 7D0DC7C22FFD987400BEE8B2 /* Range+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Range+Iterable.swift"; sourceTree = ""; }; + 7D0DC7C42FFD990E00BEE8B2 /* ClosedRange+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "ClosedRange+Iterable.swift"; sourceTree = ""; }; + 7D0DC7C62FFDC40600BEE8B2 /* With.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = With.swift; sourceTree = ""; }; + 7D12E33C2FF5CC2A003050AB /* OutputSpan+Helpers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Helpers.swift"; sourceTree = ""; }; + 7D12E33E2FF5DADE003050AB /* _HTable+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Deprecated.swift"; sourceTree = ""; }; + 7D12E3402FF5DD07003050AB /* RigidSet+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidSet+Deprecated.swift"; sourceTree = ""; }; 7D24E3EC2FAD4C37005A55EB /* RigidArray+Formatter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Formatter.swift"; sourceTree = ""; }; 7D24E9862FAD53E1005A55EB /* RigidArray_Fixture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidArray_Fixture.swift; sourceTree = ""; }; 7D24E9882FAD53E1005A55EB /* Package.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Package.swift; sourceTree = ""; }; @@ -617,8 +644,6 @@ 7D24E98E2FAD53E1005A55EB /* HEADER.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HEADER.swift; sourceTree = ""; }; 7D24E98F2FAD53E1005A55EB /* test_formatters.py */ = {isa = PBXFileReference; lastKnownFileType = text.script.python; path = test_formatters.py; sourceTree = ""; }; 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Span+Extras.swift"; sourceTree = ""; }; - 7D2A77272F27F1E4005780C7 /* OutputSpan+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Extras.swift"; sourceTree = ""; }; - 7D2A77282F27F1E4005780C7 /* TemporaryAllocation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemporaryAllocation.swift; sourceTree = ""; }; 7D2A772F2F27F1E4005780C7 /* Drain.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Drain.swift; sourceTree = ""; }; 7D2A77302F27F1E4005780C7 /* Producer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Producer.swift; sourceTree = ""; }; 7D2A77332F27F1E4005780C7 /* UniqueBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueBox.swift; sourceTree = ""; }; @@ -667,6 +692,7 @@ 7D2A77762F27F2BF005780C7 /* UniqueDeque+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Replacements.swift"; sourceTree = ""; }; 7D2A779D2F27F367005780C7 /* RefTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RefTests.swift; sourceTree = ""; }; 7D2F598D2FAC229B00D43FE7 /* MutableRefTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableRefTests.swift; sourceTree = ""; }; + 7D3F1F7A3007176C00AD924D /* Producer+Unfold.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Producer+Unfold.swift"; sourceTree = ""; }; 7D479CAF2F450E3F00A8CB59 /* RigidSet+BorrowingSequence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidSet+BorrowingSequence.swift"; sourceTree = ""; }; 7D479CB12F45296000A8CB59 /* UniqueSet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueSet.swift; sourceTree = ""; }; 7D479CB42F452D6700A8CB59 /* UniqueSetTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueSetTests.swift; sourceTree = ""; }; @@ -704,7 +730,6 @@ 7D479CFA2F4D080500A8CB59 /* UniqueDictionary+Keys.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDictionary+Keys.swift"; sourceTree = ""; }; 7D479CFB2F4D080500A8CB59 /* UniqueDictionary+Removals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDictionary+Removals.swift"; sourceTree = ""; }; 7D479CFE2F4E487700A8CB59 /* RigidSet+Equatable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidSet+Equatable.swift"; sourceTree = ""; }; - 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClassBox.swift; sourceTree = ""; }; 7D48BCDD2E51558700D7F6F7 /* TestPrintable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestPrintable.swift; sourceTree = ""; }; 7D48BCDE2E51558700D7F6F7 /* LifetimeTrackedStruct.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LifetimeTrackedStruct.swift; sourceTree = ""; }; @@ -742,6 +767,14 @@ 7D57EDE62F64913C0029D5E3 /* Producer+Filter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Producer+Filter.swift"; sourceTree = ""; }; 7D57EDEA2F649CEF0029D5E3 /* Container+Filter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Container+Filter.swift"; sourceTree = ""; }; 7D57EDEC2F649F0C0029D5E3 /* ContainerIterator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContainerIterator.swift; sourceTree = ""; }; + 7D59D0592FE48B89005B5097 /* Optional+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Optional+Extras.swift"; sourceTree = ""; }; + 7D59D05A2FE48B89005B5097 /* OutputSpan+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Extras.swift"; sourceTree = ""; }; + 7D59D05B2FE48B89005B5097 /* TemporaryAllocation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TemporaryAllocation.swift; sourceTree = ""; }; + 7D59D0602FE49BDA005B5097 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; + 7D59D0612FE49C87005B5097 /* InputSpan+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "InputSpan+Container.swift"; sourceTree = ""; }; + 7D59D0622FE49C87005B5097 /* MutableSpan+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MutableSpan+Container.swift"; sourceTree = ""; }; + 7D59D0632FE49C87005B5097 /* OutputSpan+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Container.swift"; sourceTree = ""; }; + 7D59D0642FE49C87005B5097 /* Span+Container.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Span+Container.swift"; sourceTree = ""; }; 7D5A64D229CCE8CC00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 7D5A64D329CCEE9A00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 7D5A64D829CCF0FE00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; @@ -760,6 +793,14 @@ 7D72F5972F75E5E6004AB792 /* BorrowingSequenceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowingSequenceTests.swift; sourceTree = ""; }; 7D7646052FAAA2B9008639E5 /* UniqueBoxTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UniqueBoxTests.swift; sourceTree = ""; }; 7D7646072FAAABDF008639E5 /* UniqueDeque+Deprecated.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Deprecated.swift"; sourceTree = ""; }; + 7D77E6112FCF810E003FA63B /* CountedProducer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CountedProducer.swift; sourceTree = ""; }; + 7D77E6242FD0F87B003FA63B /* UnsafePointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafePointer+Extras.swift"; sourceTree = ""; }; + 7D77E6262FD0F940003FA63B /* UnsafeMutablePointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafeMutablePointer+Extras.swift"; sourceTree = ""; }; + 7D945E6A2FF5E0CB001041A6 /* UniqueSet+Deprecations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueSet+Deprecations.swift"; sourceTree = ""; }; + 7D945E6C2FF71D76001041A6 /* Span+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Span+Iterable.swift"; sourceTree = ""; }; + 7D945E6E2FF71DF8001041A6 /* MutableSpan+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "MutableSpan+Iterable.swift"; sourceTree = ""; }; + 7D945E702FF71E53001041A6 /* OutputSpan+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OutputSpan+Iterable.swift"; sourceTree = ""; }; + 7D945E722FF71E86001041A6 /* InputSpan+Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "InputSpan+Iterable.swift"; sourceTree = ""; }; 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Character.swift"; sourceTree = ""; }; 7D9748D02E9748930098631A /* BigString+Chunk+Index.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Index.swift"; sourceTree = ""; }; 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+UnicodeScalar.swift"; sourceTree = ""; }; @@ -793,7 +834,6 @@ 7DA23F592F32C67D00E4C03A /* RigidArray+Hashable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Hashable.swift"; sourceTree = ""; }; 7DA23F5B2F32C68B00E4C03A /* RigidArray+Descriptions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "RigidArray+Descriptions.swift"; sourceTree = ""; }; 7DA295FF2FB79DC5005042B0 /* CollectionsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CollectionsTests.swift; sourceTree = ""; }; - 7DACFA112F75FBF100291F2E /* SpanIterator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpanIterator.swift; sourceTree = ""; }; 7DAD899A2E8B09C300DD5786 /* FixedWidthInteger+roundUpToPowerOfTwo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "FixedWidthInteger+roundUpToPowerOfTwo.swift"; sourceTree = ""; }; 7DAD899B2E8B09C300DD5786 /* Integer rank.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Integer rank.swift"; sourceTree = ""; }; 7DAD899C2E8B09C300DD5786 /* UInt+first and last set bit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UInt+first and last set bit.swift"; sourceTree = ""; }; @@ -813,18 +853,16 @@ 7DB257A22F58B1CC007B539F /* UniqueDictionary+Debugging.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDictionary+Debugging.swift"; sourceTree = ""; }; 7DC037AC2FE3492D00CF0CB8 /* Iterable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Iterable.swift; sourceTree = ""; }; 7DC037AD2FE3492D00CF0CB8 /* Iterable+Algorithms.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Iterable+Algorithms.swift"; sourceTree = ""; }; - 7DC037AE2FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Iterable+Standard Conformances.swift"; sourceTree = ""; }; 7DC037AF2FE3492D00CF0CB8 /* Iterable+Utilities.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Iterable+Utilities.swift"; sourceTree = ""; }; - 7DC037B02FE3492D00CF0CB8 /* IterableIteratorProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IterableIteratorProtocol.swift; sourceTree = ""; }; - 7DC037B12FE3492D00CF0CB8 /* IterableIteratorProtocol+Copy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+Copy.swift"; sourceTree = ""; }; - 7DC037B22FE3492D00CF0CB8 /* IterableIteratorProtocol+ElementsEqual.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+ElementsEqual.swift"; sourceTree = ""; }; - 7DC037B32FE3492D00CF0CB8 /* IterableIteratorProtocol+Filter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+Filter.swift"; sourceTree = ""; }; - 7DC037B42FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+Map.swift"; sourceTree = ""; }; - 7DC037B52FE3492D00CF0CB8 /* IterableIteratorProtocol+Reduce.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+Reduce.swift"; sourceTree = ""; }; - 7DC037B62FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+SpanwiseZip.swift"; sourceTree = ""; }; + 7DC037B02FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowingIteratorProtocol.swift; sourceTree = ""; }; + 7DC037B12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+Copy.swift"; sourceTree = ""; }; + 7DC037B22FE3492D00CF0CB8 /* BorrowingIteratorProtocol+ElementsEqual.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+ElementsEqual.swift"; sourceTree = ""; }; + 7DC037B32FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+Filter.swift"; sourceTree = ""; }; + 7DC037B42FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Map.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+Map.swift"; sourceTree = ""; }; + 7DC037B52FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Reduce.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+Reduce.swift"; sourceTree = ""; }; + 7DC037B62FE3492D00CF0CB8 /* BorrowingIteratorProtocol+SpanwiseZip.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+SpanwiseZip.swift"; sourceTree = ""; }; 7DC037C22FE34B2800CF0CB8 /* Heap+Testing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Heap+Testing.swift"; sourceTree = ""; }; - 7DC037C42FE3717200CF0CB8 /* IterableIteratorProtocol+MapError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "IterableIteratorProtocol+MapError.swift"; sourceTree = ""; }; - 7DC037C62FE378B300CF0CB8 /* Optional+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Optional+Extras.swift"; sourceTree = ""; }; + 7DC037C42FE3717200CF0CB8 /* BorrowingIteratorProtocol+MapError.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BorrowingIteratorProtocol+MapError.swift"; sourceTree = ""; }; 7DC037C82FE3792300CF0CB8 /* MutableRef.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MutableRef.swift; sourceTree = ""; }; 7DC85F8C2F3FDC82004A4E3D /* String+Padding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+Padding.swift"; sourceTree = ""; }; 7DC85F8E2F43D05F004A4E3D /* RigidDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidDictionaryTests.swift; sourceTree = ""; }; @@ -976,7 +1014,6 @@ 7DE91F1F29CA70F3004483EB /* _CharacterRecognizer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _CharacterRecognizer.swift; sourceTree = ""; }; 7DE91F2029CA70F3004483EB /* String.Index+ABI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "String.Index+ABI.swift"; sourceTree = ""; }; 7DE91F2129CA70F3004483EB /* Optional Utilities.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Optional Utilities.swift"; sourceTree = ""; }; - 7DE91F2E29CA70F3004483EB /* CMakeLists.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; 7DE91F3029CA70F3004483EB /* _SortedCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _SortedCollection.swift; sourceTree = ""; }; 7DE91F3829CA70F3004483EB /* _UniqueCollection.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = _UniqueCollection.swift; sourceTree = ""; }; 7DE91F3B29CA70F3004483EB /* BitSet+SetAlgebra symmetricDifference.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitSet+SetAlgebra symmetricDifference.swift"; sourceTree = ""; }; @@ -1236,6 +1273,7 @@ 7DFA40832FD3A98D00CD20C1 /* OrderedSet+Move.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OrderedSet+Move.swift"; sourceTree = ""; }; 7DFA40852FD3A99D00CD20C1 /* OrderedDictionary+Move.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "OrderedDictionary+Move.swift"; sourceTree = ""; }; 7DFA40892FD3ACE700CD20C1 /* UnsafeBufferTrimTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UnsafeBufferTrimTests.swift; sourceTree = ""; }; + 7DFC9DF62FEB5D7D00BE8808 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; A93AC20F2E7C841700A824DF /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; A93AC21A2E7C845300A824DF /* ArrayLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ArrayLayout.swift; sourceTree = ""; }; A93AC21B2E7C845300A824DF /* RigidArrayTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidArrayTests.swift; sourceTree = ""; }; @@ -1304,32 +1342,22 @@ path = Debugger; sourceTree = ""; }; - 7D2A77292F27F1E4005780C7 /* Extensions */ = { - isa = PBXGroup; - children = ( - 7DC037C62FE378B300CF0CB8 /* Optional+Extras.swift */, - 7D2A77272F27F1E4005780C7 /* OutputSpan+Extras.swift */, - 7D2A77282F27F1E4005780C7 /* TemporaryAllocation.swift */, - ); - path = Extensions; - sourceTree = ""; - }; 7D2A77312F27F1E4005780C7 /* Protocols */ = { isa = PBXGroup; children = ( 7DC037AC2FE3492D00CF0CB8 /* Iterable.swift */, 7DC037AD2FE3492D00CF0CB8 /* Iterable+Algorithms.swift */, - 7DC037AE2FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift */, 7DC037AF2FE3492D00CF0CB8 /* Iterable+Utilities.swift */, - 7DC037B02FE3492D00CF0CB8 /* IterableIteratorProtocol.swift */, - 7DC037B12FE3492D00CF0CB8 /* IterableIteratorProtocol+Copy.swift */, - 7DC037B22FE3492D00CF0CB8 /* IterableIteratorProtocol+ElementsEqual.swift */, - 7DC037B32FE3492D00CF0CB8 /* IterableIteratorProtocol+Filter.swift */, - 7DC037B42FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift */, - 7DC037C42FE3717200CF0CB8 /* IterableIteratorProtocol+MapError.swift */, - 7DC037B52FE3492D00CF0CB8 /* IterableIteratorProtocol+Reduce.swift */, - 7DC037B62FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift */, + 7DC037B02FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift */, + 7DC037B12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift */, + 7DC037B22FE3492D00CF0CB8 /* BorrowingIteratorProtocol+ElementsEqual.swift */, + 7DC037B32FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift */, + 7DC037B42FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Map.swift */, + 7DC037C42FE3717200CF0CB8 /* BorrowingIteratorProtocol+MapError.swift */, + 7DC037B52FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Reduce.swift */, + 7DC037B62FE3492D00CF0CB8 /* BorrowingIteratorProtocol+SpanwiseZip.swift */, 7D57EDCE2F647DB10029D5E3 /* Container */, + 7D77E6112FCF810E003FA63B /* CountedProducer.swift */, 7D2A772F2F27F1E4005780C7 /* Drain.swift */, 7D57EDCF2F647DB10029D5E3 /* Drain+Map.swift */, 7D57EDD02F647DB10029D5E3 /* Drain+Reduce.swift */, @@ -1338,6 +1366,7 @@ 7D57EDE62F64913C0029D5E3 /* Producer+Filter.swift */, 7D57EDD12F647DB10029D5E3 /* Producer+Map.swift */, 7D57EDD22F647DB10029D5E3 /* Producer+Reduce.swift */, + 7D3F1F7A3007176C00AD924D /* Producer+Unfold.swift */, ); path = Protocols; sourceTree = ""; @@ -1347,9 +1376,9 @@ children = ( 7D2A77332F27F1E4005780C7 /* UniqueBox.swift */, 7DC037C82FE3792300CF0CB8 /* MutableRef.swift */, + 7D12E33C2FF5CC2A003050AB /* OutputSpan+Helpers.swift */, 7D2A77352F27F1E4005780C7 /* InputSpan.swift */, 7D2A77362F27F1E4005780C7 /* Shared.swift */, - 7DACFA112F75FBF100291F2E /* SpanIterator.swift */, ); path = Types; sourceTree = ""; @@ -1424,6 +1453,7 @@ 7D479CCC2F46D23400A8CB59 /* UniqueSet+BorrowingSequence.swift */, 7D479CC42F46D20400A8CB59 /* UniqueSet+Consumption.swift */, 7D479CBA2F46A71500A8CB59 /* UniqueSet+Debugging.swift */, + 7D945E6A2FF5E0CB001041A6 /* UniqueSet+Deprecations.swift */, 7DEB31532F4E75AF00F9AF28 /* UniqueSet+Equatable.swift */, 7DEB31552F4E75B800F9AF28 /* UniqueSet+Hashable.swift */, 7DEB31652F52268100F9AF28 /* UniqueSet+Index.swift */, @@ -1459,10 +1489,10 @@ 7D48BCCE2E51524200D7F6F7 /* ContainersPreview */ = { isa = PBXGroup; children = ( - 7D2A77292F27F1E4005780C7 /* Extensions */, + 7D59D0602FE49BDA005B5097 /* CMakeLists.txt */, + 7D59D0652FE49C87005B5097 /* Conformances */, 7D2A77312F27F1E4005780C7 /* Protocols */, 7D2A77372F27F1E4005780C7 /* Types */, - 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */, 7D6FEE312E88A4B9007C1B86 /* ContainersPreview.docc */, ); path = ContainersPreview; @@ -1498,6 +1528,25 @@ path = Container; sourceTree = ""; }; + 7D59D0652FE49C87005B5097 /* Conformances */ = { + isa = PBXGroup; + children = ( + 7D0DC7BE2FFD929500BEE8B2 /* Array+Iterable.swift */, + 7D0DC7C42FFD990E00BEE8B2 /* ClosedRange+Iterable.swift */, + 7D0DC7C02FFD92B500BEE8B2 /* InlineArray+Iterable.swift */, + 7D945E722FF71E86001041A6 /* InputSpan+Iterable.swift */, + 7D59D0612FE49C87005B5097 /* InputSpan+Container.swift */, + 7D945E6E2FF71DF8001041A6 /* MutableSpan+Iterable.swift */, + 7D59D0622FE49C87005B5097 /* MutableSpan+Container.swift */, + 7D945E702FF71E53001041A6 /* OutputSpan+Iterable.swift */, + 7D59D0632FE49C87005B5097 /* OutputSpan+Container.swift */, + 7D0DC7C22FFD987400BEE8B2 /* Range+Iterable.swift */, + 7D945E6C2FF71D76001041A6 /* Span+Iterable.swift */, + 7D59D0642FE49C87005B5097 /* Span+Container.swift */, + ); + path = Conformances; + sourceTree = ""; + }; 7D7246822F3D9DDB00112FD0 /* HashTable */ = { isa = PBXGroup; children = ( @@ -1506,6 +1555,7 @@ 7D72467C2F3D9DDB00112FD0 /* _HTable+Bucket.swift */, 7D479CE62F47D88000A8CB59 /* _HTable+Consumption.swift */, 7D9B75762F3E65DB0048157E /* _HTable+Debug.swift */, + 7D12E33E2FF5DADE003050AB /* _HTable+Deprecated.swift */, 7D72467E2F3D9DDB00112FD0 /* _HTable+Find.swift */, 7D72467F2F3D9DDB00112FD0 /* _HTable+Insert.swift */, 7D7246802F3D9DDB00112FD0 /* _HTable+Iteration.swift */, @@ -1543,6 +1593,7 @@ 7D479CAF2F450E3F00A8CB59 /* RigidSet+BorrowingSequence.swift */, 7D479CC02F46D14800A8CB59 /* RigidSet+Consumption.swift */, 7D479CB82F46A6D700A8CB59 /* RigidSet+Debugging.swift */, + 7D12E3402FF5DD07003050AB /* RigidSet+Deprecated.swift */, 7D479CFE2F4E487700A8CB59 /* RigidSet+Equatable.swift */, 7DEB31512F4E720500F9AF28 /* RigidSet+Hashable.swift */, 7DEB31632F5218A600F9AF28 /* RigidSet+Index.swift */, @@ -1949,19 +2000,24 @@ children = ( 7DEBDAE229CBEE5300ADC226 /* IntegerTricks */, 7DEBDADA29CBEE5300ADC226 /* UnsafeBitSet */, - 7DE91F2E29CA70F3004483EB /* CMakeLists.txt */, + 7DFC9DF62FEB5D7D00BE8808 /* CMakeLists.txt */, 7DE91F3029CA70F3004483EB /* _SortedCollection.swift */, 7DE91F3829CA70F3004483EB /* _UniqueCollection.swift */, 7DAD89A82E8B09EC00DD5786 /* Debugging.swift */, 7DAD89A92E8B09EC00DD5786 /* Descriptions.swift */, 7DAD89AA2E8B09EC00DD5786 /* LifetimeOverride.swift */, + 7D59D0592FE48B89005B5097 /* Optional+Extras.swift */, + 7D59D05A2FE48B89005B5097 /* OutputSpan+Extras.swift */, 7DAD89AB2E8B09EC00DD5786 /* RandomAccessCollection+Offsets.swift */, 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */, 7DC85F8C2F3FDC82004A4E3D /* String+Padding.swift */, + 7D59D05B2FE48B89005B5097 /* TemporaryAllocation.swift */, 7DAD89AC2E8B09EC00DD5786 /* UnsafeBufferPointer+Extras.swift */, 7DAD89AD2E8B09EC00DD5786 /* UnsafeMutableBufferPointer+Extras.swift */, 7DAD89AE2E8B09EC00DD5786 /* UnsafeMutableRawBufferPointer+Extras.swift */, 7DAD89AF2E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift */, + 7D77E6242FD0F87B003FA63B /* UnsafePointer+Extras.swift */, + 7D77E6262FD0F940003FA63B /* UnsafeMutablePointer+Extras.swift */, ); path = InternalCollectionsUtilities; sourceTree = ""; @@ -2402,6 +2458,7 @@ 7DEBDB2529CCE43600ADC226 /* Utilities */ = { isa = PBXGroup; children = ( + 7D0DC7C62FFDC40600BEE8B2 /* With.swift */, 7DEBDB2C29CCE43600ADC226 /* AllOnesRandomNumberGenerator.swift */, 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */, 7D48BCDD2E51558700D7F6F7 /* TestPrintable.swift */, @@ -2577,7 +2634,7 @@ attributes = { BuildIndependentTargetsInParallel = 1; LastSwiftUpdateCheck = 1430; - LastUpgradeCheck = 2640; + LastUpgradeCheck = 2700; TargetAttributes = { 7DE91B2529CA6721004483EB = { CreatedOnToolsVersion = 14.3; @@ -2637,22 +2694,21 @@ 7D479CB02F450E4600A8CB59 /* RigidSet+BorrowingSequence.swift in Sources */, 7DE9216629CA70F4004483EB /* _HashNode+Storage.swift in Sources */, 7DE920CE29CA70F4004483EB /* BitSet+CustomReflectable.swift in Sources */, - 7DC037C52FE3717A00CF0CB8 /* IterableIteratorProtocol+MapError.swift in Sources */, + 7DC037C52FE3717A00CF0CB8 /* BorrowingIteratorProtocol+MapError.swift in Sources */, 7DE9215029CA70F4004483EB /* _UnmanagedHashNode.swift in Sources */, 7DE920EF29CA70F4004483EB /* BitArray+Codable.swift in Sources */, 7DE920C029CA70F4004483EB /* BitSet+SetAlgebra conformance.swift in Sources */, 7DE9203C29CA70F3004483EB /* OrderedSet+Partial SetAlgebra formSymmetricDifference.swift in Sources */, - 7DC037B72FE3492D00CF0CB8 /* IterableIteratorProtocol+Copy.swift in Sources */, + 7DC037B72FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Copy.swift in Sources */, 7DC037B82FE3492D00CF0CB8 /* Iterable+Utilities.swift in Sources */, - 7DC037B92FE3492D00CF0CB8 /* Iterable+Standard Conformances.swift in Sources */, - 7DC037BA2FE3492D00CF0CB8 /* IterableIteratorProtocol.swift in Sources */, + 7DC037BA2FE3492D00CF0CB8 /* BorrowingIteratorProtocol.swift in Sources */, 7DC037BB2FE3492D00CF0CB8 /* Iterable+Algorithms.swift in Sources */, - 7DC037BC2FE3492D00CF0CB8 /* IterableIteratorProtocol+Filter.swift in Sources */, + 7DC037BC2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Filter.swift in Sources */, 7DC037BD2FE3492D00CF0CB8 /* Iterable.swift in Sources */, - 7DC037BE2FE3492D00CF0CB8 /* IterableIteratorProtocol+ElementsEqual.swift in Sources */, - 7DC037BF2FE3492D00CF0CB8 /* IterableIteratorProtocol+Reduce.swift in Sources */, - 7DC037C02FE3492D00CF0CB8 /* IterableIteratorProtocol+SpanwiseZip.swift in Sources */, - 7DC037C12FE3492D00CF0CB8 /* IterableIteratorProtocol+Map.swift in Sources */, + 7DC037BE2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+ElementsEqual.swift in Sources */, + 7DC037BF2FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Reduce.swift in Sources */, + 7DC037C02FE3492D00CF0CB8 /* BorrowingIteratorProtocol+SpanwiseZip.swift in Sources */, + 7DC037C12FE3492D00CF0CB8 /* BorrowingIteratorProtocol+Map.swift in Sources */, 7DE9209029CA70F4004483EB /* Rope.swift in Sources */, 7D2A77782F27F2BF005780C7 /* Deque._Storage.swift in Sources */, 7D2A77792F27F2BF005780C7 /* RigidDeque+Prepend.swift in Sources */, @@ -2664,6 +2720,7 @@ 7D2A777F2F27F2BF005780C7 /* RigidDeque+Container.swift in Sources */, 7D2A77802F27F2BF005780C7 /* Deque.swift in Sources */, 7D2A77812F27F2BF005780C7 /* UniqueDeque+Append.swift in Sources */, + 7D945E712FF71E58001041A6 /* OutputSpan+Iterable.swift in Sources */, 7D2A77822F27F2BF005780C7 /* UniqueDeque+Initializers.swift in Sources */, 7D2A77832F27F2BF005780C7 /* Deque+Equatable.swift in Sources */, 7D2A77842F27F2BF005780C7 /* UniqueDeque+Container.swift in Sources */, @@ -2690,9 +2747,10 @@ 7D2A77952F27F2BF005780C7 /* Deque+Codable.swift in Sources */, 7D2A77962F27F2BF005780C7 /* RigidDeque+Experimental.swift in Sources */, 7D2A77972F27F2BF005780C7 /* Deque+Testing.swift in Sources */, + 7D12E33D2FF5CC2A003050AB /* OutputSpan+Helpers.swift in Sources */, 7D2A77982F27F2BF005780C7 /* RigidDeque+Replacements.swift in Sources */, 7D7246872F3D9DDB00112FD0 /* _HTable+Iteration.swift in Sources */, - 7DC037C72FE378B300CF0CB8 /* Optional+Extras.swift in Sources */, + 7D945E6B2FF5E0D1001041A6 /* UniqueSet+Deprecations.swift in Sources */, 7D7246882F3D9DDB00112FD0 /* RigidDictionary.swift in Sources */, 7D7246892F3D9DDB00112FD0 /* _HTable+Find.swift in Sources */, 7D72468A2F3D9DDB00112FD0 /* _HTable.swift in Sources */, @@ -2724,6 +2782,7 @@ 7D57A2B82F33FF48002543BD /* RigidArray+Consumption.swift in Sources */, 7DA23F582F32C66300E4C03A /* RigidArray+Equatable.swift in Sources */, 7D479CFC2F4D080500A8CB59 /* UniqueDictionary+Removals.swift in Sources */, + 7D77E6272FD0F94B003FA63B /* UnsafeMutablePointer+Extras.swift in Sources */, 7D479CFD2F4D080500A8CB59 /* UniqueDictionary+Keys.swift in Sources */, 7DE9208A29CA70F4004483EB /* BigString+Comparable.swift in Sources */, 7DE9213629CA70F4004483EB /* TreeSet+SetAlgebra basics.swift in Sources */, @@ -2737,6 +2796,7 @@ 7DE9204629CA70F3004483EB /* _Hashtable+Header.swift in Sources */, 7DE9208129CA70F4004483EB /* BigString+CustomStringConvertible.swift in Sources */, 7DE920A929CA70F4004483EB /* Optional Utilities.swift in Sources */, + 7D77E6252FD0F880003FA63B /* UnsafePointer+Extras.swift in Sources */, 7DE920BD29CA70F4004483EB /* BitSet+SetAlgebra symmetricDifference.swift in Sources */, 7DE9208229CA70F4004483EB /* BigString+BidirectionalCollection.swift in Sources */, 7D479CDF2F47D5CA00A8CB59 /* RigidDictionary+Insertions.swift in Sources */, @@ -2768,6 +2828,7 @@ 7D479CF32F47FB4100A8CB59 /* _HTable+Removal.swift in Sources */, 7DE9203529CA70F3004483EB /* OrderedSet+CustomReflectable.swift in Sources */, 7DEB31582F4E762200F9AF28 /* RigidDictionary+Equatable.swift in Sources */, + 7D3F1F7B3007177100AD924D /* Producer+Unfold.swift in Sources */, 7DE920C929CA70F4004483EB /* BitSet+BidirectionalCollection.swift in Sources */, 7DE920ED29CA70F4004483EB /* BitArray+Extras.swift in Sources */, 7DE9206829CA70F4004483EB /* BigString+Chunk+Append and Insert.swift in Sources */, @@ -2778,7 +2839,6 @@ 7DE9209A29CA70F4004483EB /* Rope+Append.swift in Sources */, 7DE9203F29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isDisjoint.swift in Sources */, 7DC85F8D2F3FDC91004A4E3D /* String+Padding.swift in Sources */, - 7DACFA122F75FBF100291F2E /* SpanIterator.swift in Sources */, 7DE9208629CA70F4004483EB /* BigString+LosslessStringConvertible.swift in Sources */, 7DE9204329CA70F3004483EB /* _HashTable+Bucket.swift in Sources */, 7DE9216A29CA70F4004483EB /* TreeDictionary.swift in Sources */, @@ -2801,6 +2861,7 @@ 7D479CE72F47D88600A8CB59 /* _HTable+Consumption.swift in Sources */, 7DE9202B29CA70F3004483EB /* OrderedSet+Equatable.swift in Sources */, 7D479CC52F46D20B00A8CB59 /* UniqueSet+Consumption.swift in Sources */, + 7D0DC7BF2FFD929900BEE8B2 /* Array+Iterable.swift in Sources */, 7DE920EA29CA70F4004483EB /* BitArray.swift in Sources */, 7DE920CB29CA70F4004483EB /* BitSet+Random.swift in Sources */, 7DE9201629CA70F3004483EB /* OrderedDictionary+Elements.swift in Sources */, @@ -2875,6 +2936,7 @@ 7DAD899E2E8B09C300DD5786 /* UInt+first and last set bit.swift in Sources */, 7DAD899F2E8B09C300DD5786 /* UInt+reversed.swift in Sources */, 7DAD89A02E8B09C300DD5786 /* FixedWidthInteger+roundUpToPowerOfTwo.swift in Sources */, + 7D12E3412FF5DD0B003050AB /* RigidSet+Deprecated.swift in Sources */, 7DAD89A12E8B09C300DD5786 /* Integer rank.swift in Sources */, 7DE9207429CA70F4004483EB /* BigString+ReplaceSubrange.swift in Sources */, 7DE920DC29CA70F4004483EB /* BitSet+Invariants.swift in Sources */, @@ -2928,6 +2990,7 @@ 7DE920A329CA70F4004483EB /* Rope+Index.swift in Sources */, 7DA23F462F329A2300E4C03A /* RigidArray+Experimental.swift in Sources */, 7DA23F472F329A2300E4C03A /* UniqueArray.swift in Sources */, + 7D945E732FF71E8C001041A6 /* InputSpan+Iterable.swift in Sources */, 7DFA40842FD3A98D00CD20C1 /* OrderedSet+Move.swift in Sources */, 7DA23F482F329A2300E4C03A /* RigidArray+Replacements.swift in Sources */, 7DA23F492F329A2300E4C03A /* RigidArray+Container.swift in Sources */, @@ -2952,6 +3015,9 @@ 7DE9214729CA70F4004483EB /* _HashNode+Primitive Replacement.swift in Sources */, 7DE9201229CA70F3004483EB /* OrderedDictionary+Elements.SubSequence.swift in Sources */, 7DE9204429CA70F3004483EB /* _HashTable.swift in Sources */, + 7D59D05C2FE48B89005B5097 /* Optional+Extras.swift in Sources */, + 7D59D05D2FE48B89005B5097 /* OutputSpan+Extras.swift in Sources */, + 7D59D05E2FE48B89005B5097 /* TemporaryAllocation.swift in Sources */, 7DE9206529CA70F4004483EB /* BigString+Ingester.swift in Sources */, 7DE9209129CA70F4004483EB /* Rope+_UnsafeHandle.swift in Sources */, 7DC037C32FE34B2800CF0CB8 /* Heap+Testing.swift in Sources */, @@ -2967,10 +3033,9 @@ 7DE9215529CA70F4004483EB /* _RawHashNode+UnsafeHandle.swift in Sources */, 7D2A77392F27F1E4005780C7 /* UniqueBox.swift in Sources */, 7D2A773A2F27F1E4005780C7 /* Drain.swift in Sources */, + 7D12E33F2FF5DAE4003050AB /* _HTable+Deprecated.swift in Sources */, 7D479CC32F46D19600A8CB59 /* RigidSet+Resizing.swift in Sources */, - 7D2A773C2F27F1E4005780C7 /* TemporaryAllocation.swift in Sources */, 7D57A2D02F353946002543BD /* RigidArray+Deprecated.swift in Sources */, - 7D2A77422F27F1E4005780C7 /* OutputSpan+Extras.swift in Sources */, 7D2A77432F27F1E4005780C7 /* Shared.swift in Sources */, 7D2A77442F27F1E4005780C7 /* InputSpan.swift in Sources */, 7D2A77452F27F1E4005780C7 /* Producer.swift in Sources */, @@ -3009,6 +3074,7 @@ 7DE9202729CA70F3004483EB /* OrderedSet+Insertions.swift in Sources */, 7D479CD42F46DD9600A8CB59 /* UniqueSet+Initializers.swift in Sources */, 7DE9208729CA70F4004483EB /* BigString+Sequence.swift in Sources */, + 7D0DC7C32FFD987800BEE8B2 /* Range+Iterable.swift in Sources */, 7DE9202229CA70F3004483EB /* OrderedSet+Diffing.swift in Sources */, 7DE920CA29CA70F4004483EB /* BitSet+CustomStringConvertible.swift in Sources */, 7DEB31622F4F98D700F9AF28 /* RigidDictionary+Indices.swift in Sources */, @@ -3039,6 +3105,7 @@ 7DE9201829CA70F3004483EB /* OrderedDictionary+Invariants.swift in Sources */, 7DE920CD29CA70F4004483EB /* BitSet+CustomDebugStringConvertible.swift in Sources */, 7DE9212529CA70F4004483EB /* TreeSet+SetAlgebra isStrictSubset.swift in Sources */, + 7D945E6F2FF71DFF001041A6 /* MutableSpan+Iterable.swift in Sources */, 7DE9209229CA70F4004483EB /* Rope+_Storage.swift in Sources */, 7DE9203929CA70F3004483EB /* OrderedSet+Partial RangeReplaceableCollection.swift in Sources */, 7DE9206329CA70F4004483EB /* BigString+Contents.swift in Sources */, @@ -3059,6 +3126,10 @@ 7DE9217E29CA70F4004483EB /* Heap+ExpressibleByArrayLiteral.swift in Sources */, 7D57EDD32F647DB10029D5E3 /* RandomAccessContainer.swift in Sources */, 7D57EDD52F647DB10029D5E3 /* MutableContainer.swift in Sources */, + 7D59D0662FE49C87005B5097 /* Span+Container.swift in Sources */, + 7D59D0672FE49C87005B5097 /* InputSpan+Container.swift in Sources */, + 7D59D0682FE49C87005B5097 /* MutableSpan+Container.swift in Sources */, + 7D59D0692FE49C87005B5097 /* OutputSpan+Container.swift in Sources */, 7D57EDD62F647DB10029D5E3 /* DynamicContainer.swift in Sources */, 7D57EDD72F647DB10029D5E3 /* Drain+Reduce.swift in Sources */, 7D57EDD82F647DB10029D5E3 /* Producer+Map.swift in Sources */, @@ -3092,19 +3163,23 @@ 7DE920E029CA70F4004483EB /* Range+Utilities.swift in Sources */, 7DE920D929CA70F4004483EB /* BitSet+SetAlgebra intersection.swift in Sources */, 7DE920DD29CA70F4004483EB /* BitSet+SetAlgebra isStrictSubset.swift in Sources */, + 7D0DC7C52FFD990E00BEE8B2 /* ClosedRange+Iterable.swift in Sources */, 7DE920F229CA70F4004483EB /* BitArray._UnsafeHandle.swift in Sources */, 7D479CEB2F47F3C100A8CB59 /* UniqueDictionary+Resizing.swift in Sources */, 7DE9204229CA70F3004483EB /* _HashTable+UnsafeHandle.swift in Sources */, 7DE9208E29CA70F4004483EB /* _RopeVersion.swift in Sources */, 7DE9212629CA70F4004483EB /* TreeSet+Sendable.swift in Sources */, 7DE9209C29CA70F4004483EB /* Rope+Find.swift in Sources */, + 7D77E6122FCF810E003FA63B /* CountedProducer.swift in Sources */, 7DE920E829CA70F4004483EB /* BitArray+BitwiseOperations.swift in Sources */, 7DE9207829CA70F4004483EB /* BigString+Append.swift in Sources */, + 7D0DC7C12FFD92BB00BEE8B2 /* InlineArray+Iterable.swift in Sources */, 7DE9217F29CA70F4004483EB /* _HeapNode.swift in Sources */, 7D479CB92F46A6DB00A8CB59 /* RigidSet+Debugging.swift in Sources */, 7DE9202929CA70F3004483EB /* OrderedSet+Codable.swift in Sources */, 7DE9204829CA70F3004483EB /* _HashTable+CustomStringConvertible.swift in Sources */, 7D479CE52F47D74500A8CB59 /* RigidDictionary+Resizing.swift in Sources */, + 7D945E6D2FF71D76001041A6 /* Span+Iterable.swift in Sources */, 7DE9213029CA70F4004483EB /* TreeSet+SetAlgebra isSuperset.swift in Sources */, 7DE9217529CA70F4004483EB /* TreeDictionary+MapValues.swift in Sources */, 7DE9206C29CA70F4004483EB /* BigString+Chunk.swift in Sources */, @@ -3208,6 +3283,7 @@ 7DEBDB7E29CCE44A00ADC226 /* CheckComparable.swift in Sources */, 7DEBDB7C29CCE44A00ADC226 /* MinimalDecoder.swift in Sources */, 7DE9220829CA8576004483EB /* BitSetTests.swift in Sources */, + 7D0DC7C72FFDC40900BEE8B2 /* With.swift in Sources */, 7DEBDB7329CCE44A00ADC226 /* _MinimalCollectionCore.swift in Sources */, 7DE921C829CA81DC004483EB /* _UniqueCollection.swift in Sources */, 7D48BCF42E5159A300D7F6F7 /* StaccatoContainer.swift in Sources */, diff --git a/Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme b/Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme index 48e313d4..afc31473 100644 --- a/Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme +++ b/Xcode/Collections.xcodeproj/xcshareddata/xcschemes/Collections.xcscheme @@ -1,6 +1,6 @@