Initial commit for SortedCollections

Signed-off-by: Vihan Bhargava <vihan_bhargava@apple.com>
This commit is contained in:
Vihan Bhargava committed 2021-08-09 19:13:41 -07:00
1 parent cc69069676
commit 9cf2cdadc0
40 files changed
+4019 -41

No files matched your search

@@ -0,0 +1,323 @@
//===----------------------------------------------------------------------===//
//
// 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 _BTree: BidirectionalCollection {
/// The total number of elements contained within the BTree
/// - Complexity: O(1)
@inlinable
@inline(__always)
internal var count: Int { self.root.storage.header.totalElements }
/// A Boolean value that indicates whether the BTree is empty.
@inlinable
@inline(__always)
internal var isEmpty: Bool { self.count == 0 }
/// Locates the first element and returns a proper path to it, or nil if the BTree is empty.
/// - Complexity: O(1)
@inlinable
internal var startIndex: Index {
if count == 0 { return Index(nil, forTree: self) }
var depth = 0
var currentNode = self.root
while !currentNode.read({ $0.isLeaf }) {
// TODO: figure out how to avoid the swift retain here
currentNode = currentNode.read({ $0[childAt: 0] })
depth += 1
}
let path = UnsafePath(
node: currentNode,
slot: 0,
childSlots: Array<Int>(repeating: 0, count: depth),
offset: 0
)
return Index(path, forTree: self)
}
/// Returns a sentinel value for the last element
/// - Complexity: O(1)
@inlinable
internal var endIndex: Index { Index(nil, forTree: self) }
/// Gets the effective offset of an index
/// - Warning: this does not
@inlinable
@inline(__always)
internal func offset(of index: Index) -> Int {
return index.path?.offset ?? self.count
}
/// Returns the distance between two indices.
/// - 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.
/// - Complexity: O(1)
@inlinable
internal func distance(from start: Index, to end: Index) -> Int {
return self.offset(of: end) - self.offset(of: start)
}
/// Replaces the given index with its successor.
/// - Parameter index: A valid index of the collection. i must be less than endIndex.
/// - Complexity: O(`log n`) in the worst-case.
@inlinable
internal func formIndex(after index: inout Index) {
guard var path = index.path else {
preconditionFailure("Attempt to advance out of collection bounds.")
}
let shouldSeekWithinLeaf = Node(path.node).read({
$0.isLeaf && _fastPath(path.slot + 1 < $0.numElements)
})
if shouldSeekWithinLeaf {
// Continue searching within the same leaf
path.slot += 1
path.offset += 1
index.path = path
} else {
self.formIndex(&index, offsetBy: 1)
}
}
/// Returns the position immediately after the given index.
/// - Parameter i: A valid index of the collection. i must be less than endIndex.
/// - Returns: The index value immediately after i.
/// - Complexity: O(`log n`) in the worst-case.
@inlinable
internal func index(after i: Index) -> Index {
var newIndex = i
self.formIndex(after: &newIndex)
return newIndex
}
/// Replaces the given index with its predecessor.
/// - Parameter index: A valid index of the collection. i must be greater than startIndex.
/// - Complexity: O(`log n`) in the worst-case.
@inlinable
internal func formIndex(before index: inout Index) {
assert(!self.isEmpty && self.offset(of: index) != 0, "Attempt to advance out of collection bounds.")
// TODO: implement more efficient logic to better move through the tree
self.formIndex(&index, offsetBy: -1)
}
/// Returns the position immediately before the given index.
/// - Parameter i: A valid index of the collection. i must be greater than startIndex.
/// - Returns: The index value immediately before i.
/// - Complexity: O(`log n`) in the worst-case.
@inlinable
internal func index(before i: Index) -> Index {
var newIndex = i
self.formIndex(before: &newIndex)
return newIndex
}
/// Offsets the given index by the specified distance.
///
/// The value passed as distance must not offset i beyond the bounds of the collection.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - Complexity: O(`log n`) in the worst-case.
@inlinable
internal func formIndex(_ i: inout Index, offsetBy distance: Int) {
let newIndex = self.offset(of: i) + distance
assert(0 <= newIndex && newIndex <= self.count, "Attempt to advance out of collection bounds.")
if newIndex == self.count {
i.path = nil
return
}
// TODO: optimization for searching within children
if var path = i.path, path.node.header.children == nil {
// Check if the target element will be in the same node
let targetSlot = path.slot + distance
if 0 <= targetSlot && targetSlot < path.node.header.count {
path.slot = targetSlot
path.offset = newIndex
i.path = path
return
}
}
// Otherwise, re-seek
i = self.indexToElement(at: newIndex)
}
/// Returns an index that is the specified distance from the given index.
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - Returns: An index offset by `distance` from the index `i`. If `distance`
/// is positive, this is the same value as the result of `distance` calls to
/// `index(after:)`. If `distance` is negative, this is the same value as the
/// result of `abs(distance)` calls to `index(before:)`.
@inlinable
internal func index(_ i: Index, offsetBy distance: Int) -> Index {
var newIndex = i
self.formIndex(&newIndex, offsetBy: distance)
return newIndex
}
/// Offsets the given index by the specified distance, or so that it equals the given limiting index.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `distance > 0`, a limit that is
/// less than `i` has no effect. Likewise, if `distance < 0`, a limit that is greater than `i`
/// has no effect.
/// - Returns: `true` if `i` has been offset by exactly `distance` steps without going beyond
/// `limit`; otherwise, `false`. When the return value is `false`, the value of `i` is equal
/// to `limit`.
/// - Complexity: O(`log n`) in the worst-case.
@inlinable
internal func formIndex(_ i: inout Index, offsetBy distance: Int, limitedBy limit: Index) -> Bool {
let distanceToLimit = self.distance(from: i, to: limit)
if distance < 0 ? distanceToLimit > distance : distanceToLimit < distance {
self.formIndex(&i, offsetBy: distanceToLimit)
return false
} else {
self.formIndex(&i, offsetBy: distance)
return true
}
}
/// Returns an index that is the specified distance from the given index, unless that distance
/// is beyond a given limiting index.
///
/// - Parameters:
/// - i: A valid index of the collection.
/// - distance: The distance to offset `i`.
/// - limit: A valid index of the collection to use as a limit. If `distance > 0`, a `limit`
/// that is less than `i` has no effect. Likewise, if `distance < 0`, a `limit` that is
/// greater twhan `i` has no effect.
/// - Returns: An index offset by `distance` from the index `i`, unless that index would
/// be beyond `limit` in the direction of movement. In that case, the method returns `nil`.
@inlinable
internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? {
let distanceToLimit = self.distance(from: i, to: limit)
if distance < 0 ? distanceToLimit > distance : distanceToLimit < distance {
return nil
} else {
var newIndex = i
self.formIndex(&newIndex, offsetBy: distance)
return newIndex
}
}
@inlinable
@inline(__always)
internal subscript(index: Index) -> Element {
assert(index.path != nil, "Attempt to subscript out of range index.")
return index.path!.element
}
}
// MARK: Custom Indexing Operations
extension _BTree {
/// Returns the path corresponding to the first found instance of the key. This may
/// not be the first instance of the key. This is marginally more efficient for trees
/// that do not have duplicates.
///
/// - Parameter key: The key to search for within the tree.
/// - Returns: If found, returns a path to the element. Otherwise, `nil`.
@inlinable
internal func anyIndex(forKey key: Key) -> Index? {
var childSlots = [Int]()
childSlots.reserveCapacity(BTREE_MAX_DEPTH)
var node: Node? = self.root
while let currentNode = node {
let path: UnsafePath? = currentNode.read { handle in
let keySlot = handle.firstSlot(for: key)
if keySlot < handle.numElements && handle[keyAt: keySlot] == key {
return UnsafePath(node: currentNode.storage, slot: keySlot, childSlots: childSlots, offset: 0)
} else {
if handle.isLeaf {
node = nil
} else {
childSlots.append(keySlot)
node = handle[childAt: keySlot]
}
return nil
}
}
if let path = path {
return Index(path, forTree: self)
}
}
return nil
}
/// Returns a path to the key at absolute offset `i`.
/// - Parameter offset: 0-indexed offset within BTree bounds, else may panic.
/// - Returns: the index of the appropriate element.
/// - Complexity: O(`log n`)
@inlinable
internal func indexToElement(at offset: Int) -> Index {
assert(offset <= self.count, "Index out of bounds.")
if offset == self.count {
return Index(nil, forTree: self)
}
var childSlots = [Int]()
childSlots.reserveCapacity(BTREE_MAX_DEPTH)
var node: _Node = self.root
var startIndex = 0
while !node.read({ $0.isLeaf }) {
let internalPath: UnsafePath? = node.read { handle in
for childSlot in 0..<handle.numChildren {
let child = handle[childAt: childSlot]
let endIndex = startIndex + child.read({ $0.numTotalElements })
if offset < endIndex {
childSlots.append(childSlot)
node = child
return nil
} else if offset == endIndex {
// We've found the node we want
return UnsafePath(node: node, slot: childSlot, childSlots: childSlots, offset: offset)
} else {
startIndex = endIndex + 1
}
}
// TODO: convert into debug-only preconditionFaliure
preconditionFailure("In-bounds index not found within tree.")
}
if let internalPath = internalPath { return Index(internalPath, forTree: self) }
}
let path: UnsafePath = UnsafePath(
node: node,
slot: offset - startIndex,
childSlots: childSlots,
offset: offset
)
return Index(path, forTree: self)
}
}
@@ -0,0 +1,25 @@
//===----------------------------------------------------------------------===//
//
// 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 _BTree: CustomDebugStringConvertible {
#if DEBUG
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
return "BTree<\(Key.self), \(Value.self)>\n" +
self.root.read { String(reflecting: $0) }
}
#else
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
return "BTree<\(Key.self), \(Value.self)>(\(self.root))"
}
#endif // DEBUG
}
@@ -0,0 +1,18 @@
//===----------------------------------------------------------------------===//
//
// 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 _BTree {
/// Runs some operations on a BTree, ensuring it does not get deallocated in the process
@_spi(Testing)
public mutating func withSelf<R>(_ body: (inout _BTree) throws -> R) rethrows -> R {
try body(&self)
}
}
@@ -0,0 +1,82 @@
//===----------------------------------------------------------------------===//
//
// 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 _BTree {
/// An index to an element of the BTree represented as a path.
/// - Warning: operations using this type do not perform checks if the
/// tree is still valid. Therefore, operations using this may result in
/// undefined behavior if the tree is muated or deallocated.
@usableFromInline
internal struct Index: Comparable {
/// The path to the element in the BTree. A `nil` value indicates
/// the endIndex
@usableFromInline
internal var path: UnsafePath?
/// The tree that this index references.
@usableFromInline
internal weak var root: Node.Storage?
/// The age of the tree when this index was captures.
@usableFromInline
internal let age: Int32
// TODO: optimize this to potentially avoid capturing a weak
// reference for `nil` or endIndex by using another mechanism
// to perform validity checks.
@inlinable
@inline(__always)
internal init(_ path: UnsafePath?, forTree tree: _BTree) {
self.path = path
self.root = tree.root.storage
self.age = tree.age
}
@inlinable
@inline(__always)
internal static func ==(lhs: Index, rhs: Index) -> Bool {
return lhs.path?.node === rhs.path?.node
}
@inlinable
@inline(__always)
internal static func <(lhs: Index, rhs: Index) -> Bool {
switch (lhs.path, rhs.path) {
case let (lhsPath?, rhsPath?):
return lhsPath < rhsPath
case (_?, nil):
return true
case (nil, _?):
return false
case (nil, nil):
return false
}
}
/// Ensures the precondition that the index is valid for a given dictionary.
@inlinable
@inline(__always)
internal func ensureValid(for tree: _BTree) {
precondition(
self.root === tree.root.storage && self.age == tree.age,
"Attempt to use an invalid index.")
}
/// Ensures the precondition that the index is valid for use with another index
@inlinable
@inline(__always)
internal func ensureValid(with index: Index) {
precondition(
self.root != nil && self.root === index.root && self.age == index.age,
"Attempt to use an invalid indices.")
}
}
}
@@ -0,0 +1,182 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// TODO: add 0 key validations
// TODO: potentially make operations mutating.
extension _BTree {
/// Represents a specific element in a BTree. This holds strong references to the
/// element it points to.
/// - Warning: Operations on this path will trap if the underlying node is deallocated.
/// and they become invalid if the tree is mutated, however this is not checked. For
/// safety, use ``_BTree.Index`` instead
@usableFromInline
internal struct UnsafePath {
@usableFromInline
internal struct PackedOffsetList {
@usableFromInline
internal var depth: UInt8
@usableFromInline
internal var offsets: UInt64
@inlinable
@inline(__always)
internal init() {
self.depth = 0
self.offsets = 0
}
@inlinable
@inline(__always)
internal mutating func pop() {
assert(depth != 0, "Attempted to ascend from root path.")
self.depth &-= 1
}
@inlinable
@inline(__always)
internal mutating func move(by slots: UInt16) {
let level: UInt8 = depth << 4
let mask: UInt64 = UInt64(0xFFFF) << level
var oldSlot = (offsets & mask) >> level
oldSlot &+= UInt64(slots)
offsets = (offsets & ~mask) | (oldSlot << level)
}
@inlinable
@inline(__always)
internal mutating func child(at slot: UInt16) {
assert(depth != 3, "Attempted to exceed maximum depth.")
depth &+= 1
let level: UInt8 = depth << 4
let mask: UInt64 = UInt64(0xFFFF) << level
offsets = (offsets & ~mask) | (UInt64(slot) << level)
}
}
// TODO: potentially make compact (U)Int8/16 type to be more compact
/// The position of each of the parent nodes in their parents. The path's depth
/// is offsets.count + 1
@usableFromInline
internal var childSlots: Array<Int>
@usableFromInline
internal unowned(unsafe) var node: Node.Storage
@usableFromInline
internal var slot: Int
/// The absolute offset of the path's element in the entire tree
@usableFromInline
internal var offset: Int
// MARK: Validation
#if COLLECTIONS_INTERNAL_CHECKS
@inline(never)
@usableFromInline
internal func validatePath() {
precondition(slot >= 0, "Slot must be non-negative integer")
}
#else
@inlinable
@inline(__always)
internal func validatePath() {}
#endif // COLLECTIONS_INTERNAL_CHECKS
// MARK: Path Initializers
/// Creates a path representing a sequence of nodes to an element.
/// - Parameters:
/// - node: The node to which this path points.
/// - slot: The specific slot within node where the path points
/// - parents: The parent nodes and their children's offsets for this path.
/// - index: The absolute offset of this path's element in the tree.
@inlinable
internal init(
node: Node,
slot: Int,
childSlots: Array<Int>,
offset: Int) {
self.init(node: node.storage, slot: slot, childSlots: childSlots, offset: offset)
}
/// Creates a path representing a sequence of nodes to an element.
/// - Parameters:
/// - node: The node to which this path points.
/// - slot: The specific slot within node where the path points
/// - parents: The parent nodes and their children's offsets for this path.
/// - index: The absolute offset of this path's element in the tree.
@inlinable
internal init(
node: Node.Storage,
slot: Int,
childSlots: Array<Int>,
offset: Int
) {
self.node = node
self.slot = slot
self.childSlots = childSlots
self.offset = offset
validatePath()
}
/// Gets the element the path points to.
@inlinable
@inline(__always)
internal var element: Element {
return Node(self.node).read { $0[elementAt: self.slot] }
}
}
}
// MARK: Equatable
extension _BTree.UnsafePath: Equatable {
/// Returns true if two paths are identical (point to the same node).
/// - Precondition: expects both paths are from the same BTree.
/// - Complexity: O(1)
@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
}
}
// MARK: Comparable
extension _BTree.UnsafePath: Comparable {
/// Returns true if the first path points to an element before the second path
/// - Complexity: O(`log n`)
@inlinable
public static func <(lhs: _BTree.UnsafePath, rhs: _BTree.UnsafePath) -> Bool {
for i in 0..<min(lhs.childSlots.count, rhs.childSlots.count) {
if lhs.childSlots[i] < rhs.childSlots[i] {
return true
}
}
if lhs.childSlots.count < rhs.childSlots.count {
let rhsOffset = rhs.childSlots[lhs.childSlots.count - 1]
return lhs.slot < rhsOffset
} else if rhs.childSlots.count < lhs.childSlots.count {
let lhsOffset = lhs.childSlots[rhs.childSlots.count - 1]
return lhsOffset <= rhs.slot
} else {
return lhs.slot < rhs.slot
}
}
}
@@ -0,0 +1,263 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// TODO: decide node capacity. Currently exploring 470 v 1050
// TODO: better benchmarking here
/// Internal node capacity for BTree
@usableFromInline
internal let BTREE_INTERNAL_CAPACITY = 16
/// Leaf node capacity for BTree
@usableFromInline
internal let BTREE_LEAF_CAPACITY = 470
/// An expected rough upper bound for BTree depth
@usableFromInline
internal let BTREE_MAX_DEPTH = 10
/// A bidirectional collection representing a BTree which efficiently stores its
/// elements in sorted order and maintains roughly `O(log count)`
/// performance for most operations.
///
/// - Warning: Indexing operations on a BTree are unchecked. ``_BTree.Index``
/// offers `ensureValid(for:)` methods to validate indices for use in higher-level
/// collections.
@usableFromInline
internal struct _BTree<Key: Comparable, Value> {
@usableFromInline
typealias Element = (key: Key, value: Value)
@usableFromInline
typealias Node = _Node<Key, Value>
/// The underlying node behind this local BTree
@usableFromInline
internal var root: Node
// TODO: remove
/// 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
/// coincidence.
@usableFromInline
internal var age: Int32
/// Creates an empty BTree rooted at a specific node with a specified uniform capacity
/// - Parameter capacity: The key capacity of all nodes.
@inlinable
@inline(__always)
internal init(capacity: Int) {
self.init(
leafCapacity: capacity,
internalCapacity: capacity
)
}
/// 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`.
@inlinable
@inline(__always)
internal init(leafCapacity: Int = BTREE_LEAF_CAPACITY, internalCapacity: Int = BTREE_INTERNAL_CAPACITY) {
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
/// - Parameters:
/// - root: The root node.
/// - capacity: The key capacity of all 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 = BTREE_LEAF_CAPACITY, internalCapacity: Int = BTREE_INTERNAL_CAPACITY) {
self.root = root
self.internalCapacity = internalCapacity
self.age = Int32(truncatingIfNeeded: ObjectIdentifier(root.storage).hashValue)
}
}
// MARK: Mutating Operations
extension _BTree {
/// Invalidates the issued indices of the dictionary. Ensure this is
/// called for operations which mutate the SortedDictionary.
@inlinable
@inline(__always)
internal mutating func invalidateIndices() {
self.age &+= 1
}
@usableFromInline
internal enum InsertionResult {
case updated(previousValue: Value)
case splintered(Node.Splinter)
case inserted
@inlinable
@inline(__always)
internal init(from splinter: Node.Splinter?) {
if let splinter = splinter {
self = .splintered(splinter)
} else {
self = .inserted
}
}
}
/// Inserts an element into the BTree, or updates it if it already exists within the tree. If there are
/// multiple instances of the key in the tree, this may update any one.
///
/// This operation is marginally more efficient on trees without duplicates, and may have
/// inconsistent results on trees with duplicates.
///
/// - Parameters:
/// - element: The key-value pair to insert
/// - Returns: If updated, the previous value for the key.
/// - Complexity: O(`log n`)
@inlinable
@discardableResult
internal mutating func setAnyValue(_ value: Value, forKey key: Key) -> Value? {
invalidateIndices()
let result = self.root.update { $0.setAnyValue(value, forKey: key) }
switch result {
case let .updated(previousValue):
return previousValue
case let .splintered(splinter):
self.root = splinter.toNode(
from: self.root,
withCapacity: self.internalCapacity
)
default: break
}
return nil
}
/// Removes the key-value pair corresponding to the first found instance of the key.
/// This may not be the first instance of the key. This is marginally more efficient for trees
/// that do not have duplicates.
///
/// If the key is not found, the tree is not modified, although the age of the tree may change.
///
/// - Parameter key: The key to remove in the tree
/// - Returns: The key-value pair which was removed. `nil` if not removed.
@inlinable
@discardableResult
internal mutating func removeAny(key: Key) -> Element? {
invalidateIndices()
func deleteWithin(node handle: Node.UnsafeHandle) -> Element? {
let slot = handle.firstSlot(for: key)
// if slot < handle.numElements && handle[keyAt: slot] == key {
// // We have found the key
// if handle.isLeaf {
// // Check if removing the element will make the element undersized
// if handle.numElements <= handle.minCapacity {
// // Undersized node
// return handle.
// } else {
// return handle.removeElement(at: slot)
// }
// } else {
// if handle.numElements <= handle.minCapacity {
// // Undersized node.
// } else {
// // Swap with the
// }
// }
// } else {
// if handle.isLeaf {
// // If we're in a leaf node and didn't find the key, it does
// // not exist.
// return nil
// } else {
// // Sanity-check
// assert(slot < handle.numChildren, "Attempt to remove from invalid child.")
// assert()
//
// let childElement = handle[childAt: slot].update { deleteWithin(node: $0) }
//
// //
// }
// }
return nil
}
// TODO: Don't create CoW copy until needed.
return self.root.update { deleteWithin(node: $0) }
}
}
// MARK: Read Operations
extension _BTree {
/// Returns the value corresponding to the first found instance of the key. This may
/// not be the first instance of the key. This is marginally more efficient for trees
/// that do not have duplicates.
///
/// - Parameter key: The key to search for
/// - Returns: `nil` if the key was not found. Otherwise, the previous value.
/// - Complexity: O(`log n`)
@inlinable
internal func anyValue(for key: Key) -> Value? {
// the retain/release calls
// Retain
var node: Node? = self.root
while let currentNode = node {
let value: Value? = currentNode.read { handle in
let slot = handle.firstSlot(for: key)
if slot < handle.numElements && handle[keyAt: slot] == key {
return handle[valueAt: slot]
} else {
if handle.isLeaf {
node = nil
} else {
// Release
// Retain
node = handle[childAt: slot]
}
}
return nil
}
if let value = value { return value }
}
return nil
}
}
@@ -0,0 +1,17 @@
//===----------------------------------------------------------------------===//
//
// 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: CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
self.read { $0.debugDescription }
}
}
@@ -0,0 +1,62 @@
//===----------------------------------------------------------------------===//
//
// 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 {
/// Initialize a node from a list of key-value tuples.
@_spi(Testing)
public init<C: Collection>(
_keyValuePairs keyValuePairs: C,
children: [_Node<Key, Value>]? = nil,
capacity: Int
) where C.Element == Element {
precondition(keyValuePairs.count <= capacity, "Too many key-value pairs.")
self.init(withCapacity: capacity, isLeaf: children == nil)
self.update { handle in
let sortedKeyValuePairs = keyValuePairs.sorted(by: { $0.key < $1.key })
for (index, pair) in sortedKeyValuePairs.enumerated() {
let (key, value) = pair
handle.keys.advanced(by: index).initialize(to: key)
handle.values.advanced(by: index).initialize(to: value)
}
if let children = children {
for (index, child) in children.enumerated() {
handle.children!.advanced(by: index).initialize(to: child)
}
}
let totalChildElements = children?.reduce(0, { $0 + $1.read({ $0.numTotalElements }) })
handle.numElements = keyValuePairs.count
handle.numTotalElements = keyValuePairs.count + (totalChildElements ?? 0)
}
}
/// Converts a node to a single array.
@_spi(Testing)
public func toArray() -> [Element] {
self.read { handle in
if handle.isLeaf {
return Array((0..<handle.numElements).map { handle[elementAt: $0] })
} else {
var elements = [Element]()
for i in 0..<handle.numElements {
elements.append(contentsOf: handle[childAt: i].toArray())
elements.append(handle[elementAt: i])
}
elements.append(contentsOf: handle[childAt: handle.numElements].toArray())
return elements
}
}
}
}
@@ -0,0 +1,24 @@
//===----------------------------------------------------------------------===//
//
// 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>
}
@@ -0,0 +1,48 @@
//===----------------------------------------------------------------------===//
//
// 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 {
/// Represents the result of a overfilled node's split.
@usableFromInline
internal struct Splinter {
@inlinable
@inline(__always)
internal init(median: Element, rightChild: _Node<Key, Value>) {
self.median = median
self.rightChild = rightChild
}
/// The former median element which should be propogated upward.
@usableFromInline
internal let median: Element
/// The right product of the node split.
@usableFromInline
internal var rightChild: _Node<Key, Value>
@inlinable
@inline(__always)
internal func toNode(from node: _Node<Key, Value>, withCapacity capacity: Int) -> _Node {
var newNode = _Node(withCapacity: capacity, isLeaf: false)
newNode.update { handle in
handle.keys.initialize(to: median.key)
handle.values.initialize(to: median.value)
handle.children.unsafelyUnwrapped.initialize(to: node)
handle.children.unsafelyUnwrapped.advanced(by: 1).initialize(to: self.rightChild)
handle.numElements = 1
handle.numTotalElements = 1 + node.storage.header.totalElements + self.rightChild.storage.header.totalElements
}
return newNode
}
}
}
@@ -0,0 +1,68 @@
//===----------------------------------------------------------------------===//
//
// 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 Header {
@inlinable
internal init(
capacity: Int,
count: Int,
totalElements: Int,
values: _Node<Key, Value>.Buffer<Value>,
children: _Node<Key, Value>.Buffer<_Node<Key, Value>>?
) {
self.capacity = capacity
self.count = count
self.values = values
self.children = children
self.totalElements = totalElements
}
@usableFromInline
internal var capacity: Int
/// Refers to the amount of keys in the node.
@usableFromInline
internal var count: Int
/// The total amount of elements contained underneath this node
@usableFromInline
internal var totalElements: Int
/// Pointer to the buffer containing the corresponding values.
@usableFromInline
internal var values: Buffer<Value>
/// Pointer to the buffer containing the elements.
@usableFromInline
internal var children: Buffer<_Node<Key, Value>>?
}
/// Represents the underlying data for a node in the heap.
@usableFromInline
internal class Storage: ManagedBuffer<_Node.Header, Key> {
@inlinable
deinit {
self.withUnsafeMutablePointers { header, elements in
_ = header.pointee.values.withUnsafeMutablePointerToElements { values in
values.deinitialize(count: header.pointee.count)
}
_ = header.pointee.children?.withUnsafeMutablePointerToElements { children in
children.deinitialize(count: header.pointee.count + 1)
}
elements.deinitialize(count: header.pointee.count)
}
}
}
}
@@ -0,0 +1,124 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// MARK: CustomDebugStringConvertible
extension _Node.UnsafeHandle: CustomDebugStringConvertible {
#if DEBUG
private enum PrintPosition { case start, end, middle }
private func indentDescription(_ node: _Node<Key, Value>.UnsafeHandle, position: PrintPosition) -> String {
let label = "(\(node.numTotalElements))"
let spaces = String(repeating: " ", count: label.count)
let lines = describeNode(node).split(separator: "\n")
return lines.enumerated().map({ index, line in
var lineToInsert = line
let middle = (lines.count - 1) / 2
if index < middle {
if position == .start {
return " " + spaces + lineToInsert
} else {
return "┃ " + spaces + lineToInsert
}
} else if index > middle {
if position == .end {
return " " + spaces + lineToInsert
} else {
return "┃ " + spaces + lineToInsert
}
} else {
switch line[line.startIndex] {
case "╺": lineToInsert.replaceSubrange(...line.startIndex, with: "━")
case "┗": lineToInsert.replaceSubrange(...line.startIndex, with: "┻")
case "┏": lineToInsert.replaceSubrange(...line.startIndex, with: "┳")
case "┣": lineToInsert.replaceSubrange(...line.startIndex, with: "╋")
default: break
}
switch position {
case .start: return "┏━\(label)━" + lineToInsert
case .middle: return "┣━\(label)━" + lineToInsert
case .end: return "┗━\(label)━" + lineToInsert
}
}
}).joined(separator: "\n")
}
/// A textual representation of this instance, suitable for debugging.
private func describeNode(_ node: _Node<Key, Value>.UnsafeHandle) -> String {
var result = ""
for slot in 0..<node.numElements {
if !node.isLeaf {
let child = node[childAt: slot]
let childDescription = child.read {
indentDescription($0, position: slot == 0 ? .start : .middle)
}
result += childDescription + "\n"
}
if node.isLeaf {
if node.numElements == 1 {
result += "╺━ "
} else if slot == node.numElements - 1 {
result += "┗━ "
} else if slot == 0 {
result += "┏━ "
} else {
result += "┣━ "
}
} else {
result += "┣━ "
}
debugPrint(node[keyAt: slot], terminator: ": ", to: &result)
debugPrint(node[valueAt: slot], terminator: "", to: &result)
if !node.isLeaf && slot == node.numElements - 1 {
let childDescription = node[childAt: slot + 1].read {
indentDescription($0, position: .end)
}
result += "\n" + childDescription
}
result += "\n"
}
return result
}
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
return indentDescription(self, position: .end)
}
#else
/// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
var result = "Node<\(Key.self), \(Value.self)>(["
var first = true
for slot in 0..<self.numElements {
if first {
first = false
} else {
result += ", "
}
result += "("
debugPrint(self[keyAt: slot], terminator: ", ", to: &result)
debugPrint(self[valueAt: slot], terminator: ")", to: &result)
}
result += "], "
if let children = self.children {
debugPrint(Array(UnsafeBufferPointer(start: children, count: self.numChildren)), terminator: ")", to: &result)
} else {
result += "[])"
}
return result
}
#endif // DEBUG
}
@@ -0,0 +1,265 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// MARK: Tree Insertions
extension _Node.UnsafeHandle {
@usableFromInline
internal enum InsertionResult {
case updated(previousValue: Value)
case splintered(_Node.Splinter)
case inserted
@inlinable
@inline(__always)
internal init(from splinter: _Node.Splinter?) {
if let splinter = splinter {
self = .splintered(splinter)
} else {
self = .inserted
}
}
}
/// Inserts an element in the tree, starting at the current node, returning a possible
/// splinter, or the previous value for any matching key if updating a node.
///
/// In the case of duplicates, this is marginally more efficient, however, this may update
/// any element with a key equal to the provided one in the tree. For this reason, refrain
/// from using this unless the tree is guaranteed to have unique keys, else it may have
/// inconsistent behavior.
///
/// If a matching key is found, only the value will be updated.
///
/// - Parameters:
/// - value: The value to insert or update.
/// - key: The key to equate.
/// - Returns: A representation of the possible results of the update/insertion.
@inlinable
@inline(__always)
internal func setAnyValue(_ value: Value, forKey key: Key) -> InsertionResult {
let insertionIndex = self.lastSlot(for: key)
if 0 < insertionIndex && insertionIndex <= self.numElements &&
self[keyAt: insertionIndex - 1] == key {
// TODO: potential copy of `value`. See if there is a way to prevent this.
let oldValue = self.values.advanced(by: insertionIndex - 1).move()
self.values.advanced(by: insertionIndex - 1).initialize(to: value)
return .updated(previousValue: oldValue)
}
// We need to try to insert as deep as possible as first, and have the splinter
// bubble up.
if self.isLeaf {
let maybeSplinter = self.immediatelyInsert(
element: (key, value),
withRightChild: nil,
at: insertionIndex
)
return InsertionResult(from: maybeSplinter)
} else {
let result = self[childAt: insertionIndex].update { $0.setAnyValue(value, forKey: key) }
switch result {
case .updated:
return result
case .splintered(let splinter):
let maybeSplinter = self.immediatelyInsert(splinter: splinter, at: insertionIndex)
return InsertionResult(from: maybeSplinter)
case .inserted:
self.numTotalElements += 1
return .inserted
}
}
}
}
// MARK: Immediate Node Insertions
extension _Node.UnsafeHandle {
/// Inserts a value into this node without considering the children. Be careful when using
/// this as you can violate the BTree invariants if not careful.
/// - Parameters:
/// - element: The new key-value pair to insert in the node.
/// - rightChild: The new element's corresponding right-child provided iff the
/// node is not a leaf, otherwise `nil`.
/// - insertionSlot: The slot to insert the new element.
/// - Returns: A splinter object if node splintered during the insert, otherwise `nil`
/// - Warning: Ensure you insert the node in a valid order as to not break the node's
/// sorted invariant.
@inlinable
internal func immediatelyInsert(
element: _Node.Element,
withRightChild rightChild: _Node?,
at insertionSlot: Int
) -> _Node.Splinter? {
assertMutable()
assert(self.isLeaf == (rightChild == nil), "A child can only be inserted iff the node is a leaf.")
// If we have a full B-Tree, we'll need to splinter
if self.numElements == self.capacity {
// Right median == left median for BTrees with odd capacity
let rightMedian = self.numElements / 2
let leftMedian = (self.numElements - 1) / 2
var splinterElement: _Node.Element
var rightNode = _Node(withCapacity: self.capacity, isLeaf: self.isLeaf)
if insertionSlot == rightMedian {
splinterElement = element
let numLeftElements = rightMedian
let numRightElements = self.numElements - rightMedian
rightNode.update { handle in
self.moveElements(toHandle: handle, fromSlot: rightMedian, toSlot: 0, count: numRightElements)
// TODO: also possible to do !self.isLeaf and force unwrap right child to
// help the compiler avoid this branch.
if !self.isLeaf {
handle.children.unsafelyUnwrapped.initialize(to: rightChild.unsafelyUnwrapped)
self.moveChildren(toHandle: handle, fromSlot: rightMedian + 1, toSlot: 1, count: numRightElements)
}
self.numElements = numLeftElements
handle.numElements = numRightElements
self.recomputeTotalElementCount(withRightSplit: handle)
}
} else if insertionSlot > rightMedian {
// This branch is almost certainly correct
splinterElement = self.moveElement(at: rightMedian)
rightNode.update { handle in
let insertionSlotInRightNode = insertionSlot - (rightMedian + 1)
self.moveElements(
toHandle: handle,
fromSlot: rightMedian + 1,
toSlot: 0,
count: insertionSlotInRightNode
)
self.moveElements(
toHandle: handle,
fromSlot: insertionSlot,
toSlot: insertionSlotInRightNode + 1,
count: self.numElements - insertionSlot
)
if !self.isLeaf {
self.moveChildren(
toHandle: handle,
fromSlot: rightMedian + 1,
toSlot: 0,
count: insertionSlot - rightMedian
)
self.moveChildren(
toHandle: handle,
fromSlot: insertionSlot + 1,
toSlot: insertionSlotInRightNode + 2,
count: self.numElements - insertionSlot
)
}
handle.setElement(element, withRightChild: rightChild, at: insertionSlotInRightNode)
handle.numElements = self.numElements - rightMedian
self.numElements = rightMedian
self.recomputeTotalElementCount(withRightSplit: handle)
}
} else {
// insertionSlot < rightMedian
splinterElement = self.moveElement(at: leftMedian)
rightNode.update { handle in
self.moveElements(
toHandle: handle,
fromSlot: leftMedian + 1,
toSlot: 0,
count: self.numElements - leftMedian - 1
)
self.moveElements(
toHandle: self,
fromSlot: insertionSlot,
toSlot: insertionSlot + 1,
count: leftMedian - insertionSlot
)
if !self.isLeaf {
self.moveChildren(
toHandle: handle,
fromSlot: leftMedian + 1,
toSlot: 0,
count: self.numElements - leftMedian
)
self.moveChildren(
toHandle: self,
fromSlot: insertionSlot + 1,
toSlot: insertionSlot + 2,
count: leftMedian - insertionSlot
)
}
self.setElement(element, withRightChild: rightChild, at: insertionSlot)
handle.numElements = self.numElements - leftMedian - 1
self.numElements = leftMedian + 1
self.recomputeTotalElementCount(withRightSplit: handle)
}
}
return _Node.Splinter(
median: splinterElement,
rightChild: rightNode
)
} else {
// Shift over elements near the insertion slot.
let numElemsToShift = self.numElements - insertionSlot
self.moveElements(
toHandle: self,
fromSlot: insertionSlot,
toSlot: insertionSlot + 1,
count: numElemsToShift
)
if !self.isLeaf {
let numChildrenToShift = self.numChildren - insertionSlot - 1
self.moveChildren(
toHandle: self,
fromSlot: insertionSlot + 1,
toSlot: insertionSlot + 2,
count: numChildrenToShift
)
}
self.setElement(element, withRightChild: rightChild, at: insertionSlot)
self.numElements += 1
self.numTotalElements += 1
return nil
}
}
/// Inserts a splinter, attaching the children appropriately
/// - Parameters:
/// - splinter: The splinter object from a child
/// - insertionSlot: The slot of the child which produced the splinter
/// - Returns: Another splinter which may need to be propagated upward
@inlinable
@inline(__always)
internal func immediatelyInsert(splinter: _Node.Splinter, at insertionSlot: Int) -> _Node.Splinter? {
return self.immediatelyInsert(element: splinter.median, withRightChild: splinter.rightChild, at: insertionSlot)
}
}
@@ -0,0 +1,476 @@
//===----------------------------------------------------------------------===//
//
// 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 UnsafeHandle {
@usableFromInline
internal let header: UnsafeMutablePointer<Header>
@usableFromInline
internal let keys: UnsafeMutablePointer<Key>
@usableFromInline
internal let values: UnsafeMutablePointer<Value>
@usableFromInline
internal let children: UnsafeMutablePointer<_Node<Key, Value>>?
@inlinable
@inline(__always)
internal init(
keys: UnsafeMutablePointer<Key>,
values: UnsafeMutablePointer<Value>,
children: UnsafeMutablePointer<_Node<Key, Value>>?,
header: UnsafeMutablePointer<Header>,
isMutable: Bool
) {
self.keys = keys
self.values = values
self.children = children
self.header = header
#if COLLECTIONS_INTERNAL_CHECKS
self.isMutable = isMutable
#endif
}
// MARK: Mutablility Checks
#if COLLECTIONS_INTERNAL_CHECKS
@usableFromInline
internal let isMutable: Bool
#endif
/// Check that this handle supports mutating operations.
/// Every member that mutates node data must start by calling this function.
/// This helps preventing COW violations.
///
/// Note that this is a noop in release builds.
@inlinable
@inline(__always)
internal func assertMutable() {
#if COLLECTIONS_INTERNAL_CHECKS
assert(self.isMutable, "Attempt to mutate a node through a read-only handle")
#endif
}
// MARK: Invariant Checks
#if COLLECTIONS_INTERNAL_CHECKS
@inline(never)
@usableFromInline
internal func checkInvariants() {
assert(isLeaf || numChildren == numElements + 1, "Node must have either zero children or a child on the side of each key.")
assert(numElements == numElements, "Node must have equal count of keys and values ")
assert(numElements >= 0, "Node cannot have negative number of elements")
assert(numTotalElements >= numElements, "Total number of elements under node cannot be less than the number of immediate elements.")
if numElements > 1 {
for i in 0..<(numElements - 1) {
precondition(self[keyAt: i] <= self[keyAt: i + 1], "Node is out-of-order.")
}
}
if !isLeaf {
for i in 0..<numElements {
let key = self[keyAt: i]
let child = self[childAt: i].read({ $0[keyAt: $0.numElements - 1] })
precondition(child <= key, "Left subtree must be less or equal to than its parent key.")
}
let key = self[keyAt: numElements - 1]
let child = self[childAt: numElements].read({ $0[keyAt: $0.numElements - 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
let nextLevelIsLeaf = self[childAt: 0].read({ $0.isLeaf })
for i in 0..<numChildren {
precondition(self[childAt: i].read({ $0.isLeaf }) == nextLevelIsLeaf, "All children must be the same depth.")
}
}
}
#else
@inlinable
@inline(__always)
internal func checkInvariants() {}
#endif // COLLECTIONS_INTERNAL_CHECKS
/// Creates a mutable version of this handle
@inlinable
@inline(__always)
internal init(mutableCopyOf handle: UnsafeHandle) {
self.init(
keys: handle.keys,
values: handle.values,
children: handle.children,
header: handle.header,
isMutable: true
)
}
// MARK: Convenience properties
@inlinable
@inline(__always)
internal var capacity: Int { header.pointee.capacity }
/// The number of elements immediately stored in the node
@inlinable
@inline(__always)
internal var numElements: Int {
get { header.pointee.count }
nonmutating set { assertMutable(); header.pointee.count = newValue }
}
/// The total number of elements that this node directly or indirectly stores
@inlinable
@inline(__always)
internal var numTotalElements: Int {
get { header.pointee.totalElements }
nonmutating set { assertMutable(); header.pointee.totalElements = newValue }
}
/// The number of children this node directly contains
/// - Warning: Do not access on a leaf, else will panic.
@inlinable
@inline(__always)
internal var numChildren: Int {
// TODO: should this be a method given that it may panic?
assert(!self.isLeaf, "Cannot access the child count on a leaf.")
return self.numElements + 1
}
// TODO: not sure what the branch predictor would do for this, given
// this is perfectly impredictable without context.
@inlinable
@inline(__always)
internal var isLeaf: Bool { children == nil }
/// A lower bound on the amount of keys we would want a node to contain.
///
/// Defined as `ceil(capacity)/2 - 1`.
@inlinable
@inline(__always)
internal var minCapacity: Int { (capacity + 1) / 2 - 1 }
}
}
// MARK: Subscript
extension _Node.UnsafeHandle {
@inlinable
@inline(__always)
internal subscript(elementAt slot: Int) -> _Node.Element {
get {
assert(slot < self.numElements, "Node element subscript out of bounds.")
return (key: self.keys[slot], value: self.values[slot])
}
}
@inlinable
@inline(__always)
internal subscript(keyAt slot: Int) -> Key {
_read {
assert(slot < self.numElements, "Node key subscript out of bounds.")
yield self.keys[slot]
}
}
@inlinable
@inline(__always)
internal subscript(valueAt slot: Int) -> Value {
_read {
assert(slot < self.numElements, "Node values subscript out of bounds.")
yield self.values[slot]
}
}
// TODO: consider implementing `_modify` for these subscripts
@inlinable
@inline(__always)
internal subscript(childAt slot: Int) -> _Node {
_read {
assert(!isLeaf, "Cannot access children of leaf node.")
assert(slot < self.numChildren, "Node child subscript out of bounds")
yield self.children.unsafelyUnwrapped[slot]
}
nonmutating _modify {
assert(!isLeaf, "Cannot modify children of leaf node.")
var child = self.children.unsafelyUnwrapped.advanced(by: slot).move()
defer { self.children.unsafelyUnwrapped.advanced(by: slot).initialize(to: child) }
yield &child
}
}
}
// MARK: Binary Search
extension _Node.UnsafeHandle {
/// Performs O(log n) search for a key, returning the first instance when duplicates exist. This
/// returns the first possible insertion point for `key`.
/// - Parameter key: The key to search for within the node.
/// - Returns: Either the slot if the first instance of the key, otherwise
/// the valid insertion point for the key.
@inlinable
internal func firstSlot(for key: Key) -> Int {
var start: Int = 0
var end: Int = self.numElements
while end > start {
let mid = (end &- start) / 2 &+ start
// TODO: make this info a conditional_mov
if key <= self.keys[mid] {
end = mid
} else {
start = mid &+ 1
}
}
return end
}
/// Performs O(log n) search for a key, returning the last instance when duplicates exist. This
/// returns the last possible valid insertion point for `key`.
/// - Parameter key: The key to search for within the node.
/// - Returns: Either the slot after the last instance of the key, otherwise
/// the valid insertion point for the key.
@inlinable
internal func lastSlot(for key: Key) -> Int {
var start: Int = 0
var end: Int = self.numElements
while end > start {
let mid = (end - start) / 2 + start
if key >= self.keys[mid] {
start = mid + 1
} else {
end = mid
}
}
return end
}
/// Searches the node and its children for a given value
@inlinable
internal func findValue(for key: Key) -> Value? {
// TODO: get rid of this method (suboptimal implementation).
let slot = self.firstSlot(for: key)
if slot < self.numElements && self[keyAt: slot] == key {
return self[valueAt: slot]
} else {
if self.isLeaf {
return nil
} else {
return self[childAt: slot].read { $0.findValue(for: key) }
}
}
}
}
// MARK: Element-wise Buffer Operations
extension _Node.UnsafeHandle {
/// Moves elements from the current handle to a new handle
/// - Parameters:
/// - newHandle: The destination handle to write to which could be the same
/// as the source to move within a handle.
/// - sourceSlot: The offset of the source handle to move from.
/// - destinationSlot: The offset of the destintion handle to write to.
/// - count: The amount of values to move
/// - Warning: This does not adjust the buffer counts.
@inlinable
@inline(__always)
internal func moveElements(
toHandle newHandle: _Node.UnsafeHandle,
fromSlot sourceSlot: Int,
toSlot destinationSlot: Int,
count: Int
) {
assert(sourceSlot >= 0, "Move source slot must be positive.")
assert(destinationSlot >= 0, "Move destination slot must be positive.")
assert(count >= 0, "Amount of elements to move be positive.")
assert(sourceSlot + count <= self.capacity, "Cannot move elements beyond source buffer capacity.")
assert(destinationSlot + count <= newHandle.capacity, "Cannot move elements beyond destination buffer capacity.")
self.assertMutable()
newHandle.assertMutable()
newHandle.keys.advanced(by: destinationSlot)
.moveInitialize(from: self.keys.advanced(by: sourceSlot), count: count)
newHandle.values.advanced(by: destinationSlot)
.moveInitialize(from: self.values.advanced(by: sourceSlot), count: count)
}
/// Moves children from the current handle to a new handle
/// - Parameters:
/// - newHandle: The destination handle to write to which could be the same
/// as the source to move within a handle.
/// - sourceSlot: The offset of the source handle to move from.
/// - destinationSlot: The offset of the destintion handle to write to.
/// - count: The amount of values to move
/// - Warning: This does not adjust the buffer counts.
/// - Warning: This will trap if either the source and destination handles are leaves.
@inlinable
@inline(__always)
internal func moveChildren(
toHandle newHandle: _Node.UnsafeHandle,
fromSlot sourceSlot: Int,
toSlot destinationSlot: Int,
count: Int
) {
assert(sourceSlot >= 0, "Move source slot must be positive.")
assert(destinationSlot >= 0, "Move destination slot must be positive.")
assert(count >= 0, "Amount of children to move be positive.")
assert(sourceSlot + count <= self.capacity + 1, "Cannot move children beyond source buffer capacity.")
assert(destinationSlot + count <= newHandle.capacity + 1, "Cannot move children beyond destination buffer capacity.")
assert(!newHandle.isLeaf, "Cannot move children to a leaf node")
assert(!self.isLeaf, "Cannot move chidlren from a leaf node")
self.assertMutable()
newHandle.assertMutable()
newHandle.children.unsafelyUnwrapped.advanced(by: destinationSlot)
.moveInitialize(from: self.children.unsafelyUnwrapped.advanced(by: sourceSlot), count: count)
}
/// Inserts a new element somewhere into the handle.
/// - Parameters:
/// - element: The element to insert which the node will take ownership of.
/// - slot: An uninitialized slot in the buffer to insert the element into.
/// - Warning: This does not adjust the buffer counts.
@inlinable
@inline(__always)
internal func setElement(_ element: _Node.Element, withRightChild rightChild: _Node?, at slot: Int) {
assertMutable()
assert(slot < self.capacity, "Cannot insert beyond node capacity.")
assert(self.isLeaf == (rightChild == nil), "A child can only be inserted iff the node is a leaf.")
self.keys.advanced(by: slot).initialize(to: element.key)
self.values.advanced(by: slot).initialize(to: element.value)
if let rightChild = rightChild {
self.children.unsafelyUnwrapped.advanced(by: slot + 1).initialize(to: rightChild)
}
}
/// Moves an element out of the handle and returns it.
///
/// This may leave a hold within the node's buffer so it is critical to ensure that
/// it is filled, either by inserting a new element or some other operation.
///
/// - Parameter slot: The in-bounds slot of an element to move out
/// - Returns: A tuple of the key and value.
/// - Warning: This does not adjust buffer counts
@inlinable
@inline(__always)
internal func moveElement(at slot: Int) -> _Node.Element {
assertMutable()
assert(slot < self.numElements, "Attempted to move out-of-bounds element.")
return (
key: self.keys.advanced(by: slot).move(),
value: self.values.advanced(by: slot).move()
)
}
/// Recomputes the total amount of elements in two nodes.
///
/// Use this to recompute the tracked total element counts for the current node when it
/// splits. This performs a shallow recalculation, assuming that its children's counts are
/// already accurate.
///
/// - Parameter rightHandle: A handle to the right-half of the split.
@inlinable
@inline(__always)
internal func recomputeTotalElementCount(withRightSplit rightHandle: _Node.UnsafeHandle) {
assertMutable()
let originalTotalElements = self.numTotalElements
var totalChildElements = 0
if !self.isLeaf {
// Calculate total amount of child elements
// TODO: potentially evaluate min(left.children, right.children),
// but the cost of the branch will likely exceed the cost of 1 copmarison
for i in 0..<self.numChildren {
totalChildElements += self[childAt: i].storage.header.totalElements
}
}
assert(totalChildElements >= 0, "Cannot have negative number of child elements.")
self.numTotalElements = self.numElements + totalChildElements
rightHandle.numTotalElements = originalTotalElements - self.numTotalElements
checkInvariants()
}
/// Removes a key-value pair from a given slot within the node. This is assumed to
/// run on a leaf.
///
/// - Parameter slot: The slot to remove which must be in-bounds.
/// - Returns: The element that was removed..
/// - Warning: This does not perform any balancing or rotation.
@inlinable
@inline(__always)
internal func removeElement(at slot: Int) -> _Node.Element {
assertMutable()
assert(self.isLeaf, "Attempt to call removeElement(at:) on a leaf.")
assert(slot < self.numElements, "Attempt to remove out-of-bounds element.")
let element = self.moveElement(at: slot)
// Shift everything else over to the left
self.moveElements(
toHandle: self,
fromSlot: slot + 1,
toSlot: slot,
count: self.numElements - slot - 1
)
self.numElements -= 1
self.numTotalElements -= 1
return element
}
// TODO: see if this optimizes neatly to getrid of memmove
/// Removes the last key-value pair from the node. This is assumed to run on a
/// non-empty leaf.
@inlinable
@inline(__always)
internal func popElement() -> _Node.Element {
return self.removeElement(at: self.numElements - 1)
}
}
// MARK: Tree-Wise Operations
extension _Node.UnsafeHandle {
@usableFromInline
internal typealias ElementReference = (handle: _Node.UnsafeHandle, slot: Int)
// TODO: see if these closures optimize well
/// Obtains a handle to the node's immediate predecessor. If a predecessor
/// does not exist, the closure recieves a `nil` parameter.
// @inlinable
// @inline(__always)
// internal func withPredecessor<R>(
// of slot: Int,
// _ body: (ElementReference?) -> R
// ) -> R {
// assert(slot < self.numElements, "Cannot get predecessor for out-of-bounds slot.")
//
// var currentNode = self
//
// return body(nil)
// }
}
+152
View File
@@ -0,0 +1,152 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@usableFromInline
internal struct _Node<Key: Comparable, Value> {
@usableFromInline
typealias Element = (key: Key, value: Value)
/// Strong reference to the node's underlying data
@usableFromInline
internal var storage: Storage
/// Creates a node wrapping a Storage object in order to interact with it.
/// - Parameter storage: Underlying node storage.
@inlinable
@inline(__always)
internal init(_ storage: Storage) {
self.storage = storage
}
/// Creates a node which copies the storage of an existing node.
@inlinable
@inline(__always)
internal init(copyingFrom oldNode: _Node) {
let capacity = oldNode.storage.header.capacity
let count = oldNode.storage.header.count
let totalElements = oldNode.storage.header.totalElements
let isLeaf = oldNode.storage.header.children == nil
self.init(withCapacity: capacity, isLeaf: isLeaf)
self.storage.header.count = count
self.storage.header.totalElements = totalElements
oldNode.storage.withUnsafeMutablePointerToElements { oldKeys in
self.storage.withUnsafeMutablePointerToElements { newKeys in
newKeys.initialize(from: oldKeys, count: count)
}
}
oldNode.storage.header.values.withUnsafeMutablePointerToElements { oldValues in
self.storage.header.values.withUnsafeMutablePointerToElements { newValues in
newValues.initialize(from: oldValues, count: count)
}
}
oldNode.storage.header.children?.withUnsafeMutablePointerToElements { oldChildren in
self.storage.header.children!.withUnsafeMutablePointerToElements { newChildren in
newChildren.initialize(from: oldChildren, count: count + 1)
}
}
}
/// Creates and allocates a new node.
/// - Parameters:
/// - capacity: the maximum potential size of the node.
/// - isLeaf: whether or not the node is a leaf (it does not have any children).
@inlinable
internal init(withCapacity capacity: Int, isLeaf: Bool) {
let storage = Storage.create(minimumCapacity: capacity) { _ in
Header(
capacity: capacity,
count: 0,
totalElements: 0,
values: Buffer<Value>.create(minimumCapacity: capacity) { _ in BufferHeader() },
children: isLeaf ? nil
: Buffer<_Node<Key, Value>>.create(minimumCapacity: capacity + 1) { _ in BufferHeader() }
)
}
self.storage = unsafeDowncast(storage, to: Storage.self)
}
}
// MARK: CoW
extension _Node {
/// Allows **read-only** access to the underlying data behind the node.
///
/// - Parameter body: A closure with a handle which allows interacting with the node
/// - Returns: The value the closure body returns, if any.
@inlinable
@inline(__always)
internal func read<R>(_ body: (UnsafeHandle) throws -> R) rethrows -> R {
return try self.storage.withUnsafeMutablePointers { header, keys in
try header.pointee.values.withUnsafeMutablePointerToElements { values in
if let childrenPtr = header.pointee.children {
return try childrenPtr.withUnsafeMutablePointerToElements { children in
let handle = UnsafeHandle(
keys: keys,
values: values,
children: children,
header: header,
isMutable: false
)
return try body(handle)
}
} else {
let handle = UnsafeHandle(
keys: keys,
values: values,
children: nil,
header: header,
isMutable: false
)
return try body(handle)
}
}
}
}
/// Allows mutable access to the underlying data behind the node.
///
/// - Parameter body: A closure with a handle which allows interacting with the node
/// - Returns: The value the closure body returns, if any.
@inlinable
@inline(__always)
internal mutating func update<R>(_ body: (UnsafeHandle) throws -> R) rethrows -> R {
self.ensureUnique()
return try self.read { handle in
defer { handle.checkInvariants() }
return try body(UnsafeHandle(mutableCopyOf: handle))
}
}
/// Ensure that this storage refers to a uniquely held buffer by copying
/// elements if necessary.
@inlinable
@inline(__always)
internal mutating func ensureUnique() {
if !isKnownUniquelyReferenced(&self.storage) {
self = _Node(copyingFrom: self)
}
}
}
// MARK: Equatable
extension _Node: Equatable {
@inlinable
@inline(__always)
internal static func ==(lhs: _Node, rhs: _Node) -> Bool {
return lhs.storage === rhs.storage
}
}
@@ -0,0 +1,89 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: BidirectionalCollection {
/// The number of elements in the sorted dictionary.
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var count: Int { self._root.count }
/// A Boolean value that indicates whether the dictionary is empty.
@inlinable
@inline(__always)
public var isEmpty: Bool { self._root.isEmpty }
/// The position of the first element in a nonempty dictionary.
///
/// If the collection is empty, `startIndex` is equal to `endIndex`.
///
/// - Complexity: O(`log n`)
@inlinable
@inline(__always)
public var startIndex: Index { Index(self._root.startIndex) }
/// The dictionary's "past the end" position---that is, the position one
/// greater than the last valid subscript argument.
///
/// If the collection is empty, `endIndex` is equal to `startIndex`.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public var endIndex: Index { Index(self._root.endIndex) }
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return self._root.distance(from: start._index, to: end._index)
}
@inlinable
public func formIndex(after index: inout Index) {
index._index.ensureValid(for: self._root)
self._root.formIndex(after: &index._index)
}
@inlinable
public func index(after index: Index) -> Index {
index._index.ensureValid(for: self._root)
return Index(self._root.index(after: index._index))
}
@inlinable
public func formIndex(before index: inout Index) {
index._index.ensureValid(for: self._root)
self._root.formIndex(before: &index._index)
}
@inlinable
public func index(before index: Index) -> Index {
index._index.ensureValid(for: self._root)
return Index(self._root.index(before: index._index))
}
@inlinable
public func formIndex(_ i: inout Index, offsetBy distance: Int) {
i._index.ensureValid(for: self._root)
self._root.formIndex(&i._index, offsetBy: distance)
}
@inlinable
public func index(_ i: Index, offsetBy distance: Int) -> Index {
i._index.ensureValid(for: self._root)
return Index(self._root.index(i._index, offsetBy: distance))
}
@inlinable
public subscript(position: Index) -> Element {
position._index.ensureValid(for: self._root)
return self._root[position._index]
}
}
@@ -0,0 +1,21 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: CustomReflectable {
// TODO: Review this implementation
// TODO: Implement nice playground output.
/// The custom mirror for this instance.
public var customMirror: Mirror {
// TODO: instead of Array(self), implement a Element view?
Mirror(self, unlabeledChildren: Array(self), displayStyle: .dictionary)
}
}
@@ -0,0 +1,49 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: CustomStringConvertible, CustomDebugStringConvertible {
// TODO: see if there is way to reduce boilerplate here
@inlinable
public var description: String {
if isEmpty { return "[:]" }
var result = "["
var first = true
for (key, value) in self {
if first {
first = false
} else {
result += ", "
}
result += "\(key): \(value)"
}
result += "]"
return result
}
@inlinable
public var debugDescription: String {
if isEmpty { return "[:]" }
var result = "["
var first = true
for (key, value) in self {
if first {
first = false
} else {
result += ", "
}
debugPrint(key, value, separator: ": ", terminator: "", to: &result)
}
result += "]"
return result
}
}
@@ -0,0 +1,34 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: Equatable where Value: Equatable {
// TODO: look into more efficient ways to implement this
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is false.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
/// - Complexity: O(`n log n`)
@inlinable
public static func ==(lhs: SortedDictionary<Key, Value>, rhs: SortedDictionary<Key, Value>) -> Bool {
if lhs.count != rhs.count { return false }
for ((k1, v1), (k2, v2)) in zip(lhs, rhs) {
if k1 != k2 || v1 != v2 {
return false
}
}
return true
}
}
@@ -0,0 +1,33 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: ExpressibleByDictionaryLiteral {
/// Creates a new sorted dictionary from the contents of a dictionary
/// literal.
///
/// Duplicate elements in the literal are allowed, but the resulting
/// set will only contain the first occurrence of each.
///
/// Do not call this initializer directly. It is used by the compiler when you
/// use a dictionary literal. Instead, create a new ordered dictionary using a
/// dictionary literal as its value by enclosing a comma-separated list of
/// values in square brackets. You can use an array literal anywhere a set is
/// expected by the type context.
///
/// - Parameter elements: A variadic list of key-value pairs for the new
/// dictionary.
///
/// - Complexity: O(`n log n`)
@inlinable
public init(dictionaryLiteral elements: (Key, Value)...) {
self.init(uniqueKeysWithValues: elements)
}
}
@@ -0,0 +1,26 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: Hashable where Key: Hashable, Value: Hashable {
/// Hashes the essential components of this value by feeding them
/// into the givenhasher.
/// - Parameter hasher: The hasher to use when combining
/// the components of this instance.
/// - Complexity: O(`n log n`)
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(self.count)
for (key, value) in self {
hasher.combine(key)
hasher.combine(value)
}
}
}
@@ -0,0 +1,36 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary: Sequence {
// /// An iterator over the elements of the sorted dictionary
// public struct Iterator: IteratorProtocol {
// @usableFromInline
// internal var _iterator: _Tree.Iterator
//
// @inlinable
// internal init(_base: SortedDictionary) {
// self._iterator = _base._root.makeIterator()
// }
//
// @inlinable
// public mutating func next() -> Element? {
// return self._iterator.next()
// }
// }
//
// /// Returns an iterator over the elements of the sorted dictionary.
// ///
// /// - Complexity: O(1)
// @inlinable
// public __consuming func makeIterator() -> Iterator {
// return Iterator(_base: self)
// }
//}
@@ -0,0 +1,54 @@
//===----------------------------------------------------------------------===//
//
// 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 SortedDictionary {
/// Returns the index for a given key, if it exists
/// - Complexity: O(`log n`)
@inlinable
public func index(forKey key: Key) -> Index? {
if let index = self._root.anyIndex(forKey: key) {
return Index(index)
} else {
return nil
}
}
/// The position of an element within a sorted dictionary
public struct Index {
@usableFromInline
internal var _index: _Tree.Index
@inlinable
@inline(__always)
internal init(_ _index: _Tree.Index) {
self._index = _index
}
}
}
// MARK: Equatable
extension SortedDictionary.Index: Equatable {
// TODO: Potentially validate if lhs & rhs aren't pointing to deallocated dictionaries.
@inlinable
public static func ==(lhs: SortedDictionary.Index, rhs: SortedDictionary.Index) -> Bool {
lhs._index.ensureValid(with: rhs._index)
return lhs._index == rhs._index
}
}
// MARK: Comparable
extension SortedDictionary.Index: Comparable {
@inlinable
public static func <(lhs: SortedDictionary.Index, rhs: SortedDictionary.Index) -> Bool {
lhs._index.ensureValid(with: rhs._index)
return lhs._index < rhs._index
}
}
@@ -0,0 +1,141 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// A collection which maintains key-value pairs in ascending sorted order.
///
/// A sorted dictionary is a type of tree, providing efficient read and write operations
/// to the entries it contains. Each entry in the sorted dictionary is identified using a
/// key, which is a comparable type such as a string or number. You can use that key
/// to retrieve the corresponding value.
public struct SortedDictionary<Key: Comparable, Value> {
/// An element of the sorted dictionary. A key-value tuple.
public typealias Element = (key: Key, value: Value)
@usableFromInline
internal typealias _Tree = _BTree<Key, Value>
@usableFromInline
internal var _root: _Tree
/// Creates an empty dictionary.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public init() {
self._root = _Tree()
}
/// Creates a dictionary rooted at a given BTree.
@inlinable
internal init(_rootedAt tree: _Tree) {
self._root = tree
}
/// Creates a dictionary from a sequence of key-value pairs which must
/// be unique.
/// - Complexity: O(`n log n`)
@inlinable
@inline(__always)
public init<S>(
uniqueKeysWithValues keysAndValues: S
) where S: Sequence, S.Element == Element {
self.init()
for (key, value) in keysAndValues {
self._root.setAnyValue(value, forKey: key)
}
}
}
// MARK: Mutations
extension SortedDictionary {
/// Updates the value stored in the dictionary for the given key, or
/// adds a new key-value pair if the key does not exist.
///
/// Use this method instead of key-based subscripting when you need to
/// know whether the new value supplants the value of an existing key. If
/// the value of an existing key is updated, `updateValue(_:forKey:)` returns
/// the original value.
///
/// - Parameters:
/// - value: The new value to add to the dictionary.
/// - key: The key to associate with value. If key already exists in the
/// dictionary, value replaces the existing associated value. If key
/// isn’t already a key of the dictionary, the (key, value) pair is added.
/// - Returns: The value that was replaced, or nil if a new key-value pair was added.
/// - Complexity: O(`log n`)
@inlinable
@discardableResult
public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? {
return self._root.setAnyValue(value, forKey: key)
}
}
// MARK: Subscripts
extension SortedDictionary {
/// Accesses the value associated with the key for both read and write operations
///
/// This key-based subscript returns the value for the given key if the key is found in
/// the dictionary, or nil if the key is not found.
///
/// When you assign a value for a key and that key already exists, the dictionary overwrites
/// the existing value. If the dictionary doesn’t contain the key, the key and value are added
/// as a new key-value pair.
///
/// - Parameter key: The key to find in the dictionary.
/// - Returns: The value associated with key if key is in the dictionary; otherwise, nil.
/// - Complexity: O(`log n`)
@inlinable
@inline(__always)
public subscript(key: Key) -> Value? {
get {
return self._root.anyValue(for: key)
}
// TODO: implement _modify
mutating set {
if let newValue = newValue {
self._root.setAnyValue(newValue, forKey: key)
} else {
// TODO: Removal
self._root.removeAny(key: key)
}
}
}
/// Accesses the value with the given key. If the dictionary doesn’t contain the given
/// key, accesses the provided default value as if the key and default value existed
/// in the dictionary.
///
/// Use this subscript when you want either the value for a particular key or, when that
/// key is not present in the dictionary, a default value.
///
/// - Parameters:
/// - key: The key the look up in the dictionary.
/// - defaultValue: The default value to use if key doesn’t exist in the dictionary.
/// - Returns: The value associated with key in the dictionary; otherwise, defaultValue.
/// - Complexity: O(`log n`)
@inlinable
@inline(__always)
public subscript(
key: Key, default defaultValue: @autoclosure () -> Value
) -> Value {
get {
return self[key] ?? defaultValue()
}
mutating set {
self[key] = newValue
}
}
}
@@ -0,0 +1,12 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import Foundation
@@ -0,0 +1,12 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//