Final touch up, polishes, and optimizations.

Key Changes:
 - Add duplicate handling functionality to _BTree.Builder
 - Remove transient allocation in SortedDictionary.values _modify
 - Add missing SortedDictionary.Values.subscript _modify
 - Add SortedSet(sortedElements:)
 - Add optimized SetAlgebra implementations
 - Remove remaining high-level offset APIs
 - Various optimizations
 - Expand internal documentation

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

Optimizations:
 - Use dummy node for transient _modify state rather than allocating new buffer
This commit is contained in:
Vihan Bhargava committed 2021-08-19 00:02:17 -07:00
1 parent e67460c942
commit cf672265c7
30 files changed
+691 -282

No files matched your search

@@ -132,6 +132,20 @@
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "SortedCollections"
BuildableName = "SortedCollections"
BlueprintName = "SortedCollections"
ReferencedContainer = "container:">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
@@ -180,6 +194,16 @@
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "SortedCollectionsTests"
BuildableName = "SortedCollectionsTests"
BlueprintName = "SortedCollectionsTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
@@ -58,12 +58,22 @@
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "SortedCollectionsTests"
BuildableName = "SortedCollectionsTests"
BlueprintName = "SortedCollectionsTests"
ReferencedContainer = "container:">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
buildConfiguration = "Release"
selectedDebuggerIdentifier = ""
selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
@@ -80,6 +90,32 @@
ReferencedContainer = "container:">
</BuildableReference>
</BuildableProductRunnable>
<CommandLineArguments>
<CommandLineArgument
argument = "run"
isEnabled = "YES">
</CommandLineArgument>
<CommandLineArgument
argument = "-f"
isEnabled = "YES">
</CommandLineArgument>
<CommandLineArgument
argument = "SortedDictionary.*init"
isEnabled = "YES">
</CommandLineArgument>
<CommandLineArgument
argument = "/Users/vihan/Documents/swift-collections/output"
isEnabled = "YES">
</CommandLineArgument>
<CommandLineArgument
argument = "--mode"
isEnabled = "YES">
</CommandLineArgument>
<CommandLineArgument
argument = "replace-all"
isEnabled = "YES">
</CommandLineArgument>
</CommandLineArguments>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
@@ -26,7 +26,7 @@ extension _BTree: BidirectionalCollection {
@inline(__always)
internal var isEmpty: Bool { self.count == 0 }
// TODO: look into O(1) implementation
// TODO: further consider O(1) implementation
/// Locates the first element and returns a proper path to it, or nil if the BTree is empty.
/// - Complexity: O(`log n`)
@inlinable
@@ -92,6 +92,8 @@ extension _BTree: BidirectionalCollection {
precondition(index.offset < self.count,
"Attempt to advance out of collection bounds.")
// TODO: this might be redundant given the fact the same (but generalized)
// logic is implemented in offsetBy
let shouldSeekWithinLeaf = index.readNode {
$0.isLeaf && _fastPath(index.slot + 1 < $0.elementCount)
}
@@ -123,7 +125,6 @@ extension _BTree: BidirectionalCollection {
internal func formIndex(before index: inout Index) {
precondition(!self.isEmpty && index.offset != 0,
"Attempt to advance out of collection bounds.")
// TODO: implement more efficient logic to better move through the tree
self.formIndex(&index, offsetBy: -1)
}
@@ -19,7 +19,6 @@ extension _BTree {
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> _BTree {
// TODO: optimize implementation to O(n)
var builder = Builder()
for element in self where try isIncluded(element) {
builder.append(element)
@@ -94,7 +94,6 @@ extension _BTree: Sequence {
return
}
// TODO: maybe convert to unowned(unsafe)
var nextNode: Unmanaged? = .passUnretained(tree.root.storage)
while let node = nextNode {
self.path.append(node)
@@ -1,18 +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 _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)
}
}
@@ -379,15 +379,73 @@ extension _BTree {
/// This 'consumes' the tree, however it expects the callee to retain the root of the tree for the duration of
/// the cursors lifetime.
///
/// - Parameters:
/// - key: The key to search for
/// - mutable: whether a mutable cursor should be returned.
/// - Parameter key: The key to search for
/// - Returns: A `cursor` to the key or where the key should be inserted, and a `found`
/// parameter indicating whether or not the key exists within the tree, iff `found` is true, the cursor
/// is concrete.
/// - Complexity: O(`log n`)
@inlinable
internal mutating func findAnyCursor(
internal mutating func takeCursor(at index: Index) -> UnsafeCursor {
var slots = index.childSlots
slots.append(UInt16(index.slot))
// Initialize parents with some dummy value filling it.
var parents =
UnsafeCursor.Path(repeating: .passUnretained(self.root.storage))
var ownedRoot: Node.Storage
do {
var tempRoot: Node.Storage? = nil
swap(&tempRoot, &self.root._storage)
ownedRoot = tempRoot.unsafelyUnwrapped
}
var node: Unmanaged<Node.Storage> = .passUnretained(ownedRoot)
// The depth containing the first instance of a shared
var lastUniqueDepth = isKnownUniquelyReferenced(&ownedRoot) ? 0 : -1
var isOnUniquePath = isKnownUniquelyReferenced(&ownedRoot)
for d in 0..<index.childSlots.depth {
node._withUnsafeGuaranteedRef { storage in
storage.read { handle in
parents.append(node)
let slot = Int(index.childSlots[d])
node = .passUnretained(handle[childAt: slot].storage)
if isOnUniquePath && handle.isChildUnique(atSlot: slot) {
lastUniqueDepth += 1
} else {
isOnUniquePath = false
}
}
}
}
parents.append(node)
let cursor = UnsafeCursor(
root: ownedRoot,
slots: slots,
path: parents,
lastUniqueDepth: lastUniqueDepth
)
return cursor
}
/// Obtains a cursor to a given element in the tree.
///
/// This 'consumes' the tree, however it expects the callee to retain the root of the tree for the duration of
/// the cursors lifetime.
///
/// - Parameter key: The key to search for
/// - Returns: A `cursor` to the key or where the key should be inserted, and a `found`
/// parameter indicating whether or not the key exists within the tree, iff `found` is true, the cursor
/// is concrete.
/// - Complexity: O(`log n`)
@inlinable
internal mutating func takeCursor(
forKey key: Key
) -> (cursor: UnsafeCursor, found: Bool) {
var slots = Index.Offsets(repeating: 0)
@@ -12,6 +12,10 @@
extension _BTree {
/// Provides an interface for efficiently constructing a filled B-Tree from sorted data.
///
/// A builder supports duplicate keys, in which case they are inserted in the same order they are recieved.
/// However, is the `deduplicating` parameter is passed as `true`, operations will silently drop
/// duplicates.
///
/// This type has a few advantages when constructing a B-Tree over other approaches such as manually
/// inserting each element or using a cursor:
///
@@ -101,11 +105,19 @@ extension _BTree {
@usableFromInline
internal let internalCapacity: Int
@usableFromInline
internal let deduplicating: Bool
@usableFromInline
internal var lastKey: Key?
/// Creates a new B-Tree builder with default capacities
/// - Parameter deduplicating: Whether duplicates should be removed.
@inlinable
@inline(__always)
internal init() {
internal init(deduplicating: Bool = false) {
self.init(
deduplicating: deduplicating,
leafCapacity: _BTree.defaultLeafCapacity,
internalCapacity: _BTree.defaultInternalCapacity
)
@@ -113,19 +125,27 @@ extension _BTree {
/// Creates a new B-Tree builder with a custom uniform capacity configuration
/// - Parameters:
/// - deduplicating: Whether duplicates should be removed.
/// - capacity: The amount of elements per node.
@inlinable
@inline(__always)
internal init(capacity: Int) {
self.init(leafCapacity: capacity, internalCapacity: capacity)
internal init(deduplicating: Bool = false, capacity: Int) {
self.init(
deduplicating: deduplicating,
leafCapacity: capacity,
internalCapacity: capacity
)
}
/// Creates a new B-Tree builder with a custom capacity configuration
/// - Parameters:
/// - capacity: The amount of elements per node.
/// - deduplicating: Whether duplicates should be removed.
/// - leafCapacity: The amount of elements per leaf node.
/// - internalCapacity: The amount of elements per internal node.
@inlinable
@inline(__always)
internal init(
deduplicating: Bool = false,
leafCapacity: Int,
internalCapacity: Int
) {
@@ -138,6 +158,8 @@ extension _BTree {
self._seedling = Node(withCapacity: leafCapacity, isLeaf: true)
self.leafCapacity = leafCapacity
self.internalCapacity = internalCapacity
self.deduplicating = deduplicating
self.lastKey = nil
}
/// Pops a sapling and it's associated seperator
@@ -176,8 +198,16 @@ extension _BTree {
/// Appends a new element to the tree
/// - Parameter element: Element which is after all previous elements in sorted order.
@inlinable
@inline(__always)
internal mutating func append(_ element: __owned Element) {
assert(lastKey == nil || lastKey! <= element.key,
"New element must be non-decreasing.")
defer { lastKey = element.key }
if deduplicating {
if let lastKey = lastKey {
if lastKey == element.key { return }
}
}
switch state {
case .addingSeperator:
completeSeedling(withSeperator: element)
@@ -200,7 +230,6 @@ extension _BTree {
/// Declares that the current seedling is finished with insertion and creates a new seedling to
/// further operate on.
@inlinable
@inline(__always)
internal mutating func completeSeedling(
withSeperator newSeperator: __owned Element
) {
@@ -311,7 +340,6 @@ extension _BTree {
///
/// - Returns: A usable, fully-filled B-Tree
@inlinable
@inline(__always)
internal mutating func finish() -> _BTree {
var root: Node = seedling
_seedling = nil
@@ -331,3 +359,12 @@ extension _BTree {
}
}
}
extension _BTree.Builder where Value == Void {
/// Appends a value to a B-Tree builder without values.
@inlinable
@inline(__always)
internal mutating func append(_ key: __owned Key) {
self.append((key, ()))
}
}
+38 -9
View File
@@ -19,9 +19,6 @@
@usableFromInline
internal struct _BTree<Key: Comparable, Value> {
// TODO: decide node capacity. Currently exploring 470 v 1050
// TODO: better benchmarking here
/// Internal node size in bytes for B-Tree
@inlinable
@inline(__always)
@@ -72,6 +69,19 @@ internal struct _BTree<Key: Comparable, Value> {
@usableFromInline
internal var version: Int
/// Creates a dummy B-Tree with no underlying node storage class.
///
/// It is invalid and a serious error to ever attempt to read or write to such a B-Tree.
@inlinable
@inline(__always)
internal static var dummy: _BTree {
_BTree(
_rootedAtNode: _Node.dummy,
internalCapacity: 0,
version: 0
)
}
/// Creates an empty B-Tree with an automatically determined optimal capacity.
@inlinable
@inline(__always)
@@ -91,7 +101,7 @@ internal struct _BTree<Key: Comparable, Value> {
)
}
/// Creates an empty BTree which creates node with specified capacities
/// Creates an empty B-Tree 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
@@ -105,7 +115,7 @@ internal struct _BTree<Key: Comparable, Value> {
)
}
/// Creates a BTree rooted at a specific nodey
/// Creates a B-Tree rooted at a specific nodey
/// - Parameters:
/// - root: The root node.
/// - internalCapacity: The key capacity of new internal nodes.
@@ -116,6 +126,18 @@ internal struct _BTree<Key: Comparable, Value> {
self.internalCapacity = internalCapacity
self.version = ObjectIdentifier(root.storage).hashValue
}
@inlinable
@inline(__always)
internal init(
_rootedAtNode root: Node,
internalCapacity: Int,
version: Int
) {
self.root = root
self.internalCapacity = internalCapacity
self.version = version
}
}
// MARK: Mutating Operations
@@ -196,7 +218,9 @@ extension _BTree {
invalidateIndices()
defer { self.checkInvariants() }
// TODO: Don't create CoW copy until needed.
// TODO: It is possible that there is a single transient CoW copied made
// if the removal results in the CoW copied node being completely removed
// from the tree.
let removedElement = self.root.update { $0.removeAnyElement(forKey: key) }
// Check if the tree height needs to be reduced
@@ -311,23 +335,30 @@ extension _BTree {
internal func findAnyIndex(forKey key: Key) -> Index? {
var childSlots = Index.Offsets(repeating: 0)
var node: Unmanaged? = .passUnretained(self.root.storage)
var offset: Int = 0
while let currentNode = node {
let index: Index? = currentNode._withUnsafeGuaranteedRef { storage in
storage.read { handle in
let keySlot = handle.startSlot(forKey: key)
offset += keySlot
if keySlot < handle.elementCount && handle[keyAt: keySlot] == key {
return Index(
node: .passUnretained(storage),
slot: keySlot,
childSlots: childSlots,
offset: 0,
offset: offset,
forTree: self
)
} else {
if handle.isLeaf {
node = nil
} else {
for i in 0..<keySlot {
offset += handle[childAt: i].storage.header.subtreeCount
}
childSlots.append(UInt16(keySlot))
node = .passUnretained(handle[childAt: keySlot].storage)
}
@@ -399,7 +430,6 @@ extension _BTree {
}
}
// TODO: convert into debug-only preconditionFaliure
preconditionFailure("In-bounds index not found within tree.")
})
}
@@ -538,7 +568,6 @@ extension _BTree {
public func mapValues<T>(
_ transform: (Value) throws -> T
) rethrows -> _BTree<Key, T> {
// TODO: explore forEach vs iteration speed
let root = try _Node<Key, T>(
mappingFrom: self.root,
transform
@@ -17,98 +17,100 @@
/// do not put non-trivial types in this.
@usableFromInline
internal struct _FixedSizeArray<Element> {
@inlinable
@inline(__always)
internal static var maxSize: Int8 { 16 }
@usableFromInline
internal var depth: Int8
@usableFromInline
internal var values: (
Element, Element, Element, Element,
Element, Element, Element, Element,
Element, Element, Element, Element,
Element, Element, Element, Element
@inlinable
@inline(__always)
internal static var maxSize: Int8 { 16 }
@usableFromInline
internal var depth: Int8
@usableFromInline
internal var values: (
Element, Element, Element, Element,
Element, Element, Element, Element,
Element, Element, Element, Element,
Element, Element, Element, Element
)
@inlinable
@inline(__always)
internal init(repeating initialValue: Element, depth: Int8 = 0) {
self.depth = depth
self.values = (
initialValue, initialValue, initialValue, initialValue,
initialValue, initialValue, initialValue, initialValue,
initialValue, initialValue, initialValue, initialValue,
initialValue, initialValue, initialValue, initialValue
)
@inlinable
@inline(__always)
internal init(repeating initialValue: Element, depth: Int8 = 0) {
self.depth = depth
self.values = (
initialValue, initialValue, initialValue, initialValue,
initialValue, initialValue, initialValue, initialValue,
initialValue, initialValue, initialValue, initialValue,
initialValue, initialValue, initialValue, initialValue
)
}
/// Appends a value to the offset list
@inlinable
@inline(__always)
internal mutating func append(_ value: __owned Element) {
assert(depth < _FixedSizeArray.maxSize,
"Out of bounds access in fixed sized array.")
defer { self.depth &+= 1 }
self[self.depth] = value
}
/// Pops a value from the end of offset list
@inlinable
@inline(__always)
internal mutating func pop() -> Element {
assert(depth > 0, "Cannot pop empty fixed sized array")
self.depth &-= 1
return self[self.depth]
}
/// If the fixed size array is empty
@inlinable
@inline(__always)
internal var isEmpty: Bool { depth == 0 }
/// Refers to the last value in the list
@inlinable
@inline(__always)
internal var last: Element {
get {
assert(depth > 0, "Out of bounds access in fixed sized array")
return self[depth &- 1]
}
/// Appends a value to the offset list
@inlinable
@inline(__always)
internal mutating func append(_ value: __owned Element) {
assert(depth < _FixedSizeArray.maxSize,
_modify {
assert(depth > 0, "Out of bounds access in fixed sized array")
yield &self[depth &- 1]
}
}
@inlinable
@inline(__always)
internal subscript(_ position: Int8) -> Element {
get {
assert(position <= depth && depth <= _FixedSizeArray.maxSize,
"Out of bounds access in fixed sized array.")
defer { self.depth &+= 1 }
self[self.depth] = value
return withUnsafeBytes(of: self.values) { values in
let p = values.baseAddress!.assumingMemoryBound(to: Element.self)
return p.advanced(by: Int(position)).pointee
}
}
/// Pops a value from the end of offset list
@inlinable
@inline(__always)
internal mutating func pop() -> Element {
assert(depth > 0, "Cannot pop empty fixed sized array")
self.depth &-= 1
return self[self.depth]
}
/// If the fixed size array is empty
@inlinable
@inline(__always)
internal var isEmpty: Bool { depth == 0 }
/// Refers to the last value in the list
@inlinable
@inline(__always)
internal var last: Element {
get {
assert(depth > 0, "Out of bounds access in fixed sized array")
return self[depth - 1]
_modify {
assert(position <= depth && depth <= _FixedSizeArray.maxSize,
"Out of bounds access in fixed sized array.")
let ptr: UnsafeMutablePointer<Element> =
withUnsafeMutableBytes(of: &self.values) { values in
let p = values.baseAddress!.assumingMemoryBound(to: Element.self)
return p.advanced(by: Int(position))
}
_modify {
yield &self[depth - 1]
}
}
@inlinable
internal subscript(_ position: Int8) -> Element {
get {
assert(position <= depth && depth <= _FixedSizeArray.maxSize,
"Out of bounds access in fixed sized array.")
return withUnsafeBytes(of: self.values) { values in
let p = values.baseAddress!.assumingMemoryBound(to: Element.self)
return p.advanced(by: Int(position)).pointee
}
}
_modify {
assert(position <= depth && depth <= _FixedSizeArray.maxSize,
"Out of bounds access in fixed sized array.")
let ptr: UnsafeMutablePointer<Element> =
withUnsafeMutableBytes(of: &self.values) { values in
let p = values.baseAddress!.assumingMemoryBound(to: Element.self)
return p.advanced(by: Int(position))
}
var value = ptr.move()
defer { ptr.initialize(to: value) }
yield &value
}
var value = ptr.move()
defer { ptr.initialize(to: value) }
yield &value
}
}
}
#if DEBUG
@@ -31,7 +31,16 @@ extension _Node {
self.depth = depth
}
// Packed integer to store all node counts.
/// Packed integer to store all node counts.
///
/// This is represented as:
///
/// subtreeCount
/// vvvvvvv
/// 0x0000000FFFFFFF00
/// ^^^^^^^ ^^
/// count depth
///
@usableFromInline
internal var _internalCounts: UInt64
@@ -86,7 +95,23 @@ extension _Node {
internal var children: UnsafeMutablePointer<_Node<Key, Value>>?
}
/// Represents the underlying data for a node in the heap.
/// Represents the underlying data for a node.
///
/// Generally, this shouldn't be directly accessed. However, in performance-critical code where operating
/// on a ``_Node`` may create unwanted ARC traffic, or other concern, this provides a few low-level
/// and unsafe APIs for operations.
///
/// A node contains a tail-allocated contiguous buffer of keys, and also may maintain pointers to buffers
/// for the corresponding values and children.
///
/// There are two types of nodes distinguished "leaf" and "internal" nodes. Leaf nodes do not have a
/// buffer allocated for their children in the underlying storage class.
///
/// Additionally, a node does not have a value buffer allocated in some cases. Specifically, when the
/// value type is `Void`, no value buffer is allocated. ``_Node.hasValues`` can be used to check
/// whether a value buffer exists for a given set of generic parameters. Additionally, when a value buffer
/// does not exist, ``_Node.dummyValue`` can be used to obtain a valid value within the type system
/// that can be passed to APIs.
@usableFromInline
internal class Storage: ManagedBuffer<_Node.Header, Key> {
/// Allows **read-only** access to the underlying data behind the node.
@@ -108,7 +133,13 @@ extension _Node {
}
}
/// Allows **mutable** access to the underlying data behind the node.
/// Dangerously allows **mutable** access to the underlying data behind the node.
///
/// This does **not** perform CoW checks and so when calling this, one must be certain that the
/// storage class is indeed unique. Generally this is the wrong function to call, and should only be used
/// when the callee has created and is guaranteed to be the only owner during the execution of the
/// update callback, _and_ it has been identified that ``_Node.update(_:)`` or other alternatives
/// result in noticable slow-down.
///
/// - Parameter body: A closure with a handle which allows interacting with the node
/// - Returns: The value the closure body returns, if any.
@@ -121,7 +152,10 @@ extension _Node {
try self.read { try body(UnsafeHandle(mutating: $0)) }
}
/// Creates a new storage instance
/// Creates a new storage object.
///
/// It is generally recommend to use the ``_Node.init(withCapacity:, isLeaf:)``
/// initializer instead to create a new node.
@inlinable
@inline(__always)
internal static func create(
@@ -145,7 +179,9 @@ extension _Node {
return unsafeDowncast(storage, to: Storage.self)
}
/// Copies an existing storage to a new storage
/// Copies an existing storage to a new storage.
///
/// It is generally recommended to use the ``_Node.init(copyingFrom:)`` initializer.
@inlinable
@inline(__always)
internal func copy() -> Storage {
@@ -441,8 +441,7 @@ extension _Node.UnsafeHandle {
self.subtreeCount += 1
// TODO: might be more optimal to memcpy the right child, and avoid
// potentially creating a CoW copy of it. This will require more
// thinking
// potentially creating a CoW copy of it.
// Move the right child's elements into the left child
// ┌─┐
@@ -1,32 +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.UnsafeHandle: Equatable where Key: Equatable, Value: Equatable {
// /// Compares whether the subtree rooted at the following node is equatable to another node
// // TODO: optimized node equality checking is non-trivial
// @inlinable
// @inline(__always)
// internal static func ==(lhs: Self, rhs: Self) -> Bool {
// // Two nodes of varying sizes cannot be equal
// if lhs.subtreeCount != rhs.subtreeCount { return false }
//
// // If two nodes share the same header, they are by pointer identity the same
// // node.
// if lhs.header == rhs.header { return true }
//
//
// for i in 0..<lhs.elementCount {
//
// }
//
// // TODO: is it faster to compare the keys first or children first
// }
//}
@@ -58,7 +58,7 @@ extension _Node.UnsafeHandle {
if 0 < insertionIndex && insertionIndex <= self.elementCount &&
self[keyAt: insertionIndex - 1] == key {
if updatingKey {
// TODO: concerned about copy here
// TODO: Potential transient ARC traffic here.
let oldKey = self.keys.advanced(by: insertionIndex - 1).pointee
let oldValue: Value
@@ -264,7 +264,7 @@ extension _Node.UnsafeHandle {
rightChild: rightNode
)
} else {
// TODO: see if this can be simplified
// TODO: potentially extract out this logic to reduce code duplication.
// Shift over elements near the insertion slot.
self.moveInitializeElements(
count: self.elementCount - insertionSlot,
@@ -10,6 +10,32 @@
//===----------------------------------------------------------------------===//
extension _Node {
/// A handle allowing potentially mutable operations to be performed.
///
/// An ``UnsafeHandle`` should never be constructed directly. It is instead used when modifying a
/// node through its closure APIs, such as:
///
/// let nodeMedian = node.read { handle in
/// let medianSlot = handle.elementCount
/// return handle[elementAt: medianSlot]
/// }
///
/// The unsafe handle provides a variety of methods to ease operations on a node. This includes
/// low-level operations such as `moveElement(_:atSlot:)` or `pointerToValue(at:)` and
/// higher level operations such as `insertElement(_:)`.
///
/// There are two variants of an ``UnsafeHandle``. A mutable and immuable one.
/// ``_Node.update(_:)`` is an example of a method which vends a mutable unsafe handle. Only a
/// mutable unsafe handle can performed unsafe operations. This exists to ensure CoW-unsafe
/// operations are not performed.
///
/// Whene performing operations relating to children, it is important to know that not all nodes have
/// children, or a children buffer allocated. Check the ``isLeaf`` property before accessing any
/// properties or calling any methods which may interact with children.
///
/// Additionally, when performing operations on values, a value buffer may not always be allocated.
/// Check ``_Node.hasValues`` before performing such operations. Note that element-wise
/// operations of the handle already perform such value checks and this step is not necessary.
@usableFromInline
internal struct UnsafeHandle {
@usableFromInline
@@ -174,7 +200,6 @@ extension _Node {
internal var isFull: Bool { elementCount == capacity }
// TODO: see if deinitializer can add 0 element check for internal nodes.
/// Checks uniqueness of a child.
///
/// - Warning: Will trap if executed on leaf nodes
@@ -199,34 +224,11 @@ extension _Node {
self.header.pointee.children?.deallocate()
self.header.pointee.children = nil
}
// TODO: test performance between __consuming and passing UnsafeHandle as
// inout.
/// Converts a leaf node into an internal node, without adjusting its capacity.
/// - Returns: A new unsafe handle to operate on. The old node is still mutated.
@inlinable
@inline(__always)
internal __consuming func convertToInternalNode() -> UnsafeHandle {
assertMutable()
assert(self.isLeaf, "Already internal node.")
let children: UnsafeMutablePointer<_Node> =
.allocate(capacity: self.capacity + 1)
self.header.pointee.children = children
return UnsafeHandle(
keys: self.keys,
values: self.values,
children: children,
header: self.header,
isMutable: self.isMutable
)
}
}
}
// MARK: Subscript
extension _Node.UnsafeHandle {
// TODO: elementAtSlot & others
@inlinable
@inline(__always)
internal subscript(elementAt slot: Int) -> _Node.Element {
@@ -9,11 +9,36 @@
//
//===----------------------------------------------------------------------===//
/// A single node within a B-Tree, containing keys, values, and children.
///
/// A node is merely struct wrapper of the ``_Node.Storage`` class. This does not and should not
/// contain any other properties. By using a ``_Node`` over the underlying storage class, operations can
/// be performed with automatic copy-on-write (CoW) checks such as through the ``update(_:)``
/// method.
///
/// Refer to ``_Node.Storage`` for more information on the allocation and structure of the underlying
/// buffers of a node.
///
/// You cannot operate or read directly from a node. Instead use `read(_:)` and `update(_:)` to make
/// modifications to a node.
///
/// let nodeMedian = node.read { handle in
/// let medianSlot = handle.elementCount
/// return handle[elementAt: medianSlot]
/// }
///
/// Refer to ``_Node.UnsafeHandle`` for the APIs available when operating on a node in such a
/// manner.
@usableFromInline
internal struct _Node<Key: Comparable, Value> {
@usableFromInline
typealias Element = (key: Key, value: Value)
/// An optional parameter to the storage. Use ``storage`` instead
///
/// This will never be `nil` during a valid access of ``_Node``. However, to support moving the
/// underlying storage instance for internal and unsafe operations, this is made optional as an
/// implementation artifact.
@usableFromInline
internal var _storage: Storage?
@@ -22,6 +47,22 @@ internal struct _Node<Key: Comparable, Value> {
@inline(__always)
internal var storage: Storage { _storage.unsafelyUnwrapped }
/// An instance of a ``_Node`` with no underlying storage allocated.
///
/// Use this when you need a dummy node. It is invalid to ever attempt to read or write to this node.
@inlinable
@inline(__always)
internal static var dummy: _Node {
_Node(_underlyingStorage: nil)
}
/// Creates a node with a potentially empty underlying storage.
@inlinable
@inline(__always)
internal init(_underlyingStorage storage: Storage?) {
self._storage = storage
}
/// Creates a node wrapping a Storage object in order to interact with it.
/// - Parameter storage: Underlying node storage.
@inlinable
@@ -310,6 +351,8 @@ extension _Node {
// MARK: Equatable
extension _Node: Equatable {
/// Whether two nodes are the same underlying reference in memory.
/// - Warning: This **does not** compare the keys at all.
@inlinable
@inline(__always)
internal static func ==(lhs: _Node, rhs: _Node) -> Bool {
@@ -10,9 +10,6 @@
//===----------------------------------------------------------------------===//
extension SortedDictionary: CustomReflectable {
// TODO: Review this implementation
// TODO: Implement nice playground output.
/// The custom mirror for this instance.
public var customMirror: Mirror {
Mirror(self, unlabeledChildren: self, displayStyle: .dictionary)
@@ -10,8 +10,6 @@
//===----------------------------------------------------------------------===//
extension SortedDictionary: CustomStringConvertible, CustomDebugStringConvertible {
// TODO: see if there is way to reduce boilerplate here
@inlinable
public var description: String {
if isEmpty { return "[:]" }
@@ -10,8 +10,6 @@
//===----------------------------------------------------------------------===//
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`,
@@ -23,7 +21,7 @@ extension SortedDictionary: Equatable where Value: Equatable {
/// - Complexity: O(`self.count`)
@inlinable
public static func ==(lhs: SortedDictionary<Key, Value>, rhs: SortedDictionary<Key, Value>) -> Bool {
// TODO: optimize/benchmarking by comparing node identity.
// TODO: optimize/benchmarking by comparing node identity/shared subtrees.
if lhs.count != rhs.count { return false }
for ((k1, v1), (k2, v2)) in zip(lhs, rhs) {
if k1 != k2 || v1 != v2 {
@@ -71,7 +71,7 @@ extension SortedDictionary {
var previousKey: Key? = nil
for (key, value) in keysAndValues {
precondition(previousKey == nil || previousKey.unsafelyUnwrapped < key,
precondition(previousKey == nil || previousKey! < key,
"Sequence out of order.")
builder.append((key, value))
previousKey = key
@@ -99,7 +99,7 @@ extension SortedDictionary {
var previousKey: Key? = nil
for (key, value) in keysAndValues {
assert(previousKey != nil && previousKey.unsafelyUnwrapped < key,
precondition(previousKey == nil || previousKey! < key,
"Sequence out of order.")
builder.append((key, value))
previousKey = key
@@ -134,16 +134,10 @@ extension SortedDictionary {
by keyForValue: (S.Element) throws -> Key
) rethrows where Value == [S.Element], S : Sequence {
self.init()
// TODO: implement some way to take advantage of S.underestimateCapacity
for value in values {
let key = try keyForValue(value)
// TODO: optimize to avoid CoW copying the array
if var group = self._root.findAnyValue(forKey: key) {
self.modifyValue(forKey: key, default: []) { group in
group.append(value)
self._root.updateAnyValue(group, forKey: key)
} else {
self._root.updateAnyValue([value], forKey: key)
}
}
}
@@ -30,7 +30,7 @@ extension SortedDictionary {
}
_modify {
var (cursor, found) = self._root.findAnyCursor(forKey: key)
var (cursor, found) = self._root.takeCursor(forKey: key)
var value: Value?
if found {
@@ -97,7 +97,7 @@ extension SortedDictionary {
}
_modify {
var (cursor, found) = self._root.findAnyCursor(forKey: key)
var (cursor, found) = self._root.takeCursor(forKey: key)
var value: Value
if found {
@@ -152,8 +152,10 @@ extension SortedDictionary {
/// - Complexity: O(1)
@inlinable
public subscript(position: Index) -> Element {
position._index.ensureValid(forTree: self._root)
return self._root[position._index]
get {
position._index.ensureValid(forTree: self._root)
return self._root[position._index]
}
}
/// Accesses a contiguous subrange of the collection's elements.
@@ -210,10 +210,27 @@ extension SortedDictionary.Values {
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public subscript(position: Index) -> Value {
// TODO: add setter & _modify attributes
self._base[position].value
get {
self._base[position].value
}
_modify {
position._index.ensureValid(forTree: self._base._root)
// Ensure we don't attempt to dereference the endIndex
precondition(position != endIndex, "Attempt to subscript out of range index.")
var cursor = self._base._root.takeCursor(at: position._index)
var value = cursor.moveValue()
defer {
cursor.initializeValue(to: value)
cursor.apply(to: &self._base._root)
}
yield &value
}
}
}
@@ -36,7 +36,6 @@ extension SortedDictionary {
// 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)
@@ -62,8 +62,8 @@ extension SortedDictionary {
}
_modify {
// TODO: avoid allocating a new node
var values = Values(_base: SortedDictionary())
let dummyDict = SortedDictionary(_rootedAt: _BTree.dummy)
var values = Values(_base: dummyDict)
swap(&self, &values._base)
defer { self = values._base }
yield &values
@@ -108,7 +108,7 @@ extension SortedDictionary {
default defaultValue: @autoclosure () -> Value,
_ body: (inout Value) throws -> R
) rethrows -> R {
var (cursor, found) = self._root.findAnyCursor(forKey: key)
var (cursor, found) = self._root.takeCursor(forKey: key)
let r: R
if found {
@@ -10,8 +10,6 @@
//===----------------------------------------------------------------------===//
extension SortedSet: CustomStringConvertible, CustomDebugStringConvertible {
// TODO: see if there is way to reduce boilerplate here
@inlinable
public var description: String {
var result = "["
@@ -10,8 +10,6 @@
//===----------------------------------------------------------------------===//
extension SortedSet: 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`,
@@ -24,5 +24,30 @@ extension SortedSet {
}
}
// TODO: potentially add unconditional
/// Creates a dictionary from a sequence of **sorted** elements.
///
/// This is a more efficient alternative to ``init(_:)`` which offers
/// better asymptotic performance, and also reduces memory usage when constructing a
/// sorted set on a pre-sorted sequence.
///
/// - Parameter elements: A sequence of elements in non-decreasing comparison order for the
/// new set.
/// - Complexity: O(`n`) where `n` is the number of elements in the
/// sequence.
@inlinable
public init<S: Sequence>(
sortedElements elements: S
) where S.Element == Element {
var builder = _Tree.Builder()
var previousElement: Element? = nil
for element in elements {
precondition(previousElement != nil && previousElement! < element,
"Sequence out of order.")
builder.append(element)
previousElement = element
}
self.init(_rootedAt: builder.finish())
}
}
@@ -85,64 +85,201 @@ extension SortedSet: SetAlgebra {
/// - Returns: A new sorted set with the unique elements of this set and `other`.
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), the element from the second set is inserted.
/// - Complexity: O(max(`self.count`, `other.count`))
/// - Complexity: O(`self.count` + `other.count`)
@inlinable
public func union(_ other: __owned Self) -> Self {
var builder = _Tree.Builder()
var builder = _Tree.Builder(deduplicating: true)
var it1 = self.makeIterator()
var it2 = other.makeIterator()
var e1 = it1.next()
var e2 = it2.next()
// While both sequences have a value, consume the smallest element.
while let el1 = e1, let el2 = e2 {
if el1 < el2 {
builder.append(el1)
e1 = it1.next()
} else {
builder.append(el2)
e2 = it2.next()
}
}
while let el1 = e1 {
builder.append(el1)
e1 = it1.next()
}
while let el2 = e2 {
builder.append(el2)
e2 = it2.next()
}
return SortedSet(_rootedAt: builder.finish())
}
/// Adds the elements of the given set to the set.
///
/// - Parameter other: A set of the same type as the current set.
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), the element from the second set is inserted.
/// - Complexity: O(`self.count` + `other.count`)
@inlinable
public mutating func formUnion(_ other: __owned Self) {
self = union(other)
}
/// Returns a new set with the elements that are common to both this set and
/// the given set.
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
/// - Complexity: O(`self.count` + `other.count`)
@inlinable
public func intersection(_ other: Self) -> Self {
// We'll run this such that 'self' is the smallest array
// TODO: might want to consider uniqueness to minimize CoW copies.
var builder = _Tree.Builder(deduplicating: true)
var it1 = self.makeIterator()
var it2 = other.makeIterator()
while let e1 = it1.next(), let e2 = it2.next() {
if e1 <= e2 {
builder.append((e1, ()))
// while
var e1 = it1.next()
var e2 = it2.next()
// While both sequences have a value, consume the smallest element.
while let el1 = e1, let el2 = e2 {
if el1 < el2 {
e1 = it1.next()
} else if el1 == el2 {
builder.append(el2)
e1 = it1.next()
e2 = it2.next()
} else {
builder.append((e2, ()))
// el1 > el1
e2 = it2.next()
}
}
return SortedSet(_rootedAt: builder.finish())
}
@inlinable
public mutating func formUnion(_ other: __owned Self) {
for element in other {
self.insert(element)
}
}
@inlinable
public func intersection(_ other: Self) -> Self {
var newSet = SortedSet<Element>()
for element in self {
if other.contains(element) {
newSet.insert(element)
}
}
return newSet
}
/// Removes the elements of this set that aren't also in the given set.
///
/// - Parameter other: A set of the same type as the current set.
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
/// - Complexity: O(`self.count` + `other.count`)
@inlinable
public mutating func formIntersection(_ other: Self) {
for element in self {
if !other.contains(element) {
self.remove(element)
}
}
self = intersection(other)
}
/// Returns a new set with the elements that are either in this set or in the
/// given set, but not in both.
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
/// - Complexity: O(`self.count` + `other.count`)
@inlinable
public func symmetricDifference(_ other: Self) -> Self {
var newSet = self.union(other)
newSet.subtract(self.intersection(other))
return newSet
var builder = _Tree.Builder(deduplicating: true)
var it1 = self.makeIterator()
var it2 = other.makeIterator()
var e1 = it1.next()
var e2 = it2.next()
// While both sequences have a value, consume the smallest element.
while let el1 = e1, let el2 = e2 {
if el1 < el2 {
builder.append(el1)
e1 = it1.next()
} else if el2 < el1 {
builder.append(el2)
e2 = it2.next()
} else {
// e1 == e2
e1 = it1.next()
e2 = it2.next()
}
}
while let el1 = e1 {
builder.append(el1)
e1 = it1.next()
}
while let el2 = e2 {
builder.append(el2)
e2 = it2.next()
}
return SortedSet(_rootedAt: builder.finish())
}
/// Removes the elements of the set that are also in the given set and adds
/// the members of the given set that are not already in the set.
///
/// - Parameter other: A set of the same type.
/// - Complexity: O(`self.count` + `other.count`)
@inlinable
public mutating func formSymmetricDifference(_ other: Self) {
self.formUnion(other)
self.subtract(self.intersection(other))
self = self.symmetricDifference(other)
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
/// - Complexity: O(`self.count` + `other.count`)
@inlinable
public func subtracting(_ other: Self) -> Self {
var builder = _Tree.Builder(deduplicating: true)
var it1 = self.makeIterator()
var it2 = other.makeIterator()
var e1 = it1.next()
var e2 = it2.next()
// While both sequences have a value, consume the smallest element.
while let el1 = e1, let el2 = e2 {
if el1 < el2 {
builder.append(el1)
e1 = it1.next()
} else if el2 < el1 {
e2 = it2.next()
} else {
// e1 == e2
e1 = it1.next()
e2 = it2.next()
}
}
while let el1 = e1 {
builder.append(el1)
e1 = it1.next()
}
return SortedSet(_rootedAt: builder.finish())
}
/// Removes the elements of the given set from this set.
///
/// - Parameter other: A set of the same type as the current set.
/// - Complexity: O(`self.count` + `other.count`)
@inlinable
public mutating func subtract(_ other: SortedSet<Element>) {
self = self.subtracting(other)
}
// MARK: Comparing Sets
@@ -156,6 +293,11 @@ extension SortedSet: SetAlgebra {
@inlinable
public func isSubset(of other: SortedSet<Element>) -> Bool {
// TODO: could be worthwhile to evaluate recursive approach
// TODO: in some cases, it could be faster to search from the root each time
// Searching from the root is faster when:
// self.count < other.count / (log(other.count) - 1)
// This means when `other` is significantly larger than `self`, it may be
// faster to search from the root each time.
if self.count > other.count { return false }
var superIterator = other.makeIterator()
@@ -178,4 +320,51 @@ extension SortedSet: SetAlgebra {
return true
}
/// Returns a Boolean value that indicates whether this set is a strict
/// subset of the given set.
///
/// Set *A* is a strict subset of another set *B* if every member of *A* is
/// also a member of *B* and *B* contains at least one element that is not a
/// member of *A*.
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a strict subset of `other`; otherwise,
/// `false`.
/// - Complexity: O(`self.count` + `other.count`).
@inlinable
public func isStrictSubset(of other: SortedSet<Element>) -> Bool {
if self.count >= other.count { return false }
return self.isSubset(of: other)
}
/// Returns a Boolean value that indicates whether the set has no members in
/// common with the given set.
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
/// - Complexity: O(`self.count` + `other.count`).
@inlinable
public func isDisjoint(with other: SortedSet<Element>) -> Bool {
var it1 = self.makeIterator()
var it2 = other.makeIterator()
var e1 = it1.next()
var e2 = it2.next()
// While both sequences have a value, consume the smallest element.
while let el1 = e1, let el2 = e2 {
if el1 < el2 {
e1 = it1.next()
} else if el1 == el2 {
return false
} else {
// el1 > el2
e2 = it2.next()
}
}
return true
}
}
@@ -36,7 +36,6 @@ extension SortedSet {
// MARK: Equatable
extension SortedSet.Index: Equatable {
// TODO: Potentially validate if lhs & rhs aren't pointing to deallocated dictionaries.
@inlinable
public static func ==(lhs: SortedSet.Index, rhs: SortedSet.Index) -> Bool {
lhs._index.ensureValid(with: rhs._index)
@@ -35,23 +35,3 @@ public struct SortedSet<Element: Comparable> {
self._root = tree
}
}
// MARK: Testing for Membership
// MARK: Adding Elements
extension SortedSet {
// TODO: document
@inlinable
@inline(__always)
@discardableResult
public mutating func remove(atOffset offset: Int) -> Element {
return self._root.remove(atOffset: offset).key
}
// TODO: document
@inlinable
@inline(__always)
public subscript(offset absoluteOffset: Int) -> Element {
return self._root.index(atOffset: absoluteOffset).element.key
}
}