From 98f278545dec9ba9ee78d07ca05eca382e65d3ce Mon Sep 17 00:00:00 2001 From: Vihan Bhargava Date: Sun, 18 Jul 2021 02:18:48 -0700 Subject: [PATCH] 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. --- .../_BTree+BidirectionalCollection.swift | 13 +-- ...e+Partial RangeReplaceableCollection.swift | 38 +++------ .../BTree/_BTree+Sequence.swift | 20 ++++- .../BTree/_BTree.Index.swift | 6 +- .../BTree/_BTree.PackedList.swift | 18 +++-- .../BTree/_BTree.UnsafePath.swift | 18 +++-- Sources/SortedCollections/BTree/_BTree.swift | 80 ++++++++++++------- .../BTree/_Node.Buffer.swift | 24 ------ .../BTree/_Node.Splinter.swift | 4 +- .../BTree/_Node.Storage.swift | 4 +- .../BTree/_Node.UnsafeHandle+Deletion.swift | 29 +++---- .../BTree/_Node.UnsafeHandle+Insertion.swift | 23 ++++-- .../BTree/_Node.UnsafeHandle.swift | 25 +++--- Sources/SortedCollections/BTree/_Node.swift | 4 +- .../SortedDictionary+Initializers.swift | 8 +- .../SortedDictionary+Subscripts.swift | 2 +- .../SortedDictionary/SortedDictionary.swift | 2 +- .../SortedSet/SortedSet+Initializers.swift | 2 +- .../SortedSet/SortedSet.swift | 4 +- .../BTree/BTree+Deletion Tests.swift | 4 +- .../BTree/BTreeTests.swift | 4 +- .../BTree/Node Utils.swift | 2 +- .../BTree/Node+Balancing Tests.swift | 30 +++---- .../BTree/Node+Insertion Tests.swift | 2 +- .../BTree/NodeTests.swift | 8 +- 25 files changed, 195 insertions(+), 179 deletions(-) delete mode 100644 Sources/SortedCollections/BTree/_Node.Buffer.swift diff --git a/Sources/SortedCollections/BTree/_BTree+BidirectionalCollection.swift b/Sources/SortedCollections/BTree/_BTree+BidirectionalCollection.swift index e5a91dcb..77e3b8b3 100644 --- a/Sources/SortedCollections/BTree/_BTree+BidirectionalCollection.swift +++ b/Sources/SortedCollections/BTree/_BTree+BidirectionalCollection.swift @@ -14,7 +14,7 @@ extension _BTree: BidirectionalCollection { /// - Complexity: O(1) @inlinable @inline(__always) - internal var count: Int { self.root.storage.header.totalElements } + internal var count: Int { self.root.storage.header.subtreeCount } /// A Boolean value that indicates whether the BTree is empty. @inlinable @@ -61,7 +61,8 @@ extension _BTree: BidirectionalCollection { /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If end is equal to start, the result is zero. - /// - Returns: The distance between start and end. The result can be negative only if the collection conforms to the BidirectionalCollection protocol. + /// - Returns: The distance between start and end. The result can be negative only if the collection + /// conforms to the BidirectionalCollection protocol. /// - Complexity: O(1) @inlinable internal func distance(from start: Index, to end: Index) -> Int { @@ -77,9 +78,9 @@ extension _BTree: BidirectionalCollection { preconditionFailure("Attempt to advance out of collection bounds.") } - let shouldSeekWithinLeaf = Node(path.node).read({ + let shouldSeekWithinLeaf = path.readNode { $0.isLeaf && _fastPath(path.slot + 1 < $0.elementCount) - }) + } if shouldSeekWithinLeaf { // Continue searching within the same leaf @@ -143,10 +144,10 @@ extension _BTree: BidirectionalCollection { // TODO: optimization for searching within children - if var path = i.path, path.node.header.children == nil { + if var path = i.path, path.readNode({ $0.isLeaf }) { // Check if the target element will be in the same node let targetSlot = path.slot + distance - if 0 <= targetSlot && targetSlot < path.node.header.count { + if 0 <= targetSlot && targetSlot < path.readNode({ $0.elementCount }) { path.slot = targetSlot path.offset = newIndex i.path = path diff --git a/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift b/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift index e35406ab..6e880b95 100644 --- a/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift +++ b/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift @@ -22,7 +22,7 @@ extension _BTree { // TODO: optimize implementation to O(n) var newTree: _BTree = _BTree() for element in self where try isIncluded(element) { - newTree.setAnyValue(element.value, forKey: element.key) + newTree.updateAnyValue(element.value, forKey: element.key) } return newTree } @@ -102,29 +102,6 @@ extension _BTree { } } - // MARK: Offset Removal - /// Removes the element of a tree at a given offset. - /// - /// - Parameter offset: the offset which must be in-bounds. - /// - Returns: The moved element of the tree - @inlinable - @inline(__always) - @discardableResult - internal mutating func remove(at offset: Int) -> Element { - invalidateIndices() - let removedElement = self.root.update { $0.remove(at: offset) } - self._balanceRoot() - return removedElement - } - - @inlinable - @inline(__always) - internal mutating func removeAll() { - invalidateIndices() - // TODO: potentially use empty storage class. - self.root = _Node(withCapacity: _BTree.defaultLeafCapacity, isLeaf: true) - } - // MARK: Index Removal /// Removes the element of a tree at a given index. /// @@ -136,7 +113,16 @@ extension _BTree { internal mutating func remove(at index: Index) -> Element { invalidateIndices() guard let path = index.path else { preconditionFailure("Index out of bounds.") } - return self.remove(at: path.offset) + return self.remove(atOffset: path.offset) + } + + // MARK: Bulk Removal + @inlinable + @inline(__always) + internal mutating func removeAll() { + invalidateIndices() + // TODO: potentially use empty storage class. + self.root = _Node(withCapacity: _BTree.defaultLeafCapacity, isLeaf: true) } /// Removes the elements in the specified subrange from the collection. @@ -149,7 +135,7 @@ extension _BTree { let startOffset = startPath.offset for _ in 0.. Element? { + // Check slot sentinel value for end of tree. if _slowPath(self.slot == -1) { return nil } @@ -63,11 +71,13 @@ extension _BTree: Sequence { if !handle.isLeaf { self.parents.append(self.currentNode) self.offsets.append(UInt16(self.slot + 1)) + + // TODO: make these descents Unmanaged var node = handle[childAt: self.slot + 1] while !node.read({ $0.isLeaf }) { - self.offsets.append(0) self.parents.append(.passUnretained(node.storage)) + self.offsets.append(0) node = node.read({ $0[childAt: 0] }) } @@ -78,6 +88,11 @@ extension _BTree: Sequence { self.slot += 1 } else { while true { + if self.parents.depth == 0 { + self.slot = -1 + break + } + // If we are at a leaf, then ascend to the let parent = self.parents.pop() let offset = self.offsets.pop() @@ -88,9 +103,6 @@ extension _BTree: Sequence { self.currentNode = parent self.slot = Int(offset) break - } else if self.parents.depth == 0 { - self.slot = -1 - break } } } diff --git a/Sources/SortedCollections/BTree/_BTree.Index.swift b/Sources/SortedCollections/BTree/_BTree.Index.swift index 99dd3f81..1a647f5c 100644 --- a/Sources/SortedCollections/BTree/_BTree.Index.swift +++ b/Sources/SortedCollections/BTree/_BTree.Index.swift @@ -41,7 +41,7 @@ extension _BTree { @inlinable @inline(__always) internal static func ==(lhs: Index, rhs: Index) -> Bool { - return lhs.path?.node === rhs.path?.node + return lhs.path?.offset == rhs.path?.offset } @inlinable @@ -73,7 +73,9 @@ extension _BTree { @inline(__always) internal func ensureValid(with index: Index) { precondition( - self.root != nil && self.root === index.root && self.version == index.version, + self.root != nil && + self.root === index.root && + self.version == index.version, "Attempt to use an invalid indices.") } } diff --git a/Sources/SortedCollections/BTree/_BTree.PackedList.swift b/Sources/SortedCollections/BTree/_BTree.PackedList.swift index 40983c7d..296987bf 100644 --- a/Sources/SortedCollections/BTree/_BTree.PackedList.swift +++ b/Sources/SortedCollections/BTree/_BTree.PackedList.swift @@ -9,15 +9,17 @@ // //===----------------------------------------------------------------------===// -@usableFromInline -internal let _PACKED_OFFSET_LIST_MAX_SIZE = 16 - extension _BTree { /// A stack-allocated list of some values. + /// /// - Warning: This may hold strong references to objects after they /// do not put non-trivial types in this. @usableFromInline internal struct FixedSizeArray { + @inlinable + @inline(__always) + internal static var maxSize: UInt8 { 16 } + @usableFromInline internal var depth: UInt8 @@ -45,7 +47,8 @@ extension _BTree { @inlinable @inline(__always) internal mutating func append(_ offset: Value) { - assert(depth < _PACKED_OFFSET_LIST_MAX_SIZE, "Out of bounds access in offset list.") + assert(depth < FixedSizeArray.maxSize, + "Out of bounds access in offset list.") self.depth &+= 1 self[self.depth] = offset } @@ -63,7 +66,8 @@ extension _BTree { @inline(__always) internal subscript(_ offset: UInt8) -> Value { get { - assert(offset <= depth && depth <= _PACKED_OFFSET_LIST_MAX_SIZE, "Out of bounds access in offset list.") + assert(offset <= depth && depth <= FixedSizeArray.maxSize, + "Out of bounds access in offset list.") switch offset { case 0: return self.values.0 @@ -87,7 +91,9 @@ extension _BTree { } _modify { - assert(offset <= depth && depth <= _PACKED_OFFSET_LIST_MAX_SIZE, "Out of bounds access in offset list.") + assert(offset <= depth && depth <= FixedSizeArray.maxSize, + "Out of bounds access in offset list.") + switch offset { case 0: yield &self.values.0 case 1: yield &self.values.1 diff --git a/Sources/SortedCollections/BTree/_BTree.UnsafePath.swift b/Sources/SortedCollections/BTree/_BTree.UnsafePath.swift index 8812a5b4..0396aa81 100644 --- a/Sources/SortedCollections/BTree/_BTree.UnsafePath.swift +++ b/Sources/SortedCollections/BTree/_BTree.UnsafePath.swift @@ -28,9 +28,8 @@ extension _BTree { @usableFromInline internal var childSlots: Offsets - // TODO: switch to Unmanaged @usableFromInline - internal unowned(unsafe) var node: Node.Storage + internal var node: Unmanaged @usableFromInline internal var slot: Int @@ -85,7 +84,7 @@ extension _BTree { childSlots: Offsets, offset: Int ) { - self.node = node + self.node = .passUnretained(node) self.slot = slot self.childSlots = childSlots self.offset = offset @@ -97,7 +96,16 @@ extension _BTree { @inlinable @inline(__always) internal var element: Element { - return Node(self.node).read { $0[elementAt: self.slot] } + return self.readNode { $0[elementAt: self.slot] } + } + + /// Operators on a handle of the node + @inlinable + @inline(__always) + internal func readNode( + _ body: (Node.UnsafeHandle) throws -> R + ) rethrows -> R { + return try self.node._withUnsafeGuaranteedRef { try $0.read(body) } } } } @@ -110,7 +118,7 @@ extension _BTree.UnsafePath: Equatable { @inlinable public static func ==(lhs: _BTree.UnsafePath, rhs: _BTree.UnsafePath) -> Bool { // We assume the parents are the same - return lhs.node === rhs.node && lhs.slot == rhs.slot + return lhs.node.toOpaque() == rhs.node.toOpaque() && lhs.slot == rhs.slot } } diff --git a/Sources/SortedCollections/BTree/_BTree.swift b/Sources/SortedCollections/BTree/_BTree.swift index ff104e81..e9eb9fda 100644 --- a/Sources/SortedCollections/BTree/_BTree.swift +++ b/Sources/SortedCollections/BTree/_BTree.swift @@ -25,12 +25,12 @@ internal struct _BTree { /// Internal node capacity for BTree @inlinable @inline(__always) - static internal var defaultInternalCapacity: Int { 16 } + static internal var defaultInternalCapacity: Int { 64 } /// Leaf node capacity for BTree @inlinable @inline(__always) - static internal var defaultLeafCapacity: Int { 500 } + static internal var defaultLeafCapacity: Int { 2000 } @usableFromInline internal typealias Element = (key: Key, value: Value) @@ -42,19 +42,35 @@ internal struct _BTree { @usableFromInline internal var root: Node - // TODO: remove - // TODO: compute capacity based on key/value size. /// The capacity of each of the internal nodes @usableFromInline internal var internalCapacity: Int - /// A metric to uniquely identify a given BTree's state. It is not - /// impossible for two BTrees to have the same age by pure + /// A metric to uniquely identify a given B-Tree's state. It is not + /// impossible for two B-Trees to have the same age by pure /// coincidence. @usableFromInline internal var version: Int - /// Creates an empty BTree rooted at a specific node with a specified uniform capacity + /// Creates an empty B-Tree with an automatically determined optimal capacity. + @inlinable + @inline(__always) + internal init() { + let leafCapacity = Swift.min( + 16, + _BTree.defaultLeafCapacity / MemoryLayout.stride + ) + + let internalCapacity = Swift.min( + 16, + _BTree.defaultInternalCapacity / MemoryLayout.stride + ) + + let root = Node(withCapacity: leafCapacity, isLeaf: true) + self.init(rootedAt: root, internalCapacity: internalCapacity) + } + + /// Creates an empty B-Tree rooted at a specific node with a specified uniform capacity /// - Parameter capacity: The key capacity of all nodes. @inlinable @inline(__always) @@ -68,39 +84,24 @@ internal struct _BTree { /// Creates an empty BTree which creates node with specified capacities /// - Parameters: /// - leafCapacity: The capacity of the leaf nodes. This is the initial buffer used to allocate. - /// - internalCapacity: The capacity of the internal nodes. Generally prefered to be less than `leafCapacity`. + /// - internalCapacity: The capacity of the internal nodes. Generally prefered to be less than + /// `leafCapacity`. @inlinable @inline(__always) - internal init(leafCapacity: Int = defaultLeafCapacity, internalCapacity: Int = defaultInternalCapacity) { + internal init(leafCapacity: Int, internalCapacity: Int) { self.init( rootedAt: Node(withCapacity: leafCapacity, isLeaf: true), - leafCapacity: leafCapacity, internalCapacity: internalCapacity ) } - /// Creates a BTree rooted at a specific node with a specified uniform capacity + /// Creates a BTree rooted at a specific nodey /// - Parameters: /// - root: The root node. - /// - capacity: The key capacity of all nodes. + /// - internalCapacity: The key capacity of new internal nodes. @inlinable @inline(__always) - internal init(rootedAt root: Node, capacity: Int) { - self.init( - rootedAt: root, - leafCapacity: capacity, - internalCapacity: capacity - ) - } - - /// Creates a BTree rooted at a specific node. - /// - Parameters: - /// - root: The root node. - /// - leafCapacity: The capacity of the leaf nodes. This is the initial buffer used to allocate. - /// - internalCapacity: The capacity of the internal nodes. Generally prefered to be less than `leafCapacity`. - @inlinable - @inline(__always) - internal init(rootedAt root: Node, leafCapacity: Int = defaultLeafCapacity, internalCapacity: Int = defaultInternalCapacity) { + internal init(rootedAt root: Node, internalCapacity: Int) { self.root = root self.internalCapacity = internalCapacity self.version = ObjectIdentifier(root.storage).hashValue @@ -131,15 +132,14 @@ extension _BTree { /// - Complexity: O(`log n`) @inlinable @discardableResult - // updateAnyValue(_:forKey:) - internal mutating func setAnyValue( + internal mutating func updateAnyValue( _ value: Value, forKey key: Key, updatingKey: Bool = false ) -> Element? { invalidateIndices() - let result = self.root.update { $0.setAnyValue(value, forKey: key, updatingKey: updatingKey) } + let result = self.root.update { $0.updateAnyValue(value, forKey: key, updatingKey: updatingKey) } switch result { case let .updated(previousValue): return previousValue @@ -194,6 +194,24 @@ extension _BTree { } } +// MARK: Removal Opertations +extension _BTree { + /// Removes the element of a tree at a given offset. + /// + /// - Parameter offset: the offset which must be in-bounds. + /// - Returns: The moved element of the tree + @inlinable + @inline(__always) + @discardableResult + internal mutating func remove(atOffset offset: Int) -> Element { + invalidateIndices() + let removedElement = self.root.update { $0.remove(at: offset) } + self._balanceRoot() + + return removedElement + } +} + // MARK: Read Operations extension _BTree { /// Determines if a key exists within a tree. diff --git a/Sources/SortedCollections/BTree/_Node.Buffer.swift b/Sources/SortedCollections/BTree/_Node.Buffer.swift deleted file mode 100644 index 8b40b887..00000000 --- a/Sources/SortedCollections/BTree/_Node.Buffer.swift +++ /dev/null @@ -1,24 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021 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 -// -//===----------------------------------------------------------------------===// - -extension _Node { - @usableFromInline - internal struct BufferHeader { - @inlinable - @inline(__always) - internal init() {} - } - - /// Represents a contiguous sequence of elements. - /// - Warning: does not deallocate itself. - @usableFromInline - typealias Buffer = ManagedBuffer -} diff --git a/Sources/SortedCollections/BTree/_Node.Splinter.swift b/Sources/SortedCollections/BTree/_Node.Splinter.swift index 06a34da8..26f9f2a9 100644 --- a/Sources/SortedCollections/BTree/_Node.Splinter.swift +++ b/Sources/SortedCollections/BTree/_Node.Splinter.swift @@ -47,8 +47,8 @@ extension _Node { handle.elementCount = 1 handle.subtreeCount = 1 + - leftChild.storage.header.totalElements + - self.rightChild.storage.header.totalElements + leftChild.storage.header.subtreeCount + + self.rightChild.storage.header.subtreeCount } return newNode } diff --git a/Sources/SortedCollections/BTree/_Node.Storage.swift b/Sources/SortedCollections/BTree/_Node.Storage.swift index cca637e1..54c2daf3 100644 --- a/Sources/SortedCollections/BTree/_Node.Storage.swift +++ b/Sources/SortedCollections/BTree/_Node.Storage.swift @@ -24,7 +24,7 @@ extension _Node { self.count = count self.values = values self.children = children - self.totalElements = totalElements + self.subtreeCount = totalElements } @usableFromInline @@ -36,7 +36,7 @@ extension _Node { /// The total amount of elements contained underneath this node @usableFromInline - internal var totalElements: Int + internal var subtreeCount: Int /// Pointer to the buffer containing the corresponding values. @usableFromInline diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift index b0b579e3..1fe0fac9 100644 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift @@ -47,7 +47,7 @@ extension _Node.UnsafeHandle { // Balance the predecessor child slot, as the pop operation may have // brought it out of balance. - self.balance(at: slot) + self.balance(atSlot: slot) return element } @@ -77,7 +77,7 @@ extension _Node.UnsafeHandle { // extra memmove being performed. // Determine if the child needs to be rebalanced - self.balance(at: slot) + self.balance(atSlot: slot) return removedElement } @@ -124,7 +124,7 @@ extension _Node.UnsafeHandle { // Balance the predecessor child slot, as the pop operation may have // brought it out of balance. - self.balance(at: childSlot) + self.balance(atSlot: childSlot) return element } else { @@ -157,7 +157,7 @@ extension _Node.UnsafeHandle { self.subtreeCount -= 1 - self.balance(at: self.childCount - 1) + self.balance(atSlot: self.childCount - 1) return poppedElement } @@ -185,7 +185,7 @@ extension _Node.UnsafeHandle { self.subtreeCount -= 1 - self.balance(at: self.childCount - 1) + self.balance(atSlot: self.childCount - 1) return poppedElement } } @@ -203,8 +203,7 @@ extension _Node.UnsafeHandle { /// /// - Parameter slot: The slot containing the child to balance. @inlinable - // balance(atSlot slot:) - internal func balance(at slot: Int) { + internal func balance(atSlot slot: Int) { assertMutable() assert(0 <= slot && slot < self.childCount, "Cannot balance out-of-bounds slot.") @@ -215,18 +214,18 @@ extension _Node.UnsafeHandle { if slot > 0 && self[childAt: slot - 1].read({ $0.isShrinkable }) { // We can rotate from the left node to the right node - self.rotateRight(at: slot - 1) + self.rotateRight(atSlot: slot - 1) } else if slot < self.childCount - 1 && self[childAt: slot + 1].read({ $0.isShrinkable }) { // We can rotate from the right node to the left node - self.rotateLeft(at: slot) + self.rotateLeft(atSlot: slot) } else if slot == self.childCount - 1 { // In the special case the deficient child at the end, // it'll be merged with it's left sibling. - self.collapse(at: slot - 1) + self.collapse(atSlot: slot - 1) } else { // Otherwise collapse the child with its right sibling. - self.collapse(at: slot) + self.collapse(atSlot: slot) } } @@ -238,8 +237,7 @@ extension _Node.UnsafeHandle { /// - Parameter slot: The slot containing the child to balance. @inlinable @inline(__always) - // rotateRight(atSlot slot:) - internal func rotateRight(at slot: Int) { + internal func rotateRight(atSlot slot: Int) { assertMutable() assert(0 <= slot && slot < self.elementCount, "Cannot rotate out-of-bounds slot.") @@ -311,7 +309,7 @@ extension _Node.UnsafeHandle { /// - Parameter slot: The slot containing the child to balance. @inlinable @inline(__always) - internal func rotateLeft(at slot: Int) { + internal func rotateLeft(atSlot slot: Int) { assertMutable() assert(0 <= slot && slot < self.elementCount, "Cannot rotate out-of-bounds slot.") @@ -387,8 +385,7 @@ extension _Node.UnsafeHandle { /// - Warning: Calling this may result in empty nodes and a state which breaks the /// B-Tree invariants, ensure the tree is further balanced after this.` @inlinable - @inline(__always) - internal func collapse(at slot: Int) { + internal func collapse(atSlot slot: Int) { assertMutable() assert(0 <= slot && slot < self.elementCount, "Cannot collapse out-of-bounds slot") diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift index a36c04db..263b8289 100644 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift @@ -46,8 +46,11 @@ extension _Node.UnsafeHandle { /// - Returns: A representation of the possible results of the update/insertion. @inlinable @inline(__always) - // updateAnyValue(_ value:, forKey key:, updatingKey:) - internal func setAnyValue(_ value: Value, forKey key: Key, updatingKey: Bool) -> InsertionResult { + internal func updateAnyValue( + _ value: Value, + forKey key: Key, + updatingKey: Bool + ) -> InsertionResult { assertMutable() let insertionIndex = self.endSlot(forKey: key) @@ -63,7 +66,11 @@ extension _Node.UnsafeHandle { return .updated(previousElement: (oldKey, oldValue)) } else { - let oldElement = self.exchangeElement(atSlot: insertionIndex - 1, with: (key, value)) + let oldElement = self.exchangeElement( + atSlot: insertionIndex - 1, + with: (key, value) + ) + return .updated(previousElement: oldElement) } } @@ -78,14 +85,16 @@ extension _Node.UnsafeHandle { ) return InsertionResult(from: maybeSplinter) } else { - let result = self[childAt: insertionIndex].update { $0.setAnyValue(value, forKey: key, updatingKey: updatingKey) } + let result = self[childAt: insertionIndex].update { + $0.updateAnyValue(value, forKey: key, updatingKey: updatingKey) + } switch result { case .updated: return result case .splintered(let splinter): - let maybeSplinter = self.insertSplinter(splinter, atSlot: insertionIndex) - return InsertionResult(from: maybeSplinter) + let splinter = self.insertSplinter(splinter, atSlot: insertionIndex) + return InsertionResult(from: splinter) case .inserted: self.subtreeCount += 1 return .inserted @@ -317,7 +326,7 @@ extension _Node.UnsafeHandle { // TODO: potentially evaluate min(left.children, right.children), // but the cost of the branch will likely exceed the cost of 1 comparison for i in 0..= 0, "Node cannot have negative number of elements") - assert(subtreeCount >= elementCount, + assert(subtreeCount >= 0, "Node cannot have negative number of elements") + assert(subtreeCount >= subtreeCount, "Subtree count cannot be less than the node element count.") - if elementCount > 1 { - for i in 0..<(elementCount - 1) { + if subtreeCount > 1 { + for i in 0..<(subtreeCount - 1) { precondition(self[keyAt: i] <= self[keyAt: i + 1], "Node is out-of-order.") } } precondition( isLeaf || - subtreeCount == elementCount + (0...elementCount).reduce(into: 0, { $0 + self[childAt: $1].read({ $0.elementCount }) }), + subtreeCount == subtreeCount + + (0...subtreeCount).reduce(into: 0, { $0 + self[childAt: $1].read({ $0.subtreeCount }) }), "Total number of elements out of sync." ) if !isLeaf { - for i in 0..= key, "Right subtree must be greater than or equal to than its parent key.") // Ensure if one child is a leaf, then all children are leaves @@ -142,9 +143,9 @@ extension _Node { @inlinable @inline(__always) internal var subtreeCount: Int { - get { header.pointee.totalElements } + get { header.pointee.subtreeCount } nonmutating set { - assertMutable(); header.pointee.totalElements = newValue + assertMutable(); header.pointee.subtreeCount = newValue } } diff --git a/Sources/SortedCollections/BTree/_Node.swift b/Sources/SortedCollections/BTree/_Node.swift index aa50b52b..cd1f6e31 100644 --- a/Sources/SortedCollections/BTree/_Node.swift +++ b/Sources/SortedCollections/BTree/_Node.swift @@ -32,13 +32,13 @@ internal struct _Node { internal init(copyingFrom oldNode: _Node) { let capacity = oldNode.storage.header.capacity let count = oldNode.storage.header.count - let totalElements = oldNode.storage.header.totalElements + let totalElements = oldNode.storage.header.subtreeCount let isLeaf = oldNode.storage.header.children == nil self.init(withCapacity: capacity, isLeaf: isLeaf) self.storage.header.count = count - self.storage.header.totalElements = totalElements + self.storage.header.subtreeCount = totalElements oldNode.storage.withUnsafeMutablePointerToElements { oldKeys in self.storage.withUnsafeMutablePointerToElements { newKeys in diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift index 4093f108..8c5eb280 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift @@ -21,7 +21,7 @@ extension SortedDictionary { self.init() for (key, value) in keysAndValues { - self._root.setAnyValue(value, forKey: key) + self._root.updateAnyValue(value, forKey: key) } } @@ -40,7 +40,7 @@ extension SortedDictionary { // in debug v production v unchecked builds? for (key, value) in keysAndValues { - self._root.setAnyValue(value, forKey: key) + self._root.updateAnyValue(value, forKey: key) } } @@ -77,9 +77,9 @@ extension SortedDictionary { // TODO: optimize to avoid CoW copying the array if var group = self._root.findAnyValue(forKey: key) { group.append(value) - self._root.setAnyValue(group, forKey: key) + self._root.updateAnyValue(group, forKey: key) } else { - self._root.setAnyValue([value], forKey: key) + self._root.updateAnyValue([value], forKey: key) } } } diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift index 2289b171..320d21e2 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift @@ -33,7 +33,7 @@ extension SortedDictionary { set { if let newValue = newValue { - self._root.setAnyValue(newValue, forKey: key) + self._root.updateAnyValue(newValue, forKey: key) } else { self._root.removeAnyElement(forKey: key) } diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift index 1f9bda65..47e00324 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift @@ -95,7 +95,7 @@ extension SortedDictionary { @inlinable @discardableResult public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? { - self._root.setAnyValue(value, forKey: key)?.value + self._root.updateAnyValue(value, forKey: key)?.value } } diff --git a/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift b/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift index 81018a94..8524996a 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift @@ -20,7 +20,7 @@ extension SortedSet { self.init() for element in elements { - self._root.setAnyValue((), forKey: element) + self._root.updateAnyValue((), forKey: element) } } diff --git a/Sources/SortedCollections/SortedSet/SortedSet.swift b/Sources/SortedCollections/SortedSet/SortedSet.swift index f416b9f2..837a3f82 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet.swift @@ -63,7 +63,7 @@ extension SortedSet { public mutating func insert( _ newMember: Element ) -> (inserted: Bool, memberAfterInsert: Element) { - if let oldKey = self._root.setAnyValue((), forKey: newMember, updatingKey: false)?.key { + if let oldKey = self._root.updateAnyValue((), forKey: newMember, updatingKey: false)?.key { return (inserted: false, memberAfterInsert: oldKey) } else { return (inserted: true, memberAfterInsert: newMember) @@ -80,6 +80,6 @@ extension SortedSet { @inline(__always) @discardableResult public mutating func update(with newMember: Element) -> Element? { - return self._root.setAnyValue((), forKey: newMember, updatingKey: true)?.key + return self._root.updateAnyValue((), forKey: newMember, updatingKey: true)?.key } } diff --git a/Tests/SortedCollectionsTests/BTree/BTree+Deletion Tests.swift b/Tests/SortedCollectionsTests/BTree/BTree+Deletion Tests.swift index 0c2e3b48..12774de2 100644 --- a/Tests/SortedCollectionsTests/BTree/BTree+Deletion Tests.swift +++ b/Tests/SortedCollectionsTests/BTree/BTree+Deletion Tests.swift @@ -14,10 +14,10 @@ import CollectionsTestSupport final class NodeDeletionTests: CollectionTestCase { func test_singleDeletion() { - withEvery("size", in: [1, 2, 4, 8, 16, 32, 64, 128, 2000]) { size in + withEvery("size", in: [1, 2, 4, 8, 16, 32, 64, 128]) { size in withEvery("key", in: 0..(capacity: 2) var keyValues = [(key: Int, value: Int)]() for i in 0..() for (key, value) in kvs { - tree.setAnyValue(value, forKey: key) + tree.updateAnyValue(value, forKey: key) } } } diff --git a/Tests/SortedCollectionsTests/BTree/Node Utils.swift b/Tests/SortedCollectionsTests/BTree/Node Utils.swift index 3bd8237c..e3a72f8e 100644 --- a/Tests/SortedCollectionsTests/BTree/Node Utils.swift +++ b/Tests/SortedCollectionsTests/BTree/Node Utils.swift @@ -25,7 +25,7 @@ struct NodeTemplate { } func toBTree(ofCapacity capacity: Int) -> _BTree { - return _BTree(rootedAt: self.toNode(ofCapacity: capacity), capacity: capacity) + return _BTree(rootedAt: self.toNode(ofCapacity: capacity), internalCapacity: capacity) } func matches(_ btree: _BTree) -> Bool { diff --git a/Tests/SortedCollectionsTests/BTree/Node+Balancing Tests.swift b/Tests/SortedCollectionsTests/BTree/Node+Balancing Tests.swift index 097eb52f..f108148b 100644 --- a/Tests/SortedCollectionsTests/BTree/Node+Balancing Tests.swift +++ b/Tests/SortedCollectionsTests/BTree/Node+Balancing Tests.swift @@ -42,14 +42,14 @@ final class NodeBalancingTests: CollectionTestCase { var btree = t.toBTree(ofCapacity: 2) print(btree.debugDescription) - btree.removeAny(key: 0) - btree.removeAny(key: 1) - btree.removeAny(key: 2) - btree.removeAny(key: 3) - btree.removeAny(key: 4) - btree.removeAny(key: 5) - btree.removeAny(key: 6) - btree.removeAny(key: 18) + btree.removeAnyElement(forKey: 0) + btree.removeAnyElement(forKey: 1) + btree.removeAnyElement(forKey: 2) + btree.removeAnyElement(forKey: 3) + btree.removeAnyElement(forKey: 4) + btree.removeAnyElement(forKey: 5) + btree.removeAnyElement(forKey: 6) + btree.removeAnyElement(forKey: 18) print(btree.debugDescription) // print(SortedDictionary(_rootedAt: btree)) } @@ -71,7 +71,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.rotateRight(at: 0) } + node.update { $0.rotateRight(atSlot: 0) } expectTrue( tree { @@ -98,7 +98,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.rotateRight(at: 0) } + node.update { $0.rotateRight(atSlot: 0) } expectTrue( tree { @@ -126,7 +126,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.rotateLeft(at: 0) } + node.update { $0.rotateLeft(atSlot: 0) } expectTrue( tree { @@ -153,7 +153,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.rotateLeft(at: 0) } + node.update { $0.rotateLeft(atSlot: 0) } expectTrue( tree { @@ -172,7 +172,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.rotateLeft(at: 0) } + node.update { $0.rotateLeft(atSlot: 0) } expectTrue( tree { @@ -198,7 +198,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.collapse(at: 0) } + node.update { $0.collapse(atSlot: 0) } expectTrue( tree { @@ -223,7 +223,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.collapse(at: 0) } + node.update { $0.collapse(atSlot: 0) } expectTrue( tree { diff --git a/Tests/SortedCollectionsTests/BTree/Node+Insertion Tests.swift b/Tests/SortedCollectionsTests/BTree/Node+Insertion Tests.swift index 4280a1a1..43227b9b 100644 --- a/Tests/SortedCollectionsTests/BTree/Node+Insertion Tests.swift +++ b/Tests/SortedCollectionsTests/BTree/Node+Insertion Tests.swift @@ -19,7 +19,7 @@ func expectInsertionInTree( toEqual refTree: NodeTemplate) { var btree = tree.toBTree(ofCapacity: capacity) - btree.setAnyValue(key * 2, forKey: key) + btree.updateAnyValue(key * 2, forKey: key) let refMatches = refTree.matches(btree) if !refMatches { diff --git a/Tests/SortedCollectionsTests/BTree/NodeTests.swift b/Tests/SortedCollectionsTests/BTree/NodeTests.swift index 73bdaac4..722f558b 100644 --- a/Tests/SortedCollectionsTests/BTree/NodeTests.swift +++ b/Tests/SortedCollectionsTests/BTree/NodeTests.swift @@ -91,8 +91,8 @@ final class NodeTests: CollectionTestCase { let newKey = position * 2 + 1 let splinter: _Node.Splinter? = node.update { handle in - let index = handle.lastSlot(for: newKey) - return handle.insertElement(element: (newKey, newKey * 2), withRightChild: nil, atSlot: index) + let index = handle.endSlot(forKey: newKey) + return handle.insertElement((newKey, newKey * 2), withRightChild: nil, atSlot: index) } insertSortedValue(newKey, into: &array) @@ -114,7 +114,7 @@ final class NodeTests: CollectionTestCase { withEveryNode(ofCapacity: capacity, keys: keys, duplicates: duplicates) { node, array, duplicatedKey in node.read { handle in expectEqual( - handle.firstSlot(for: duplicatedKey), + handle.startSlot(forKey: duplicatedKey), findFirstIndexOf(duplicatedKey, in: array) ) } @@ -131,7 +131,7 @@ final class NodeTests: CollectionTestCase { withEveryNode(ofCapacity: capacity, keys: keys, duplicates: duplicates) { node, array, duplicatedKey in node.read { handle in expectEqual( - handle.lastSlot(for: duplicatedKey), + handle.endSlot(forKey: duplicatedKey), findLastIndexOf(duplicatedKey, in: array) ) }