diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/SortedCollections.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/SortedCollections.xcscheme new file mode 100644 index 00000000..a660e589 --- /dev/null +++ b/.swiftpm/xcode/xcshareddata/xcschemes/SortedCollections.xcscheme @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme index bf3d7efa..a59aafe9 100644 --- a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme +++ b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme @@ -37,28 +37,14 @@ - - - - @@ -76,6 +62,20 @@ ReferencedContainer = "container:"> + + + + + buildForRunning = "YES" + buildForProfiling = "YES" + buildForArchiving = "YES" + buildForAnalyzing = "YES"> - - - - diff --git a/Benchmarks/Benchmarks/CppBenchmarks.swift b/Benchmarks/Benchmarks/CppBenchmarks.swift index 219283f0..1433313b 100644 --- a/Benchmarks/Benchmarks/CppBenchmarks.swift +++ b/Benchmarks/Benchmarks/CppBenchmarks.swift @@ -139,6 +139,26 @@ internal class CppPriorityQueue { } } +internal class CppMap { + var ptr: UnsafeMutableRawPointer? + + init(_ input: [Int]) { + self.ptr = input.withUnsafeBufferPointer { buffer in + cpp_map_create(buffer.baseAddress, buffer.count) + } + } + + deinit { + destroy() + } + + func destroy() { + if let ptr = ptr { + cpp_map_destroy(ptr) + } + ptr = nil + } +} extension Benchmark { public mutating func addCppBenchmarks() { @@ -706,5 +726,28 @@ extension Benchmark { pq.destroy() } } + + //-------------------------------------------------------------------------- + +// self.addSimple( +// title: "std::map insert", +// input: [Int].self +// ) { input in +// input.withUnsafeBufferPointer { buffer in +// cpp_map_insert_integers(buffer.baseAddress, buffer.count) +// } +// } + + self.add( + title: "std::map successful find", + input: ([Int], [Int]).self + ) { input, lookups in + let map = CppMap(input) + return { timer in + lookups.withUnsafeBufferPointer { buffer in + cpp_map_lookups(map.ptr, buffer.baseAddress, buffer.count, true) + } + } + } } } diff --git a/Benchmarks/Benchmarks/SortedDictionaryBenchmarks.swift b/Benchmarks/Benchmarks/SortedDictionaryBenchmarks.swift new file mode 100644 index 00000000..8e6daa8d --- /dev/null +++ b/Benchmarks/Benchmarks/SortedDictionaryBenchmarks.swift @@ -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 +// +//===----------------------------------------------------------------------===// + +import CollectionsBenchmark + +extension Benchmark { + public mutating func addSortedDictionaryBenchmarks() { +// self.add( +// title: "SortedDictionary init(uniqueKeysWithValues:)", +// input: [Int].self +// ) { input in +// let keysAndValues = input.lazy.map { (key: $0, value: 2 * $0) } +// +// return { timer in +// blackHole(SortedDictionary(uniqueKeysWithValues: keysAndValues)) +// } +// } +// +// self.add( +// title: "SortedDictionary subscript, append", +// input: [Int].self +// ) { input in +// let keysAndValues = input.lazy.map { (key: $0, value: 2 * $0) } +// var sortedDictionary = SortedDictionary() +// +// return { timer in +// for (key, value) in keysAndValues { +// sortedDictionary[key] = value +// } +// blackHole(sortedDictionary) +// } +// } + + self.add( + title: "SortedDictionary subscript, successful lookups", + input: [Int].self + ) { input in + let keysAndValues = input.lazy.map { (key: $0, value: 2 * $0) } + let sortedDictionary = SortedDictionary(uniqueKeysWithValues: keysAndValues) + + return { timer in + for (key, value) in keysAndValues { + precondition(sortedDictionary[key] == value) + } + } + } + +// self.add( +// title: "SortedDictionary._BTree firstValue", +// input: [Int].self +// ) { input in +// let keysAndValues = input.lazy.map { (key: $0, value: 2 * $0) } +// var tree = _BTree() +// +// for (key, value) in keysAndValues { +// tree.insertOrUpdate((key, value)) +// } +// +// return { timer in +// for (key, value) in keysAndValues { +// precondition(tree.anyValue(for: key) != nil) +// } +// } +// } + +// self.add( +// title: "SortedDictionary._BTree insertOrUpdate(element:)", +// input: [Int].self +// ) { input in +// let keysAndValues = input.lazy.map { (key: $0, value: 2 * $0) } +// +// return { timer in +// var tree = _BTree() +// for (key, value) in keysAndValues { +// tree.insertOrUpdate((key, value)) +// } +// blackHole(tree) +// } +// } + } +} diff --git a/Benchmarks/CppBenchmarks/include/MapBenchmarks.h b/Benchmarks/CppBenchmarks/include/MapBenchmarks.h new file mode 100644 index 00000000..53157439 --- /dev/null +++ b/Benchmarks/CppBenchmarks/include/MapBenchmarks.h @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#ifndef CPPBENCHMARKS_MAP_BENCHMARKS_H +#define CPPBENCHMARKS_MAP_BENCHMARKS_H + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/// Create a std::map, populating it with data from the supplied buffer. +/// Returns an opaque pointer to the created instance. +extern void *cpp_map_create(const intptr_t *start, size_t count); + +/// Destroys an ordered map previously returned by `cpp_map_create`. +extern void cpp_map_destroy(void *ptr); + +extern void cpp_map_insert_integers(const intptr_t *start, size_t count); + +extern void cpp_map_lookups(void *ptr, const intptr_t *start, size_t count, bool expectMatch); + +#ifdef __cplusplus +} +#endif + + +#endif /* CPPBENCHMARKS_MAP_BENCHMARKS_H */ diff --git a/Benchmarks/CppBenchmarks/include/module.modulemap b/Benchmarks/CppBenchmarks/include/module.modulemap index 7fbcf933..900b0f1a 100644 --- a/Benchmarks/CppBenchmarks/include/module.modulemap +++ b/Benchmarks/CppBenchmarks/include/module.modulemap @@ -5,6 +5,7 @@ module CppBenchmarks { header "DequeBenchmarks.h" header "UnorderedSetBenchmarks.h" header "UnorderedMapBenchmarks.h" + header "MapBenchmarks.h" header "PriorityQueueBenchmarks.h" export * } diff --git a/Benchmarks/CppBenchmarks/src/MapBenchmarks.cpp b/Benchmarks/CppBenchmarks/src/MapBenchmarks.cpp new file mode 100644 index 00000000..8e8c061e --- /dev/null +++ b/Benchmarks/CppBenchmarks/src/MapBenchmarks.cpp @@ -0,0 +1,61 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#include "MapBenchmarks.h" +#include +#include +#include "utils.h" + +typedef std::map custom_map; + +void * +cpp_map_create(const intptr_t *start, size_t count) +{ + auto map = new custom_map(); + for (size_t i = 0; i < count; ++i) { + map->insert({start[i], 2 * start[i]}); + } + return map; +} + +void +cpp_map_destroy(void *ptr) +{ + delete static_cast(ptr); +} + +void +cpp_map_insert_integers(const intptr_t *start, size_t count) +{ + auto map = custom_map(); + auto end = start + count; + for (auto p = start; p != end; ++p) { + auto v = *identity(p); + map.insert({ v, 2 * v }); + } + black_hole(&map); +} + +__attribute__((noinline)) +auto find(custom_map* map, intptr_t value) +{ + return map->find(value); +} + +void +cpp_map_lookups(void *ptr, const intptr_t *start, size_t count, bool expectMatch) +{ + auto map = static_cast(ptr); + for (auto it = start; it < start + count; ++it) { + auto found = find(map, *it) != map->end(); + if (found != expectMatch) { abort(); } + } +} diff --git a/Benchmarks/swift-collections-benchmark/main.swift b/Benchmarks/swift-collections-benchmark/main.swift index d2096d38..e13bbc79 100644 --- a/Benchmarks/swift-collections-benchmark/main.swift +++ b/Benchmarks/swift-collections-benchmark/main.swift @@ -19,6 +19,7 @@ benchmark.addDictionaryBenchmarks() benchmark.addDequeBenchmarks() benchmark.addOrderedSetBenchmarks() benchmark.addOrderedDictionaryBenchmarks() +benchmark.addSortedDictionaryBenchmarks() benchmark.addHeapBenchmarks() benchmark.addCppBenchmarks() #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) diff --git a/Package.swift b/Package.swift index ace16942..3ab9cdc8 100644 --- a/Package.swift +++ b/Package.swift @@ -54,6 +54,7 @@ let package = Package( .library(name: "Collections", targets: ["Collections"]), .library(name: "DequeModule", targets: ["DequeModule"]), .library(name: "OrderedCollections", targets: ["OrderedCollections"]), + .library(name: "SortedCollections", targets: ["SortedCollections"]), .library(name: "PriorityQueueModule", targets: ["PriorityQueueModule"]), ], dependencies: [ @@ -66,6 +67,7 @@ let package = Package( dependencies: [ "DequeModule", "OrderedCollections", + "SortedCollections", "PriorityQueueModule", ], path: "Sources/Collections", @@ -132,7 +134,16 @@ let package = Package( name: "OrderedCollectionsTests", dependencies: ["OrderedCollections", "CollectionsTestSupport"], swiftSettings: settings), - + + // SortedDictionary + .target( + name: "SortedCollections", + swiftSettings: settings), + .testTarget( + name: "SortedCollectionsTests", + dependencies: ["SortedCollections", "CollectionsTestSupport"], + swiftSettings: settings), + // PriorityQueue .target( name: "PriorityQueueModule", diff --git a/Sources/SortedCollections/BTree/_BTree+BidirectionalCollection.swift b/Sources/SortedCollections/BTree/_BTree+BidirectionalCollection.swift new file mode 100644 index 00000000..a5d53cd9 --- /dev/null +++ b/Sources/SortedCollections/BTree/_BTree+BidirectionalCollection.swift @@ -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(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..\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 +} diff --git a/Sources/SortedCollections/BTree/_BTree+Testing.swift b/Sources/SortedCollections/BTree/_BTree+Testing.swift new file mode 100644 index 00000000..868f801c --- /dev/null +++ b/Sources/SortedCollections/BTree/_BTree+Testing.swift @@ -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(_ body: (inout _BTree) throws -> R) rethrows -> R { + try body(&self) + } +} diff --git a/Sources/SortedCollections/BTree/_BTree.Index.swift b/Sources/SortedCollections/BTree/_BTree.Index.swift new file mode 100644 index 00000000..e1568490 --- /dev/null +++ b/Sources/SortedCollections/BTree/_BTree.Index.swift @@ -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.") + } + } +} diff --git a/Sources/SortedCollections/BTree/_BTree.UnsafePath.swift b/Sources/SortedCollections/BTree/_BTree.UnsafePath.swift new file mode 100644 index 00000000..5e7054b2 --- /dev/null +++ b/Sources/SortedCollections/BTree/_BTree.UnsafePath.swift @@ -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 + + @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, + 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, + 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.. { + @usableFromInline + typealias Element = (key: Key, value: Value) + + @usableFromInline + typealias Node = _Node + + /// 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 + } +} diff --git a/Sources/SortedCollections/BTree/_Node+CustomDebugString.swift b/Sources/SortedCollections/BTree/_Node+CustomDebugString.swift new file mode 100644 index 00000000..370f03db --- /dev/null +++ b/Sources/SortedCollections/BTree/_Node+CustomDebugString.swift @@ -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 } + } +} diff --git a/Sources/SortedCollections/BTree/_Node+Testing.swift b/Sources/SortedCollections/BTree/_Node+Testing.swift new file mode 100644 index 00000000..7605c5b1 --- /dev/null +++ b/Sources/SortedCollections/BTree/_Node+Testing.swift @@ -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( + _keyValuePairs keyValuePairs: C, + children: [_Node]? = 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.. = ManagedBuffer +} diff --git a/Sources/SortedCollections/BTree/_Node.Splinter.swift b/Sources/SortedCollections/BTree/_Node.Splinter.swift new file mode 100644 index 00000000..8eb9f7c5 --- /dev/null +++ b/Sources/SortedCollections/BTree/_Node.Splinter.swift @@ -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) { + 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 + + @inlinable + @inline(__always) + internal func toNode(from node: _Node, 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 + } + } +} diff --git a/Sources/SortedCollections/BTree/_Node.Storage.swift b/Sources/SortedCollections/BTree/_Node.Storage.swift new file mode 100644 index 00000000..017eb3d6 --- /dev/null +++ b/Sources/SortedCollections/BTree/_Node.Storage.swift @@ -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.Buffer, + children: _Node.Buffer<_Node>? + ) { + 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 + + /// Pointer to the buffer containing the elements. + @usableFromInline + internal var children: Buffer<_Node>? + } + + /// 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) + } + } + } +} diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift new file mode 100644 index 00000000..8797a8b7 --- /dev/null +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift @@ -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.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.UnsafeHandle) -> String { + var result = "" + for slot in 0.. 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) + } +} diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle.swift new file mode 100644 index 00000000..2cad1a42 --- /dev/null +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle.swift @@ -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
+ + @usableFromInline + internal let keys: UnsafeMutablePointer + + @usableFromInline + internal let values: UnsafeMutablePointer + + @usableFromInline + internal let children: UnsafeMutablePointer<_Node>? + + @inlinable + @inline(__always) + internal init( + keys: UnsafeMutablePointer, + values: UnsafeMutablePointer, + children: UnsafeMutablePointer<_Node>?, + header: UnsafeMutablePointer
, + 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..= 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.. _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..= 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( +// 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) +// } +} diff --git a/Sources/SortedCollections/BTree/_Node.swift b/Sources/SortedCollections/BTree/_Node.swift new file mode 100644 index 00000000..2d252c89 --- /dev/null +++ b/Sources/SortedCollections/BTree/_Node.swift @@ -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 { + @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.create(minimumCapacity: capacity) { _ in BufferHeader() }, + children: isLeaf ? nil + : Buffer<_Node>.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(_ 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(_ 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 + } +} + diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+BidirectionalCollection.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+BidirectionalCollection.swift new file mode 100644 index 00000000..613d9618 --- /dev/null +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+BidirectionalCollection.swift @@ -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] + } +} diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomReflectable.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomReflectable.swift new file mode 100644 index 00000000..f12c01dc --- /dev/null +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomReflectable.swift @@ -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) + } +} diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomStringConvertible.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomStringConvertible.swift new file mode 100644 index 00000000..d57f86f2 --- /dev/null +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomStringConvertible.swift @@ -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 + } +} diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Equatable.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Equatable.swift new file mode 100644 index 00000000..693196b3 --- /dev/null +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Equatable.swift @@ -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, rhs: SortedDictionary) -> 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 + } +} diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+ExpressibleByDictionaryLiteral.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+ExpressibleByDictionaryLiteral.swift new file mode 100644 index 00000000..730a3ceb --- /dev/null +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+ExpressibleByDictionaryLiteral.swift @@ -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) + } +} diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Hashable.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Hashable.swift new file mode 100644 index 00000000..7d093d87 --- /dev/null +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Hashable.swift @@ -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) + } + } +} diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Sequence.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Sequence.swift new file mode 100644 index 00000000..923177f0 --- /dev/null +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Sequence.swift @@ -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) +// } +//} diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary.Index.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary.Index.swift new file mode 100644 index 00000000..c5503715 --- /dev/null +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary.Index.swift @@ -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 + } +} diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift new file mode 100644 index 00000000..023e50d8 --- /dev/null +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift @@ -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 { + /// An element of the sorted dictionary. A key-value tuple. + public typealias Element = (key: Key, value: Value) + + @usableFromInline + internal typealias _Tree = _BTree + + @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( + 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 + } + } +} diff --git a/Sources/SortedCollections/SortedSet/SortedSet.swift b/Sources/SortedCollections/SortedSet/SortedSet.swift new file mode 100644 index 00000000..eab74c99 --- /dev/null +++ b/Sources/SortedCollections/SortedSet/SortedSet.swift @@ -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 diff --git a/Sources/SortedCollections/Utilities/Assertions.swift b/Sources/SortedCollections/Utilities/Assertions.swift new file mode 100644 index 00000000..fda167d4 --- /dev/null +++ b/Sources/SortedCollections/Utilities/Assertions.swift @@ -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 +// +//===----------------------------------------------------------------------===// + + diff --git a/Tests/SortedCollectionsTests/BTree/BTreeTests.swift b/Tests/SortedCollectionsTests/BTree/BTreeTests.swift new file mode 100644 index 00000000..e875e9cb --- /dev/null +++ b/Tests/SortedCollectionsTests/BTree/BTreeTests.swift @@ -0,0 +1,165 @@ +//===----------------------------------------------------------------------===// +// +// 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 CollectionsTestSupport +@_spi(Testing) @testable import SortedCollections + +func btreeOfSize( + _ size: Int, + _ body: (inout _BTree, [(key: Int, value: Int)]) throws -> Void +) rethrows { + var tree = _BTree(capacity: 2) + var keyValues = [(key: Int, value: Int)]() + for i in 0..() + for (key, value) in kvs { + tree.setAnyValue(value, forKey: key) + } + } +} diff --git a/Tests/SortedCollectionsTests/BTree/Node Utils.swift b/Tests/SortedCollectionsTests/BTree/Node Utils.swift new file mode 100644 index 00000000..2752b114 --- /dev/null +++ b/Tests/SortedCollectionsTests/BTree/Node Utils.swift @@ -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 +// +//===----------------------------------------------------------------------===// + +@_spi(Testing) @testable import SortedCollections + +struct NodeTemplate { + let keys: [Int] + let children: [NodeTemplate]? + + func toNode(ofCapacity capacity: Int) -> _Node { + let kvs = self.keys.map { (key: $0, value: $0 * 2) } + return _Node( + _keyValuePairs: kvs, + children: children?.map({ $0.toNode(ofCapacity: capacity) }), + capacity: capacity + ) + } + + func toBTree(ofCapacity capacity: Int) -> _BTree { + return _BTree(rootedAt: self.toNode(ofCapacity: capacity), capacity: capacity) + } + + func matches(_ btree: _BTree) -> Bool { + return self.matches(btree.root) + } + + func matches(_ node: _Node) -> Bool { + return node.read { handle in + if self.keys.count != handle.numElements { return false } + if (self.children == nil) != handle.isLeaf { return false } + + if let children = self.children { + for (i, child) in children.enumerated() { + if !child.matches(handle[childAt: i]) { + return false + } + } + } + + for (i, key) in self.keys.enumerated() { + if handle[keyAt: i] != key { + return false + } + } + + return true + } + } +} + +@resultBuilder +struct NodeTemplateBuilder { + static func buildBlock(_ components: Any...) -> NodeTemplate { + var keys = [Int]() + var children = [NodeTemplate]() + for c in components { + switch c { + case let c as Int: + keys.append(c) + case let c as NodeTemplate: + children.append(c) + default: + preconditionFailure("NodeTemplate child must be either key or child.") + } + } + precondition(children.count == 0 || children.count == keys.count + 1, + "NodeTemplate must be either leaf or internal node.") + return NodeTemplate(keys: keys, children: children.isEmpty ? nil : children) + } +} + +func tree(@NodeTemplateBuilder _ builder: () -> NodeTemplate) -> NodeTemplate { + return builder() +} diff --git a/Tests/SortedCollectionsTests/BTree/Node+Insertion Tests.swift b/Tests/SortedCollectionsTests/BTree/Node+Insertion Tests.swift new file mode 100644 index 00000000..4280a1a1 --- /dev/null +++ b/Tests/SortedCollectionsTests/BTree/Node+Insertion Tests.swift @@ -0,0 +1,545 @@ +//===----------------------------------------------------------------------===// +// +// 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 CollectionsTestSupport +@_spi(Testing) @testable import SortedCollections + +func expectInsertionInTree( + capacity: Int, + tree: NodeTemplate, + inserting key: Int, + toEqual refTree: NodeTemplate) { + var btree = tree.toBTree(ofCapacity: capacity) + + btree.setAnyValue(key * 2, forKey: key) + + let refMatches = refTree.matches(btree) + if !refMatches { + print("Expected: ") + print(refTree.toBTree(ofCapacity: capacity)) + print("Instead got: ") + print(btree) + } + expectTrue(refMatches) +} + +final class NodeInsertionTests: CollectionTestCase { + // MARK: Median Leaf Node Insertion + func test_medianLeafInsertion() { + expectInsertionInTree( + capacity: 2, + tree: tree { 0; 2 }, + inserting: 1, + toEqual: tree { + tree { 0 } + 1 + tree { 2 } + } + ) + + expectInsertionInTree( + capacity: 4, + tree: tree { 0; 1; 3; 4 }, + inserting: 2, + toEqual: tree { + tree { 0; 1 } + 2 + tree { 3; 4 } + } + ) + + expectInsertionInTree( + capacity: 5, + tree: tree { 0; 1; 3; 4; 5 }, + inserting: 2, + toEqual: tree { + tree { 0; 1 } + 2 + tree { 3; 4; 5 } + } + ) + } + + // MARK: Median Internal Node Insertion + func test_medianInternalInsertion() { + expectInsertionInTree( + capacity: 2, + tree: tree { + tree { 0; 1 } + 2 + tree { 3; 5 } + 6 + tree { 7; 8 } + }, + inserting: 4, + toEqual: tree { + tree { + tree { 0; 1 } + 2 + tree { 3 } + } + 4 + tree { + tree { 5 } + 6 + tree { 7; 8 } + } + } + ) + + expectInsertionInTree( + capacity: 3, + tree: tree { + tree { 0; 1; 2 } + 3 + tree { 4; 6; 7 } + 8 + tree { 9; 10; 11 } + 12 + tree { 13; 14; 15 } + }, + inserting: 5, + toEqual: tree { + tree { + tree { 0; 1; 2 } + 3 + tree { 4 } + } + 5 + tree { + tree { 6; 7 } + 8 + tree { 9; 10; 11 } + 12 + tree { 13; 14; 15 } + } + } + ) + + expectInsertionInTree( + capacity: 4, + tree: tree { + tree { 0; 1; 2; 4 } + 5 + tree { 6; 7; 8; 9 } + 10 + tree { 11; 12; 14; 15 } + 16 + tree { 17; 18; 19; 20 } + 21 + tree { 22; 23; 24; 25 } + }, + inserting: 13, + toEqual: tree { + tree { + tree { 0; 1; 2; 4 } + 5 + tree { 6; 7; 8; 9 } + 10 + tree { 11; 12 } + } + 13 + tree { + tree { 14; 15 } + 16 + tree { 17; 18; 19; 20 } + 21 + tree { 22; 23; 24; 25 } + } + } + ) + + expectInsertionInTree( + capacity: 5, + tree: tree { + tree { 0; 1; 2; 4; 5 } + 6 + tree { 7; 8; 9; 10; 11 } + 12 + tree { 13; 14; 16; 17; 18 } + 19 + tree { 20; 21; 22; 23; 24 } + 25 + tree { 26; 27; 28; 29; 30 } + 31 + tree { 32; 33; 34; 35; 36 } + }, + inserting: 15, + toEqual: tree { + tree { + tree { 0; 1; 2; 4; 5 } + 6 + tree { 7; 8; 9; 10; 11 } + 12 + tree { 13; 14 } + } + 15 + tree { + tree { 16; 17; 18 } + 19 + tree { 20; 21; 22; 23; 24 } + 25 + tree { 26; 27; 28; 29; 30 } + 31 + tree { 32; 33; 34; 35; 36 } + } + } + ) + } + + // MARK: Right Leaf Insertion + func test_rightLeafInsertion() { + expectInsertionInTree( + capacity: 2, + tree: tree { 1; 2 }, + inserting: 3, + toEqual: tree { + tree { 1 } + 2 + tree { 3 } + } + ) + + expectInsertionInTree( + capacity: 3, + tree: tree { 1; 2; 4 }, + inserting: 3, + toEqual: tree { + tree { 1 } + 2 + tree { 3; 4 } + } + ) + + expectInsertionInTree( + capacity: 4, + tree: tree { 0; 1; 2; 4 }, + inserting: 3, + toEqual: tree { + tree { 0; 1 } + 2 + tree { 3; 4 } + } + ) + + expectInsertionInTree( + capacity: 5, + tree: tree { 0; 1; 2; 3; 5 }, + inserting: 4, + toEqual: tree { + tree { 0; 1 } + 2 + tree { 3; 4; 5 } + } + ) + } + + // MARK: Right Internal Node Insertion + func test_rightInternalNodeInsertion() { + expectInsertionInTree( + capacity: 2, + tree: tree { + tree { 0; 1 } + 2 + tree { 3; 4 } + 5 + tree { 6; 7 } + }, + inserting: 8, + toEqual: tree { + tree { + tree { 0; 1 } + 2 + tree { 3; 4 } + } + 5 + tree { + tree { 6 } + 7 + tree { 8 } + } + } + ) + + expectInsertionInTree( + capacity: 3, + tree: tree { + tree { 0; 1; 2 } + 3 + tree { 4; 5; 6 } + 7 + tree { 8; 9; 10 } + 11 + tree { 12; 13; 15 } + }, + inserting: 14, + toEqual: tree { + tree { + tree { 0; 1; 2 } + 3 + tree { 4; 5; 6 } + } + 7 + tree { + tree { 8; 9; 10 } + 11 + tree { 12 } + 13 + tree { 14; 15 } + } + } + ) + + expectInsertionInTree( + capacity: 4, + tree: tree { + tree { 0; 1; 2; 4 } + 5 + tree { 6; 7; 8; 9 } + 10 + tree { 11; 12; 13; 14 } + 15 + tree { 16; 17; 18; 19 } + 20 + tree { 21; 22; 23; 25 } + }, + inserting: 24, + toEqual: tree { + tree { + tree { 0; 1; 2; 4 } + 5 + tree { 6; 7; 8; 9 } + 10 + tree { 11; 12; 13; 14 } + } + 15 + tree { + tree { 16; 17; 18; 19 } + 20 + tree { 21; 22 } + 23 + tree { 24; 25 } + } + } + ) + + expectInsertionInTree( + capacity: 5, + tree: tree { + tree { 0; 1; 2; 4; 5 } + 6 + tree { 7; 8; 9; 10; 11 } + 12 + tree { 13; 14; 15; 16; 17 } + 18 + tree { 19; 20; 21; 22; 23 } + 24 + tree { 25; 26; 27; 28; 29 } + 30 + tree { 31; 32; 33; 34; 36 } + }, + inserting: 35, + toEqual: tree { + tree { + tree { 0; 1; 2; 4; 5 } + 6 + tree { 7; 8; 9; 10; 11 } + 12 + tree { 13; 14; 15; 16; 17 } + } + 18 + tree { + tree { 19; 20; 21; 22; 23 } + 24 + tree { 25; 26; 27; 28; 29 } + 30 + tree { 31; 32 } + 33 + tree { 34; 35; 36 } + } + } + ) + } + + // MARK: Left Leaf Insertion + func test_leftLeafInsertion() { + expectInsertionInTree( + capacity: 2, + tree: tree { 1; 2 }, + inserting: 0, + toEqual: tree { + tree { 0 } + 1 + tree { 2 } + } + ) + + expectInsertionInTree( + capacity: 3, + tree: tree { 1; 2; 3 }, + inserting: 0, + toEqual: tree { + tree { 0; 1 } + 2 + tree { 3 } + } + ) + + expectInsertionInTree( + capacity: 4, + tree: tree { 0; 2; 3; 4 }, + inserting: 1, + toEqual: tree { + tree { 0; 1 } + 2 + tree { 3; 4 } + } + ) + + expectInsertionInTree( + capacity: 5, + tree: tree { 0; 2; 3; 4; 5 }, + inserting: 1, + toEqual: tree { + tree { 0; 1; 2 } + 3 + tree { 4; 5 } + } + ) + } + + // MARK: Left Internal Node Insertion + func test_leftInternalNodeInsertion() { + expectInsertionInTree( + capacity: 2, + tree: tree { + tree { 1; 2 } + 3 + tree { 4; 5 } + 6 + tree { 7; 8 } + }, + inserting: 0, + toEqual: tree { + tree { + tree { 0 } + 1 + tree { 2 } + } + 3 + tree { + tree { 4; 5 } + 6 + tree { 7; 8 } + } + } + ) + + expectInsertionInTree( + capacity: 3, + tree: tree { + tree { 1; 2; 3 } + 4 + tree { 5; 6; 7 } + 8 + tree { 9; 10; 11 } + 12 + tree { 13; 14; 15 } + }, + inserting: 0, + toEqual: tree { + tree { + tree { 0; 1 } + 2 + tree { 3 } + 4 + tree { 5; 6; 7 } + } + 8 + tree { + tree { 9; 10; 11 } + 12 + tree { 13; 14; 15 } + } + } + ) + + expectInsertionInTree( + capacity: 4, + tree: tree { + tree { 0; 2; 3; 4 } + 5 + tree { 6; 7; 8; 9 } + 10 + tree { 11; 12; 13; 14 } + 15 + tree { 16; 17; 18; 19 } + 20 + tree { 21; 22; 23; 24 } + }, + inserting: 1, + toEqual: tree { + tree { + tree { 0; 1 } + 2 + tree { 3; 4 } + 5 + tree { 6; 7; 8; 9 } + } + 10 + tree { + tree { 11; 12; 13; 14 } + 15 + tree { 16; 17; 18; 19 } + 20 + tree { 21; 22; 23; 24 } + } + } + ) + + expectInsertionInTree( + capacity: 5, + tree: tree { + tree { 0; 2; 3; 4; 5 } + 6 + tree { 7; 8; 9; 10; 11 } + 12 + tree { 13; 14; 15; 16; 17 } + 18 + tree { 19; 20; 21; 22; 23 } + 24 + tree { 25; 26; 27; 28; 29 } + 30 + tree { 31; 32; 33; 34; 35 } + }, + inserting: 1, + toEqual: tree { + tree { + tree { 0; 1; 2 } + 3 + tree { 4; 5 } + 6 + tree { 7; 8; 9; 10; 11 } + 12 + tree { 13; 14; 15; 16; 17 } + } + 18 + tree { + tree { 19; 20; 21; 22; 23 } + 24 + tree { 25; 26; 27; 28; 29 } + 30 + tree { 31; 32; 33; 34; 35 } + } + } + ) + } +} diff --git a/Tests/SortedCollectionsTests/BTree/NodeTests.swift b/Tests/SortedCollectionsTests/BTree/NodeTests.swift new file mode 100644 index 00000000..531c737a --- /dev/null +++ b/Tests/SortedCollectionsTests/BTree/NodeTests.swift @@ -0,0 +1,143 @@ +//===----------------------------------------------------------------------===// +// +// 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 CollectionsTestSupport +@_spi(Testing) @testable import SortedCollections + +func nodeFromKeys(_ keys: [Int], capacity: Int) -> _Node { + let kvPairs = keys.map { (key: $0, value: $0 * 2) } + return _Node(_keyValuePairs: kvPairs, capacity: capacity) +} + +func insertSortedValue(_ value: Int, into array: inout [Int]) { + var insertionIndex = 0 + while insertionIndex < array.count { + if array[insertionIndex] > value { + break + } + insertionIndex += 1 + } + array.insert(value, at: insertionIndex) +} + +func findFirstIndexOf(_ value: Int, in array: [Int]) -> Int { + var index = 0 + while index < array.count { + if array[index] >= value { + break + } + index += 1 + } + return index +} + +func findLastIndexOf(_ value: Int, in array: [Int]) -> Int { + var index = 0 + while index < array.count { + if array[index] > value { + break + } + index += 1 + } + return index +} + +/// Generates all shifts of a duplicate run in a node of capacity N. +/// - Parameters: +/// - capacity: Total capacity of node. +/// - keys: The number filled keys in the node. +/// - duplicates: The number of duplicates. Must be greater than or equal to 1 +/// - Returns: The duplicated key. +func withEveryNode( + ofCapacity capacity: Int, + keys: Int, + duplicates: Int, + _ body: (_Node, [Int], Int) throws -> Void +) rethrows { + let possibleShifts = keys - duplicates + 1 + try withEvery("shift", in: 0...Splinter? = node.update { handle in + let index = handle.lastSlot(for: newKey) + return handle.immediatelyInsert(element: (newKey, newKey * 2), withRightChild: nil, at: index) + } + insertSortedValue(newKey, into: &array) + + expectNil(splinter) + node.read { handle in + let keys = UnsafeBufferPointer(start: handle.keys, count: handle.numElements) + expectEqualElements(keys, array) + expectEqual(handle.numTotalElements, count + 1) + } + } + } + } + } + + func test_firstIndexOfDuplicates() { + withEvery("capacity", in: 2..<10) { capacity in + withEvery("keys", in: 0...capacity) { keys in + withEvery("duplicates", in: 0...keys) { duplicates in + withEveryNode(ofCapacity: capacity, keys: keys, duplicates: duplicates) { node, array, duplicatedKey in + node.read { handle in + expectEqual( + handle.firstSlot(for: duplicatedKey), + findFirstIndexOf(duplicatedKey, in: array) + ) + } + } + } + } + } + } + + func test_lastIndexOfDuplicates() { + withEvery("capacity", in: 2..<10) { capacity in + withEvery("keys", in: 0...capacity) { keys in + withEvery("duplicates", in: 0...keys) { duplicates in + withEveryNode(ofCapacity: capacity, keys: keys, duplicates: duplicates) { node, array, duplicatedKey in + node.read { handle in + expectEqual( + handle.lastSlot(for: duplicatedKey), + findLastIndexOf(duplicatedKey, in: array) + ) + } + } + } + } + } + } +} diff --git a/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionaryTests.swift b/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionaryTests.swift new file mode 100644 index 00000000..c4bb3727 --- /dev/null +++ b/Tests/SortedCollectionsTests/SortedDictionary/SortedDictionaryTests.swift @@ -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 +// +//===----------------------------------------------------------------------===// + +import CollectionsTestSupport +@_spi(Testing) @testable import SortedCollections + +final class SortedDictionaryTests: CollectionTestCase { + func test_uniqueKeysAndValues() { + withEvery("count", in: [0, 1, 2, 4, 8, 16, 32, 64, 128]) { count in + let kvs = (0..(uniqueKeysWithValues: kvs) + expectEqual(sortedDictionary.count, count) + } + } + + func test_orderedInsertion() { + withEvery("count", in: [0, 1, 2, 3, 4, 8, 16, 64]) { count in + var sortedDictionary: SortedDictionary = [:] + + for i in 0.. = [:] + + for i in (0..(uniqueKeysWithValues: kvs) + sortedDictionary[i * 2] = -i + + var comparison = Array(kvs) + comparison.insert((key: i * 2, value: -i), at: i) + + expectEqualElements(comparison, sortedDictionary) + } + } + } + + func test_updateValue() { + withEvery("count", in: [1, 2, 4, 8, 16, 32, 64]) { count in + var sortedDictionary: SortedDictionary = [:] + + for i in 0..