From b21316ea08ae9380b1aac0937bd112017c752f2a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 9 Feb 2026 17:28:31 -0800 Subject: [PATCH 1/2] [DequeModule] Add some top-level RigidDeque/UniqueDeque docs --- .../UniqueArray/UniqueArray.swift | 10 ++- .../DequeModule/RigidDeque/RigidDeque.swift | 81 ++++++++++++++++++- .../DequeModule/UniqueDeque/UniqueDeque.swift | 71 ++++++++++++++++ 3 files changed, 157 insertions(+), 5 deletions(-) diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray.swift b/Sources/BasicContainers/UniqueArray/UniqueArray.swift index 17cfaae3..404c7c15 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray.swift @@ -37,26 +37,28 @@ public struct UniqueArray: ~Copyable { /// /// `UniqueArray` instances automatically resize their underlying storage as /// needed to accommodate newly inserted items, using a geometric growth curve. -/// This frees code using `UniqueArray` from having to allocate enough +/// This lets code using `UniqueArray` avoid having to allocate enough /// capacity in advance; on the other hand, it makes it difficult to tell /// when and where such reallocations may happen. /// -/// For example, appending an element to a dynamic array has highly variable +/// For example, appending an element to a `UniqueArray` has highly variable /// complexity; often, it runs at a constant cost, but if the operation has to /// resize storage, then the cost of an individual append suddenly becomes /// proportional to the size of the whole array. /// /// The geometric growth curve allows the cost of such latency spikes to /// get amortized across repeated invocations, bringing the average cost back -/// to O(1); but they make this construct less suitable for use cases that +/// to O(1); but the spikes make this construct less suitable for use cases that /// expect predictable, consistent performance on every operation. /// /// Implicit growth also makes it more difficult to predict/analyze the amount /// of memory an algorithm would need. Developers targeting environments with /// stringent limits on heap allocations may prefer to avoid using dynamically -/// resizing array types as a matter of policy. The type `RigidArray` provides +/// resizing container types as a matter of policy. The type `RigidArray` provides /// a fixed-capacity array variant that caters specifically for these use cases, /// trading ease-of-use for more consistent/predictable execution. +/// For copyable elements, the copy-on-write `Array` type is an +/// even more convenient and expressive choice. @available(SwiftStdlib 5.0, *) @frozen public struct UniqueArray: ~Copyable { diff --git a/Sources/DequeModule/RigidDeque/RigidDeque.swift b/Sources/DequeModule/RigidDeque/RigidDeque.swift index 1f7f82d8..caace267 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque.swift @@ -29,7 +29,86 @@ public struct RigidDeque: ~Copyable { #else /// A fixed capacity, heap allocated, noncopyable double-ended queue of -/// potentially noncopyable elements. +/// potentially noncopyable elements. A deque (pronounced "deck") +/// is an ordered random-access container that supports efficient +/// insertions and removals from both ends. +/// +/// Deques implement the same indexing semantics as arrays: they use integer +/// indices, and the first element of a nonempty deque is always at logical +/// index zero. +/// +/// var colors = RigidDeque(capacity: 5) +/// colors.append("red") +/// colors.prepend("yellow") +/// colors.append("blue") +/// // `colors` now contains "yellow", "red", "blue" +/// +/// print(colors[0]) // prints "yellow" +/// print(colors[1]) // prints "red" +/// +/// print(colors.removeFirst()) // prints "yellow" +/// print(colors.removeLast()) // prints "blue" +/// // `colors` now contains "red" +/// +/// This double-ended nature makes deques particularly well-suited for +/// representing first-in-first-out (FIFO) buffers, where new items are +/// inserted at one end, and old items are retrieved from the other. +/// For example, they are ideal for modeling buffered data streams, such as +/// networking channels, or other producer/consumer scenarios. +/// +/// ### Implementation Notes +/// +/// `RigidDeque` implements a ring buffer. It stores its elements in a +/// single heap-allocated buffer, and to allow fast insertions and removals +/// from both ends, the buffer behaves as if its ends were glued together into +/// a ring shape. This comes at the cost of potentially discontiguous storage, as +/// the contents of the ring buffer sometimes wrap around the edges. +/// +/// While the first item in the deque is always addressed by the logical index +/// zero, its physical location can be anywhere in the underlying ring buffer. +/// Compare this with `RigidArray`'s contiguous storage, where the first item +/// is always stored at the start of the buffer, so new data can always be +/// efficiently appended to the end, but inserting at the front is relatively +/// slow, as existing elements need to be shifted to make room. +/// +/// ### Fixed Storage Capacity +/// +/// `RigidDeque` instances are created with a specific maximum capacity. +/// Elements can be added to the deque up to that capacity, but no more: trying +/// to add an item to a full deque results in a runtime trap. +/// +/// var items = RigidDeque(capacity: 2) +/// items.prepend(1) +/// items.prepend(2) +/// items.prepend(3) // Runtime error: RigidDeque capacity overflow +/// +/// Rigid deques provide convenience properties to help verify that it has +/// enough available capacity: `isFull` and `freeCapacity`. +/// +/// guard items.freeCapacity >= 4 else { throw CapacityOverflow() } +/// items.append(copying: newItems) +/// +/// It is possible to extend or shrink the capacity of a rigid deque instance, +/// but this needs to be done explicitly, with operations dedicated to this +/// purpose (such as ``reserveCapacity`` and ``reallocate(capacity:)``). +/// The deque never resizes itself automatically. +/// +/// Therefore, it is necessary to perform careful manual analysis (or up front +/// runtime capacity checks) to prevent the deque from overflowing its storage. +/// This makes this type more difficult to use than a dynamically resizing +/// container. However, it allows this construct to provide predictably stable +/// performance. +/// +/// This trading of usability in favor of stable performance limits `RigidDeque` +/// to the most resource-constrained of use cases, such as space-constrained +/// environments that require carefully accounting of every heap allocation, or +/// time-constrained applications that cannot accommodate unexpected latency +/// spikes due to a reallocation getting triggered at an inopportune moment. +/// +/// For use cases outside of these narrow domains, we generally recommmend +/// to use the dynamically resizing ``UniqueDeque`` type rather than +/// `RigidDeque`. For copyable elements, the copy-on-write `Deque` type is an +/// even more convenient and expressive choice. @available(SwiftStdlib 5.0, *) @frozen @safe diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift index 761eb6c5..ab52644c 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque.swift @@ -16,6 +16,10 @@ import ContainersPreview #if compiler(<6.2) +/// A dynamically self-resizing, heap allocated, noncopyable double-ended +/// queue of potentially noncopyable elements. A deque (pronounced "deck") +/// is an ordered random-access container that supports efficient +/// insertions and removals from both ends. @frozen @available(*, unavailable, message: "UniqueDeque requires a Swift 6.2 toolchain") public struct UniqueDeque: ~Copyable { @@ -26,6 +30,73 @@ public struct UniqueDeque: ~Copyable { #else +/// A dynamically self-resizing, heap allocated, noncopyable double-ended +/// queue of potentially noncopyable elements. A deque (pronounced "deck") +/// is an ordered random-access container that supports efficient +/// insertions and removals from both ends. +/// +/// Deques implement the same indexing semantics as arrays: they use integer +/// indices, and the first element of a nonempty deque is always at logical +/// index zero. +/// +/// var colors = UniqueDeque() +/// colors.append("red") +/// colors.prepend("yellow") +/// colors.append("blue") +/// // `colors` now contains "yellow", "red", "blue" +/// +/// print(colors[0]) // prints "yellow" +/// print(colors[1]) // prints "red" +/// +/// print(colors.removeFirst()) // prints "yellow" +/// print(colors.removeLast()) // prints "blue" +/// // `colors` now contains "red" +/// +/// This double-ended nature makes deques particularly well-suited for +/// representing first-in-first-out (FIFO) buffers, where new items are +/// inserted at one end, and old items are retrieved from the other. +/// For example, they are ideal for modeling buffered data streams, such as +/// networking channels, or other producer/consumer scenarios. +/// +/// ### Implementation Notes +/// +/// `UniqueDeque` implements a ring buffer. It stores its elements in a +/// single heap-allocated buffer, and to allow fast insertions and removals +/// from both ends, the buffer behaves as if its ends were glued together into +/// a ring shape. This comes at the cost of potentially discontiguous storage, as +/// the contents of the ring buffer sometimes wrap around the edges. +/// +/// While the first item in the deque is always addressed by the logical index +/// zero, its physical location can be anywhere in the underlying ring buffer. +/// Compare this with `UniqueArray`'s contiguous storage, where the first item +/// is always stored at the start of the buffer, so new data can always be +/// efficiently appended to the end, but inserting at the front is relatively +/// slow, as existing elements need to be shifted to make room. +/// +/// ### Dynamic Storage Sizing +/// +/// `UniqueDeque` instances automatically resize their underlying storage as +/// needed to accommodate newly inserted items, using a geometric growth curve. +/// This lets code using `UniqueDeque` avoid having to carefully allocate enough +/// capacity in advance; on the other hand, it makes it difficult to tell +/// when and where such reallocations may happen. +/// +/// For example, appending an element to a `UniqueDeque` has highly variable +/// complexity; often, it runs at a constant cost, but if the operation has to +/// resize storage, then the cost of an individual append suddenly becomes +/// proportional to the size of the whole container. +/// +/// The geometric growth curve allows the cost of such latency spikes to +/// get amortized across repeated invocations, bringing the average cost back +/// to O(1); but the spikes make this construct less suitable for use cases that +/// expect predictable, consistent performance on every operation. +/// +/// Implicit growth also makes it more difficult to predict/analyze the amount +/// of memory an algorithm would need. Developers targeting environments with +/// stringent limits on heap allocations may prefer to avoid using dynamically +/// resizing container types as a matter of policy. The type `RigidDeque` +/// provides a fixed-capacity deque variant that caters specifically for these +/// use cases, trading ease-of-use for more consistent/predictable execution. @available(SwiftStdlib 5.0, *) @frozen @safe From 5b05a1b42ba6ae82684f099bbbe25fab06821537 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 9 Feb 2026 17:40:18 -0800 Subject: [PATCH 2/2] Update README in preparation of the 1.4.0 release --- README.md | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 10de447b..c357f14b 100644 --- a/README.md +++ b/README.md @@ -10,25 +10,28 @@ Read more about the package, and the intent behind it, in the [announcement on s The package currently provides the following implementations: -- [`BitSet`][BitSet] and [`BitArray`][BitArray], dynamic bit collections. +- [`UniqueArray`][UniqueArray] and [`RigidArray`][RigidArray], noncopyable array variants trading some of `Array`'s flexibility for more predictable performance. -- [`Deque`][Deque], a double-ended queue backed by a ring buffer. Deques are range-replaceable, mutable, random-access collections. - -- [`Heap`][Heap], a min-max heap backed by an array, suitable for use as a priority queue. +- [`Deque`][Deque], [`UniqueDeque`][UniqueDeque] and [`RigidDeque`][RigidDeque], variants of a double-ended queue type backed by a ring buffer. Deques are range-replaceable, mutable, random-access collections. - [`OrderedSet`][OrderedSet], a variant of the standard `Set` where the order of items is well-defined and items can be arbitrarily reordered. Uses a `ContiguousArray` as its backing store, augmented by a separate hash table of bit packed offsets into it. - [`OrderedDictionary`][OrderedDictionary], an ordered variant of the standard `Dictionary`, providing similar benefits. -- [`TreeSet`][TreeSet] and [`TreeDictionary`][TreeDictionary], persistent hashed collections implementing Compressed Hash-Array Mapped Prefix Trees (CHAMP). These work similar to the standard `Set` and `Dictionary`, but they excel at use cases that mutate shared copies, offering dramatic memory savings and radical time improvements. +- [`BitSet`][BitSet] and [`BitArray`][BitArray], dynamic bit collections. -- [`UniqueArray`][UniqueArray] and [`RigidArray`][RigidArray], noncopyable array variants trading some of `Array`'s flexibility for more predictable performance. +- [`Heap`][Heap], a min-max heap backed by an array, suitable for use as a priority queue. + +- [`TreeSet`][TreeSet] and [`TreeDictionary`][TreeDictionary], persistent hashed collections implementing Compressed Hash-Array Mapped Prefix Trees (CHAMP). These work similar to the standard `Set` and `Dictionary`, but they excel at use cases that mutate shared copies, offering dramatic memory savings and radical time improvements. - [`TrailingArray`][TrailingArray], a low-level, ownership-aware variant of `ManagedBuffer`, for interoperability with C constructs that consist of a fixed-size header directly followed by variable-size storage buffer. [BitSet]: https://swiftpackageindex.com/apple/swift-collections/documentation/bitcollections/bitset [BitArray]: https://swiftpackageindex.com/apple/swift-collections/documentation/bitcollections/bitarray [Deque]: https://swiftpackageindex.com/apple/swift-collections/documentation/dequemodule/deque +[RigidDeque]: https://swiftpackageindex.com/apple/swift-collections/documentation/dequemodule/rigiddeque +[UniqueDeque]: https://swiftpackageindex.com/apple/swift-collections/documentation/dequemodule/uniquedeque +[Deque]: https://swiftpackageindex.com/apple/swift-collections/documentation/dequemodule/deque [Heap]: https://swiftpackageindex.com/apple/swift-collections/documentation/heapmodule/heap [OrderedSet]: https://swiftpackageindex.com/apple/swift-collections/documentation/orderedcollections/orderedset [OrderedDictionary]: https://swiftpackageindex.com/apple/swift-collections/documentation/orderedcollections/ordereddictionary @@ -57,7 +60,7 @@ The Swift Collections package is source stable. The version numbers follow [Sema ### Public API -The public API of version 1.3 of the `swift-collections` package consists of non-underscored declarations that are marked `public` in the `Collections`, `BitCollections`, `DequeModule`, `HeapModule`, `OrderedCollections` and `HashTreeCollections` modules. +The public API of version 1.4 of the `swift-collections` package consists of non-underscored declarations that are marked `public` in the `Collections`, `BasicContainers`, `BitCollections`, `DequeModule`, `HeapModule`, `OrderedCollections` and `HashTreeCollections` modules. Interfaces that aren't part of the public API may continue to change in any release, including patch releases. @@ -68,9 +71,11 @@ By "underscored declarations" we mean declarations that have a leading underscor - `_FooModule.Bar` (underscored module) - `FooModule.Bar.init(_value:)` (underscored initializer) +Interfaces that get enabled by opting into either of the `UnstableContainersPreview` or `UnstableSortedCollections` package traits are not part of the public API; those interfaces may get removed or changed in any release. + If you have a use case that requires using underscored (or otherwise non-public) APIs, please [submit a Feature Request][enhancement] describing it! We'd like the public interface to be as useful as possible -- although preferably without compromising safety or limiting future evolution. -This source compatibility promise only applies to swift-collection when built as a Swift package. (The repository also contains unstable configurations for building swift-collections using CMake and Xcode. These configurations are provided for internal Swift project use only -- such as for building the (private) swift-collections binaries that ship within Swift toolchains.) +This source compatibility promise only applies to swift-collections when built as a Swift package. (The repository also contains unstable configurations for building swift-collections using CMake and Xcode. These configurations are provided for internal Swift project use only -- such as for building the (private) swift-collections binaries that ship within Swift toolchains.) Note that the files in the `Tests`, `Utils`, `Documentation`, `Xcode`, `cmake` and `Benchmarks` subdirectories may change at whim; they may be added, modified or removed in any new release. Do not rely on anything about them. @@ -88,6 +93,7 @@ The following table maps package releases to their minimum required Swift toolch | swift-collections 1.1.x | >= Swift 5.7.2 | >= Xcode 14.2 | | swift-collections 1.2.x | >= Swift 5.10.0 | >= Xcode 15.3 | | swift-collections 1.3.x | >= Swift 6.0.3 | >= Xcode 16.2 | +| swift-collections 1.4.x | >= Swift 6.0.3 | >= Xcode 16.2 | (Note: the package has no minimum deployment target, so while it does require clients to use a recent Swift toolchain to build it, the code itself is able to run on any OS release that supports running Swift code.) @@ -104,7 +110,7 @@ let package = Package( dependencies: [ .package( url: "https://github.com/apple/swift-collections.git", - .upToNextMinor(from: "1.3.0") // or `.upToNextMajor + .upToNextMinor(from: "1.4.0") // or `.upToNextMajor ) ], targets: [ @@ -134,15 +140,16 @@ We maintain separate branches for each minor version of the package: | ----------------------- | ----------- | -------- | | swift-collections 1.0.x | release/1.0 | Obsolete | | swift-collections 1.1.x | release/1.1 | Obsolete | -| swift-collections 1.2.x | release/1.2 | Bugfixes only | +| swift-collections 1.2.x | release/1.2 | Obsolete | | swift-collections 1.3.x | release/1.3 | Bugfixes only | +| swift-collections 1.4.x | release/1.4 | Bugfixes only | | n.a. | main | Feature work towards next minor release | Changes must land on the branch corresponding to the earliest release that they will need to ship on. They are periodically propagated to subsequent branches, in the following direction: -`release/1.1` → `release/1.2` → `release/1.3` → `main` +`release/1.3` → `release/1.4` → `main` -For example, anything landing on `release/1.2` will eventually appear on `release/1.3` and then `main` too; there is no need to file standalone PRs for each release line. Change propagation is not instantaneous, as it currently requires manual work -- it is performed by project maintainers. +For example, anything landing on `release/1.3` will eventually appear on `release/1.4` and then `main` too; there is no need to file standalone PRs for each release line. Change propagation is not instantaneous, as it currently requires manual work -- it is performed by project maintainers. ### Working on the package @@ -172,7 +179,7 @@ By submitting a pull request, you represent that you have the right to license y #### Proposing the addition of a new data structure -**Note:** As of 2025, we are fully preoccupied with refactoring our existing data structures to support noncopyable and/or nonescapable element types; this includes designing new container protocols around them. I don't expect we'll have capacity to work on any major new data structure implementations until this effort is complete. +**Note:** We are currently fully preoccupied with refactoring our existing data structures to support noncopyable and/or nonescapable element types; this includes designing new container protocols around them. I don't expect we'll have capacity to work on any major new data structure implementations until this effort is complete. ### Code of Conduct