54 Commits
Author SHA1 Message Date
Sandeep Vijayarao 1aa0323dd7 [SortedCollections] Add differential fuzz tests for SortedDictionary and SortedSet
Run random sequences of operations on SortedDictionary and SortedSet and
compare them against a standard Dictionary/Set model after each step:
count, contents in sorted order (forward and backward), offset-based
indexing, lookups for every key in the domain, and value semantics of
earlier copies.

SortedDictionary operations include subscript assignment, the
`_modify` accessor (`take()`, optional chaining, inout), updateValue,
removeValue, modifyValue(forKey:default:), the default subscript,
remove(at:), removeFirst/removeLast(_:), popFirst/popLast, filter,
mapValues, and rebuilding from a sequence.

SortedSet operations include insert/update/remove with members that are
equal but distinguishable (checking that insert keeps and update
replaces the stored member), remove(at:), removeFirst/removeLast(_:),
the form* set algebra operations, and the element range subscripts.

In debug builds, nodes hold at most 4-5 keys, so even small key domains
produce multi-level trees. Building with COLLECTIONS_INTERNAL_CHECKS
also validates the B-tree after every mutation; with that, these tests
catch the bugs fixed in 93745231 (remove(at:) not rebalancing) and
3a80514a (empty root after removal through `_modify`).
2026-11-05 19:05:49 -08:00
Sandeep Vijayarao 3a80514ab6 [SortedCollections] Collapse an empty root after removing a root key through _modify
UnsafeCursor.removeElement(hasValueHole:) only collapsed an empty root
inside the loop that walks up the cursor's path, which never runs when
the removed key is in the root. Removing such a key with d[key].take()
could leave the root as an internal node with no keys and one child.
Collapse the root after the loop so every path depth is covered.

Fixes #811
2026-11-04 19:17:52 -08:00
Swastik TripathiandClaude Opus 5.5 93745231f1 [SortedCollections] Balance the child after remove(at:)
remove(at:) recursed into the child holding the offset and returned
without balancing it, so repeated removals could empty a leaf. Iterating
then read a stale slot, which returned already-removed elements and read
released references in release builds, and trapped in debug builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 09:43:22 +05:30
Joseph CursioandClaude Opus 5.5 e700932e3b Check SortedSet with checkSetAlgebraMemberIdentity
Run the member identity checker against SortedSet, including a
multi-level tree. With #761's fix reverted, it fails with the wrong
member stored by insert(_:) and update(with:), as reported in #760.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 14:49:07 -05:00
Karoy Lorentey 072a7a1643 Merge pull request #758 from Joseph-Cursio/sortedset-check-set-algebra
[SortedCollections] Check SortedSet's SetAlgebra conformance
2026-10-15 12:39:33 -07:00
Aniket 7353b0ca86 SortedSet: keep the existing member on insert, replace it on update(with:)
Signed-off-by: Aniket <aniketkomailkro@gmail.com>
2026-10-14 08:21:27 +00:00
Joseph CursioandClaude Opus 5.5 722b029996 Check SortedSet's SetAlgebra conformance
SortedSet declares SetAPIChecker since #746, but was never run through
checkSetAlgebra. The models are the same as TreeSet's and OrderedSet's,
plus three larger ones so that the sets span more than one B-tree level
in debug builds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-13 19:00:13 -05:00
Karoy Lorentey 6c138f92d8 Merge pull request #742 from Joseph-Cursio/sortedcollections-hashable
[SortedCollections] Check the BidirectionalCollection, Equatable and Hashable conformances
2026-10-08 17:33:06 -07:00
Karoy Lorentey 34151d7731 Merge pull request #746 from aniketatgithub/fix-sortedset-sequence-setalgebra
SortedSet: generalize set operations to arbitrary Sequences
2026-10-08 17:31:51 -07:00
Karoy Lorentey 75cd22c7aa Update comments
Co-authored-by: Karoy Lorentey <klorentey@apple.com>
2026-10-08 17:07:58 -07:00
Joseph Cursio 13bda5d66d Merge remote-tracking branch 'origin/main' into sortedcollections-hashable 2026-10-08 08:48:15 -05:00
Karoy Lorentey 9e7949017a Tests: add unsafe keywords where needed 2026-10-01 11:44:47 -07:00
Karoy Lorentey d07dc32dfa Sources: Add unsafe keywords where needed 2026-10-01 11:14:29 -07:00
Aniket 0d731a673c SortedSet: generalize set operations to arbitrary Sequences
SortedSet's set operations only accepted another SortedSet, so
SortedSet([1, 2]).union(0 ..< 10) did not compile and the type could
not conform to SetAPIChecker.

Add the customary Sequence generalizations for all 13 operations,
keeping the existing Self overloads as the fast path (concrete beats
generic in overload resolution). Arbitrary sequences fall back through
a temporary SortedSet or, for the membership predicates, allSatisfy.

Fixes #743.

Signed-off-by: Aniket <aniketkomailkro@gmail.com>
2026-09-30 03:14:10 -07:00
Karoy Lorentey c991c8543a Update SortedCollections for un-@testable testing 2026-09-29 18:32:58 -07:00
Karoy Lorentey 0ec72a9532 Stop using @_spi attribute and @testable import 2026-09-29 18:32:55 -07:00
Joseph CursioandClaude Opus 5.5 92a1f6184e Check SortedDictionary.SubSequence's Hashable conformance
test_subSequence_Equatable only compared three single-leaf slices with
expectEqual and expectNotEqual. Also run checkHashable, adding empty
slices, equal slices cut from bulk-built and inserted dictionaries, and
ones that differ from them only in a value or only in their keys.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:13:08 -05:00
Joseph CursioandClaude Opus 5.5 7237739c6b Check SortedDictionary.Values's Hashable conformance
test_values_Equatable only ran checkEquatable over single-leaf
dictionaries. Run checkHashable instead, and add a multi-level class
built in bulk and by insertion with different keys but the same values,
plus one that differs in a single value past the first leaf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:13:08 -05:00
Joseph CursioandClaude Opus 5.5 a091324030 Check SortedDictionary.Keys's Hashable conformance
test_keys_Equatable only ran checkEquatable over single-leaf
dictionaries. Run checkHashable instead, and add a multi-level class
built in bulk and by insertion with different values, plus one that
differs in a single key past the first leaf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:13:08 -05:00
Joseph CursioandClaude Opus 5.5 a7f70f3c9f Check SortedDictionary's Equatable and Hashable conformances
SortedDictionary conforms to Hashable but was never run through
checkHashable. The multi-level dictionary is built both in bulk and by
insertion, so equal dictionaries with different tree layouts must
compare and hash equal; the last two classes differ from it in one key
or one value past the first leaf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:13:08 -05:00
Joseph CursioandClaude Opus 5.5 e4c7f6e3d8 Check SortedSet.SubSequence's Equatable and Hashable conformances
SortedSet.SubSequence has its own copy of SortedSet's == and
hash(into:), and neither was tested. Equal slices are taken from
bulk-built and inserted sets, so they start at different leaf offsets;
the last two classes match the evens slice in count and endpoints and
differ only past the first leaf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 23:13:08 -05:00
Joseph CursioandClaude Opus 5.5 fac3148fe7 Check SortedSet's Equatable and Hashable conformances
SortedSet conforms to Hashable but was never run through checkHashable.
Multi-level sets are built both in bulk and by insertion, so equal sets
with different tree layouts must compare and hash equal. The last two
classes match the evens in count and endpoints and differ only past the
first leaf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 17:19:34 -05:00
Joseph CursioandClaude Opus 5.5 973218da0a Check SortedSet's BidirectionalCollection conformance
SortedSet conforms to BidirectionalCollection but was never run through
checkBidirectionalCollection. The counts sit on either side of the sizes
where a debug-build tree gains a level, and each is checked both
bulk-built and built by insertion, since the two give differently shaped
trees.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 17:19:26 -05:00
Hashim1999164 1efcb6cabd Fix inverted equality in SortedDictionary Keys, Values, and SubSequence.
Equality comparisons returned false for matching elements and true for mismatches. Correct the comparisons and add coverage for the affected views.
2026-08-02 22:52:49 +05:00
Franz Busch 3c373b900c Use the defines from traits directly
Package traits already pass defines with their trait name when building. Instead of adding our own conditional defines based on the traits we can use the trait provided defines directly. I observed that various tooling behaves better with the trait provided defines.
2026-05-06 07:41:02 -07:00
Karoy LorenteyandClaude Sonnet 4.6 6498b67816 [SortedCollections] SortedSet: Add value-range subscripts for ClosedRange and partial ranges
The Range<Element> subscript covers half-open intervals.  Add four
concrete overloads so callers can also write set[lo...hi], set[lo...],
set[..<hi], and set[...hi] — covering every stdlib RangeExpression
type that makes sense for a sorted set.

A single generic subscript<R: RangeExpression> would have been nicer,
but RangeExpression only exposes bounds via relative(to:), which needs
a Collection with Index == Bound.  Element is Comparable but not an
index of any collection we have, so the generic path doesn't work for
arbitrary Element types.  Five overloads it is.

The inclusive-upper variants (ClosedRange, PartialRangeThrough) use a
private _firstTreeIndex(after:) helper that returns the first
_BTree.Index strictly greater than a given element (or endIndex) —
the same logic as the public firstIndex(after:), but returning a
_Tree.Index directly for internal use.

Tests probe every lo/hi pair using a set of even numbers, so each
query exercises both "hits a member" and "falls between members"
cases, plus bounds that extend past each end of the set.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 18:10:22 -07:00
Karoy LorenteyandClaude Sonnet 4.6 64881e9cb4 [SortedCollections] SortedSet: Add firstIndex(after:) and lastIndex(before:)
The Range<Element> subscript covers half-open intervals, and with
partial-range support it would compose into ceiling/floor/lower (first
>= x, last <= x, last < x).  The strict upper bound "first element > x"
(Java's higher(_:)) can't be expressed as a range for arbitrary
Comparable types because Comparable has no successor operation, so
expose it — together with the symmetric strict lower bound — as
first-class operations.

Both are built on _BTree.startIndex(forKey:), which already returns the
first element >= the given key:
  - firstIndex(after: x) advances past that index if the element there
    equals x.
  - lastIndex(before: x) steps back one index, or returns nil if the
    lookup landed at startIndex.

Add test_firstIndexAfter and test_lastIndexBefore, covering queries
that hit an element, queries that fall between elements, and out-of-
range queries on both ends.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 17:59:18 -07:00
Karoy LorenteyandClaude Sonnet 4.6 e8b92d9f27 [SortedCollections] _BTree.lastIndex(forKey:): Fix offset and missing leftmost-child descent
Two bugs in the non-leaf path, symmetric to the ones recently fixed in
_BTree.startIndex(forKey:):

1. Offset was short by 1 when recursing into child[slot+1].  After
   computing the position of elem[slot] and saving it as the fallback
   offset, the recursion was entered with that same offset — but
   child[slot+1] starts one past elem[slot] in sorted order, so every
   element found deeper got an offset that was too small by 1.  Fix:
   build the elem[slot] offset with an exclusive loop, save it, then
   advance offset by 1 before descending.

2. When endSlot returns 0 (every element at this node is > key), the
   function returned nil instead of descending into child[0], which may
   still contain elements <= key.  This mirrors the rightmost-child
   descent case we added to startIndex(forKey:).

lastIndex(forKey:) currently has no callers, but is @inlinable internal
and clearly intended for use; leaving the latent bugs in place would
just burn the next caller.

Add test_lastIndexForKey to BTree Tests, verifying the offset returned
for every key in trees of various sizes, plus the "key smaller than
every element" edge case which exercises the leftmost-descent path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 17:30:06 -07:00
Karoy LorenteyandClaude Sonnet 4.6 8f2e4bba20 [SortedCollections] _Node.UnsafeHandle.concatenateWith: Fix children buffer corruption in simple-merge path
When two same-depth internal nodes plus a separator fit in a single
node, `concatenateWith` takes the simple-merge branch.  The non-leaf
subbranch was calling `moveInitializeElements` to move children, but
that method operates on the keys/values buffers, not the children
buffer.  The consequences:

- The re-read from `rightHandle.keys[0..<childCount]` hits slots that
  were already moved-out by the preceding `moveInitializeElements`
  call, which is UB.
- Writes land on top of keys just written by that same prior call,
  corrupting them.
- `self.children` is left with its original (too few) children plus
  uninitialized slots; subsequent traversal dereferences garbage.
- `rightHandle.drop()` deallocates the children buffer without
  transferring ownership, leaking the `_Node.Storage` references.

Fix: call `moveInitializeChildren` instead, matching the splinter
branch just above.

Add `test_join_nonLeafSimpleMerge`, which builds two depth-1 internal
nodes whose combined element count fits in capacity 4 and joins them
via `_Node.join`.  Without the fix the resulting tree's children are
undefined, so iteration either crashes or yields garbage.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 17:14:21 -07:00
Karoy LorenteyandClaude Sonnet 4.6 dd44e73a1b [SortedCollections] _BTree.startIndex(forKey:): Fix missing slot offset in non-leaf fallback
When the key was found at slot k of an internal node but an earlier
occurrence was sought in the child subtree and not found, the fallback
path returned the internal-node element's position.  The absolute offset
formula for element[k] in a non-leaf node is:

  ancestors + sum(subtreeCount[0..k]) + k

The `+ k` (slot) term was omitted, so the returned index carried the
wrong offset for any key that lives at slot > 0 of an internal node.

Add test_startIndexForKey (BTree Tests) to verify the offset for every
key in trees of several sizes, and test_rangeSubscript (SortedSet Tests)
to exercise the SortedSet[range] subscript which depends on this method.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 15:58:40 -07:00
Karoy Lorentey 1c69635852 Add SPDX-License-Identifier tags 2026-03-05 19:39:24 -08:00
Karoy Lorentey d9b09ecde8 Update copyright dates 2026-03-05 19:39:20 -08:00
Karoy Lorentey ab649ca5fc Add new package trait UnstableSortedCollections
This re-enables the SortedCollections for easi(er) experimentation.

The module remains source unstable — it may go away entirely or it may receive arbitrary source-breaking changes in any new swift-collections release, with no special pre-announcement.
2025-10-02 17:00:32 -07:00
Karoy Lorentey b5fc030a8e Merge pull request #508 from lorentey/container-previews-1
First round of noncopyable constructs: `Box`, `RigidArray`, `DynamicArray`
2025-08-29 18:23:24 -07:00
Karoy Lorentey dc55a17401 Merge pull request #507 from viere1234/patch
[SortedCollections] Fix B-tree root reduction during element removal causing data loss
2025-08-17 21:32:30 -07:00
Karoy Lorentey 54c65310f4 Adopt #filePath in test assertions 2025-08-17 13:23:00 -07:00
Brian Chang 21757b6add [BTree] Fix root reduction during element removal causing data loss
When removing elements from a B-tree, the root node could become empty while still having children. The previous code incorrectly called drop() which deallocated all children, causing massive data loss during removal operations.

This fix implements proper root reduction by moving the single remaining child out of the empty root, then safely dropping the now-empty parent node and promoting the extracted child to become the new root.

This fixes `test_modifySubscriptRemoval` in `SortedDictionaryTests`, so we re-enable SortedDictionary tests which now all pass.
2025-08-15 23:21:22 +08:00
Brian Chang 4ea19dd03e [SortedSet] Add test case for indexOf 2025-08-13 13:47:48 +08:00
Brian Chang a98fbaba8b [SortedSet] Fix subtreeCount inconsistency after remove at index
Previously, when removing an element from a child node, the subtreeCount
of the current internal node wasn't updated, leading to incorrect counts.
2025-08-01 22:45:17 +08:00
Dimitris Apostolou ab744afc39 Fix typos 2024-02-04 20:35:42 +02:00
Filip Klembara c623860624 Add tests for clearing btree using removeLast 2024-01-04 08:49:28 +01:00
Filip Klembara 9f3cced986 Add tests for clearing btree using removeFirst 2024-01-04 08:49:04 +01:00
Karoy Lorentey 4448454fbc [SortedCollections] Disable tests with @testable imports in release builds 2022-10-31 14:02:30 -07:00
Karoy Lorentey 4c4154ca23 [SortedCollections] Just disable SortedDictionary tests for now 2022-09-19 21:10:36 -07:00
Károly Lőrentey 8df65118eb Merge branch 'main' into feature/SortedCollections
# Conflicts:
#	.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme
#	.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-benchmark.xcscheme
#	Benchmarks/Benchmarks/CppBenchmarks.swift
2021-11-22 15:17:41 -08:00
Vihan Bhargava 62adcfad06 Add exhaustive SortedSet tests and benchmarks.
Key Changes:
 - Add tests and benchmarks for SortedSet
 - Fix bug during _Node.UnsafeHandle.popFirstElement() rebalancing
 - Enable _Node.UnsafeHandle.subscript(elementAt:) to work on value-less nodes.

Minor Changes:
 - Optimize Codable to use _BTree.Builder and forEach
 - Codable now checks for order, not strictly uniqueness
 - Add smaller node size for debug builds to easily catch errors
2021-08-20 00:45:58 -07:00
Vihan Bhargava e67460c942 Finish builder and
Key Changes:
 - Implement Equatable, Hashable for SubSequences
 - Implement SortedDictionary initializers
   - init(keysWithValues:) and init(sortedKeysAndValues:) with named and unnamed variants.
 - Expand benchmark suite for SortedDictionary
 - Commit _BTree.Builder

Minor Changes:
 - Update documentation
 - Expand test suits
 - Fix bug where SubSequences did not define subscript(bounds: Range<Index>)
 - _Node
   - Implement `depth` property for `_Node`
     - Packs both `depth`, `count`, and `capacity` within a single UInt64.
   - Implement `init(leftChild:seperator:rightChild:capacity:)` for `_Node`
   - Implement `concatenateWith(node:seperatedBy:)` to `_Node.UnsafeHandle`
   - Remove bad invariant check on `_Node.UnsafeHandle` deletion subroutines
 - _BTree
   - Add invariant checks as `_BTree.checkInvariants()`
   - Separate `_BTree.*capacity` into `*size` and `*capacity`
 - Make _FixedSizeArray top-level
   - Remove deque behavior.

Documentation:
 - Update complexity documentation style from 'n' to `self.count`

Testing:
 - Expand tests for SortedDictionary
 - Add tests for SortedDictionary.Keys
 - Add tests for _Node.join(...) routines
 - Add tests for _BTree.Builder
 - Restore checkBidirectionalCollection tests for _BTree
2021-08-15 00:22:39 -07:00
Vihan Bhargava 0d0d66f671 Documentation refactors, polishes, and add SubSequences
Key Changes:
 - Add custom SubSequences
 - Custom SortedDictionary.(Keys|Values).Sequence iterator
 - Add SortedDictionary.modifyValue(forKey:default:_:)

Minor Changes:
 - Update documentation
 - Various API optimizations
 - Fix bug where offsetBy:limitedBy: calls did not validate indices
 - Remove unique initializers with documented duplicate handling behavior.
 - Implement _Node.UnsafeHandle.append*() methods
 - SortedSet no longer allocates a 'values' buffer (_Node.Header.values is now optional)

Documentation:
 - Complexity guarantees
   - BidirectionalCollection conformances
   - Sequence/IteratorProtocol methods

Optimizations:
 - Add optimized dictionary value mapping (through Node.init(mappingFrom:_:))
 - Custom _BTree.forEach
 - Greater explicit @inline(__always) annotations throughout.
 - Simplify _BTree: Sequence implementation
 - Move methods to using _BTree.Builder
 - _BTree.FixedSizeArray now uses `withUnsafePointer` to prevent branching.
2021-08-09 19:14:19 -07:00
Vihan Bhargava 21d9bde3ec Add cursor tests and set iterator.
Major Changes:
 - Implement Sequence for SortedSet

Minor Changes:
 - Fix bug within _Node.UnsafeHandle.pointerToChild(atSlot:)
 - Cleanup cursor implementation and fix bugs.
 - Fix various bugs in _BTree.FixedSizeArray
2021-08-09 19:14:19 -07:00
Vihan Bhargava 5690056991 Add cursor type for imperative tree modification.
Key Changes:
 - Implement _BTree.Cursor for performing efficient mutations on a tree

Minor Changes:
 - New implementation of _BTree.Index and iteration
2021-08-09 19:13:50 -07:00