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.
This commit is contained in:
Vihan Bhargava committed 2021-08-09 19:13:50 -07:00
1 parent 8de0b4ff7a
commit 98f278545d
25 files changed
+195 -179

No files matched your search

@@ -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
@@ -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..<rangeSize {
self.remove(at: startOffset)
self.remove(atOffset: startOffset)
}
}
@@ -35,6 +35,13 @@ extension _BTree: Sequence {
self.offsets = .init(repeating: 0)
self.parents = .init(repeating: .passUnretained(tree.root.storage))
// Simple case for an empty tree
if self.tree.isEmpty {
self.currentNode = .passUnretained(tree.root.storage)
self.slot = -1
return
}
// TODO: maybe convert to unowned(unsafe)
var node = tree.root
while !node.read({ $0.isLeaf }) {
@@ -52,6 +59,7 @@ extension _BTree: Sequence {
@inlinable
@inline(__always)
internal mutating func next() -> 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
}
}
}
@@ -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.")
}
}
@@ -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<Value> {
@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
@@ -28,9 +28,8 @@ extension _BTree {
@usableFromInline
internal var childSlots: Offsets
// TODO: switch to Unmanaged<Node.Storage>
@usableFromInline
internal unowned(unsafe) var node: Node.Storage
internal var node: Unmanaged<Node.Storage>
@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<R>(
_ 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
}
}
+49 -31
View File
@@ -25,12 +25,12 @@ internal struct _BTree<Key: Comparable, Value> {
/// 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<Key: Comparable, Value> {
@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<Key>.stride
)
let internalCapacity = Swift.min(
16,
_BTree.defaultInternalCapacity / MemoryLayout<Key>.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<Key: Comparable, Value> {
/// 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.
@@ -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<Element> = ManagedBuffer<BufferHeader, Element>
}
@@ -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
}
@@ -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
@@ -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")
@@ -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..<self.childCount {
totalChildElements += self[childAt: i].storage.header.totalElements
totalChildElements += self[childAt: i].storage.header.subtreeCount
}
}
@@ -70,33 +70,34 @@ extension _Node {
internal func checkInvariants() {
// TODO: move non-constant time checks to _BTree
assert(isLeaf || childCount == elementCount + 1,
assert(isLeaf || childCount == subtreeCount + 1,
"Node must be either leaf or a child on the side of each key.")
assert(elementCount >= 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..<elementCount {
for i in 0..<subtreeCount {
let key = self[keyAt: i]
let child = self[childAt: i].read({ $0[keyAt: $0.elementCount - 1] })
let child = self[childAt: i].read({ $0[keyAt: $0.subtreeCount - 1] })
precondition(child <= key, "Left subtree must be less or equal to than its parent key.")
}
let key = self[keyAt: elementCount - 1]
let child = self[childAt: elementCount].read({ $0[keyAt: $0.elementCount - 1] })
let key = self[keyAt: subtreeCount - 1]
let child = self[childAt: subtreeCount].read({ $0[keyAt: $0.subtreeCount - 1] })
precondition(child >= 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
}
}
+2 -2
View File
@@ -32,13 +32,13 @@ internal struct _Node<Key: Comparable, Value> {
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
@@ -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)
}
}
}
@@ -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)
}
@@ -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
}
}
@@ -20,7 +20,7 @@ extension SortedSet {
self.init()
for element in elements {
self._root.setAnyValue((), forKey: element)
self._root.updateAnyValue((), forKey: element)
}
}
@@ -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
}
}
@@ -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..<size) { key in
btreeOfSize(size) { tree, kvs in
tree.removeAny(key: key)
tree.removeAnyElement(forKey: key)
var comparisonKeys = Array(0..<size)
comparisonKeys.remove(at: key)
@@ -19,7 +19,7 @@ func btreeOfSize(
var tree = _BTree<Int, Int>(capacity: 2)
var keyValues = [(key: Int, value: Int)]()
for i in 0..<size {
tree.setAnyValue(i * 2, forKey: i)
tree.updateAnyValue(i * 2, forKey: i)
keyValues.append((key: i, value: i * 2))
}
try withExtendedLifetime(tree) {
@@ -168,7 +168,7 @@ final class BTreeTests: CollectionTestCase {
var tree = _BTree<Int, Int>()
for (key, value) in kvs {
tree.setAnyValue(value, forKey: key)
tree.updateAnyValue(value, forKey: key)
}
}
}
@@ -25,7 +25,7 @@ struct NodeTemplate {
}
func toBTree(ofCapacity capacity: Int) -> _BTree<Int, Int> {
return _BTree(rootedAt: self.toNode(ofCapacity: capacity), capacity: capacity)
return _BTree(rootedAt: self.toNode(ofCapacity: capacity), internalCapacity: capacity)
}
func matches(_ btree: _BTree<Int, Int>) -> Bool {
@@ -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<Int, Int>(_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 {
@@ -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 {
@@ -91,8 +91,8 @@ final class NodeTests: CollectionTestCase {
let newKey = position * 2 + 1
let splinter: _Node<Int, Int>.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)
)
}