Commit Graph
41 Commits
Author SHA1 Message Date
Your NameandClaude Opus 4.8 259b4d52c2 Fix @inlinable deinit incompatibility with library evolution
The `Storage` classes in HashTreeCollections and SortedCollections mark
their `deinit` as `@inlinable` but lack `@_fixed_layout`. Under library
evolution (BUILD_LIBRARY_FOR_DISTRIBUTION=YES), Swift 6.2+ rejects this
with "deinitializer can only be '@inlinable' if the class is
'@_fixed_layout'", because inlining a deinit requires a known layout that
resilient mode deliberately hides.

This mirrors the existing fix already applied to the equivalent storage
classes in DequeModule (_DequeBuffer) and RopeModule (Rope._Storage). As
noted there, this does not make anything ABI stable -- these storage
classes are @usableFromInline internal and never part of the public ABI
surface -- it only lets these modules build with library evolution
enabled.

Fixes #676.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-29 16:15:00 +05:30
Aditya Singh ce67d512d5 [SortedCollections] Fix _BTree default node capacity capping at 16
The defaultInternalCapacity and defaultLeafCapacity computations used
Swift.min(16, capacityInBytes / MemoryLayout<Key>.stride), which capped
the node capacity at 16 regardless of element size. This defeated the
byte-budget intent: small elements should yield larger nodes, not be
clamped to 16. Use Swift.max instead so 16 acts as a floor and the
byte budget governs the upper bound, as confirmed by the maintainer
in issue #257.

Fixes #257
2026-05-29 00:52:15 -07: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 fb65ce5c6e [SortedCollections] _BTree.startIndex(forKey:): Fix offset accumulation and missing rightmost-child descent
Two bugs in the non-leaf path:

1. The loop used `for i in 0...slot` (inclusive), which added child[slot]'s
   subtreeCount to `offset` *before* recursing into child[slot].  This made
   the recursion start from elem[slot]'s position rather than child[slot]'s
   start, so every element found inside child[slot] carried an offset that
   was too large by subtreeCount[slot].  Fix: use `0..<slot` for the pre-
   recursion accumulation and read child[slot]'s subtreeCount separately only
   when computing the fallback `elemOffset`.

2. When startSlot returns elementCount (key is greater than every element in
   the node), the old code returned nil, silently failing to find any element
   >= key that lives in the rightmost child subtree.  Fix: descend into
   child[elementCount] in that case, mirroring how findAnyIndex handles it.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 16:44:35 -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 LorenteyandClaude Sonnet 4.6 2bbcb92987 [SortedCollections] _BTree.lastIndex(forKey:): Fix off-by-one guard and missing slot offset
The guard `slot > 0` incorrectly excluded `slot == 0`, causing the function
to return `endIndex` whenever the matching element was at position 0 of any
node. Changed to `slot >= 0`.

The non-leaf fallback was also missing `offset += slot`, matching the same
bug that exists symmetrically in startIndex(forKey:). The absolute offset
of element[k] in a non-leaf node is ancestors + sum(subtreeCount[0..k]) + k;
the `+k` term was absent.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-01 15:48:15 -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
Nate Cook 54ca53612f Include notes about index mutation in span(after/before:)
The indexes passed to span(after:) and friends on UniqueArray
and RigidArray are modified before return. This adds notes
about the updated values to the method documentation, along
with a few other minor formatting changes (dropping smart
quotes, single-sentence abstracts).
2026-03-02 16:38:48 -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 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
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 e0b68624ba [BTree] Fix incorrect offset calculation in findAnyIndex
`findAnyIndex(forKey:)` miscomputed the global offset when a key was found in an internal B-tree node, due to missing child subtree counts in the calculation.
2025-08-13 13:43:18 +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
Tony Parker c883a1729a Add support for embedded Swift mode
Remove calls to `debugPrint` (which does not exist), and ifdef out support for `Codable` and `Reflection`.
2025-07-17 16:36:56 -07:00
Karoy Lorentey d4946c5dcb Remove obsolete language checks 2025-05-20 15:12:32 -07:00
Karoy Lorentey 84087c786e [BTree] Rephrase some comments 2024-10-21 11:03:33 -07:00
Dimitris Apostolou ab744afc39 Fix typos 2024-02-04 20:35:42 +02:00
Filip Klembara 258df07928 Replace less then with less then or equal in removeLast(_:) and removeFirst (_BTree) 2024-01-04 09:05:27 +01:00
Karoy Lorentey 9b7c6ecb10 [SortedDictionary] SortedDictionary, .Iterator, .Index, .SubSequence, .SubSequence.Iterator, .Keys, .Keys.Iterator, .Values, .Values.Iterator: Explicitly conform to Sendable when Key and Value are both Sendable 2022-10-05 11:51:19 -07:00
Karoy Lorentey 58f7cf5a92 [SortedSet] SortedSet, .Iterator, .Index, .SubSequence, .SubSequence.Iterator: Explicitly conform to Sendable when Element is Sendable 2022-10-05 11:48:54 -07:00
Károly Lőrentey 8b1436f928 [SortedSet] Add missing range subscript 2021-11-22 15:35:02 -08:00
Vihan Bhargava 478d3cc73f Update swift-collections-benchmark scheme.
Signed-off-by: Vihan Bhargava <vihan_bhargava@apple.com>
2021-08-21 01:47:18 -07: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 cf672265c7 Final touch up, polishes, and optimizations.
Key Changes:
 - Add duplicate handling functionality to _BTree.Builder
 - Remove transient allocation in SortedDictionary.values _modify
 - Add missing SortedDictionary.Values.subscript _modify
 - Add SortedSet(sortedElements:)
 - Add optimized SetAlgebra implementations
 - Remove remaining high-level offset APIs
 - Various optimizations
 - Expand internal documentation

Minor Changes:
 - Add ability to create dummy node
 - _BTree.Builder.append(key: Key) for sets.
 - Fix bug where findAnyIndex(forKey:) didn't calculate the offset.
 - Remove old, unused files
 - findAnyCursor -> takeCursor (to emphasize consuming nature)
 - Add takeCursor(at: Index)
 - Optimize init(grouping:by:) to use modifyValue to reduce CoW

Optimizations:
 - Use dummy node for transient _modify state rather than allocating new buffer
2021-08-19 00:02:17 -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
Vihan Bhargava 9b470c8f92 Initial implementation of SetAlgebra and various refactors.
Key Changes:
 - SortedSet
   - Implement SetAlgebra
   - Implement Hashable
   - Implement Equatable
   - Implement Custom(Debug)StringConvertible
   - Implement CustomReflectable
   - Implement Codable
   - Implement subscript(range: Range<Element>)
   - Implement subscript(offset:)
   - Implement remove(atOffset:)

Minor Changes:
 - Fix inefficiency on SortedDictionary.customMirror
 - Optimize to O(1) _BTree.UnsafePath comparator
 - Optimize away ARC traffic on findAnyPath(forKey:)

Various additional refactors and renames.
2021-08-09 19:13:50 -07:00
Vihan Bhargava 98f278545d Continue applying refactors and optimizations.
Key Changes:
 - _BTree.init() dynamically computes capacity from stride
 - _BTree.UnsafePath uses Unmanaged +0 references.

Minor Changes:
 - Fix _BTree.Iterator bug on single-leaf trees.
2021-08-09 19:13:50 -07:00
Vihan Bhargava 8de0b4ff7a Implement primary SortedSet methods and various refactors.
Key Changes:
 - SortedSet
   - Implement Partial RangeReplaceableCollection
   - Implement ExpressibleByArrayLiteral
   - Implement init<S: Sequence>(_: S)
   - Implement Set methods:
     - update(with:) / insert(_:) / contains(_:)
 - SortedDictionary
   - Implement SortedDictionary.Values: BidirectionalCollection
   - Implement SortedDictionary.Keys: BidirectionalCollection
 - _BTree
   - Implement Partial RangeReplaceableCollection
   - Implement Sequence
     - Add high performance linear iterator

Minor Changes:
 - Benchmarks
   - Clean up benchmarks
 - _Node.UnsafeHandle
   - @freeze enum InsertionResult
 - _Node.Storage
   - Use UnsafeMutablePointer instead of ManagedBuffer

Refactors:
 - Various refactors for method signatures and documentation.
2021-08-09 19:13:50 -07:00
Vihan Bhargava 761950dad8 Implement and use PackedOffsetList for UnsafePath
Using an array was very heavy, now using a stack-allocated 64-byte wide
type which mimics an array.
2021-08-09 19:13:50 -07:00
Vihan Bhargava 817c97a403 Implement initial SortedDictionary API and implementations for SortedSet.
Key Changes:
 - SortedSet
   - Implement BidirectionalCollection
 - SortedDictionary
   - Implement Codable
   - Implement Partial RangeReplaceableCollection
     - Includes remove*() operations
   - init(grouping:by:)
   - var keys: Keys (aka SortedSet<Key>)
   - func (compact)mapValues(_:)

Minor Changes:
 - Correct time documented complexities of various methods
 - Implement more variations of removal methods.
2021-08-09 19:13:50 -07:00
Vihan Bhargava 3d5d5acb5b Implement B-Tree deletion and respective tests.
Key Changes:
 - Implement removal through SortedDictionary subscript
 - Implement _BTree.contains for efficient existence checking
 - Add tests
   - _Node.UnsafeHandle.rotation/collapse tests
   - _BTree.removeAny tests
 - Expand benchmarks
   - Add C++ reference lookup benchmarks
   - Correct old benchmarks

Minor Changes:
 - Remove B-Tree benchmarks, correct SortedDictionary benchmarks
 - Adjust debug B-Tree printer to show both numElements and numTotalElements
 - Add total count synchronization invariant check
 - Implement CustomReflectable for B-Tree
2021-08-09 19:13:50 -07:00
Vihan Bhargava 821e3e3a0a Add implementation of deficiency handling algorithms for removals.
Key Changes:
 - Implement deficiency correction methods
 - Remove inlining from _Node.ensureUnique to better inline closures
 - Add new computed properties to _Node.UnsafeHandle

Minor changes
 - Added missing mutability checks to certain _Node.UnsafeHandle methods
 - Remove unneeded _Node.UnsafeHandle.findValue(key:) method
 - Allow _Node.UnsafeHandle.removeElement(at:) to be called on non-leaves
 - Expand doc comments and fix typos
2021-08-09 19:13:50 -07:00
Vihan Bhargava 9cf2cdadc0 Initial commit for SortedCollections
Signed-off-by: Vihan Bhargava <vihan_bhargava@apple.com>
2021-08-09 19:13:41 -07:00