diff --git a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme index a59aafe9..a3af5c69 100644 --- a/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme +++ b/.swiftpm/xcode/xcshareddata/xcschemes/swift-collections-Package.xcscheme @@ -132,6 +132,20 @@ ReferencedContainer = "container:"> + + + + + + + + + + + + + + + + + + + + + + + + + + Bool ) rethrows -> _BTree { - // TODO: optimize implementation to O(n) var builder = Builder() for element in self where try isIncluded(element) { builder.append(element) diff --git a/Sources/SortedCollections/BTree/_BTree+Sequence.swift b/Sources/SortedCollections/BTree/_BTree+Sequence.swift index 57a6bbf8..7539e788 100644 --- a/Sources/SortedCollections/BTree/_BTree+Sequence.swift +++ b/Sources/SortedCollections/BTree/_BTree+Sequence.swift @@ -94,7 +94,6 @@ extension _BTree: Sequence { return } - // TODO: maybe convert to unowned(unsafe) var nextNode: Unmanaged? = .passUnretained(tree.root.storage) while let node = nextNode { self.path.append(node) diff --git a/Sources/SortedCollections/BTree/_BTree+Testing.swift b/Sources/SortedCollections/BTree/_BTree+Testing.swift deleted file mode 100644 index 868f801c..00000000 --- a/Sources/SortedCollections/BTree/_BTree+Testing.swift +++ /dev/null @@ -1,18 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -extension _BTree { - /// Runs some operations on a BTree, ensuring it does not get deallocated in the process - @_spi(Testing) - public mutating func withSelf(_ body: (inout _BTree) throws -> R) rethrows -> R { - try body(&self) - } -} diff --git a/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift b/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift index baaed3ae..29a85ee2 100644 --- a/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift +++ b/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift @@ -379,15 +379,73 @@ extension _BTree { /// This 'consumes' the tree, however it expects the callee to retain the root of the tree for the duration of /// the cursors lifetime. /// - /// - Parameters: - /// - key: The key to search for - /// - mutable: whether a mutable cursor should be returned. + /// - Parameter key: The key to search for /// - Returns: A `cursor` to the key or where the key should be inserted, and a `found` /// parameter indicating whether or not the key exists within the tree, iff `found` is true, the cursor /// is concrete. /// - Complexity: O(`log n`) @inlinable - internal mutating func findAnyCursor( + internal mutating func takeCursor(at index: Index) -> UnsafeCursor { + var slots = index.childSlots + slots.append(UInt16(index.slot)) + + // Initialize parents with some dummy value filling it. + var parents = + UnsafeCursor.Path(repeating: .passUnretained(self.root.storage)) + + var ownedRoot: Node.Storage + do { + var tempRoot: Node.Storage? = nil + swap(&tempRoot, &self.root._storage) + ownedRoot = tempRoot.unsafelyUnwrapped + } + + var node: Unmanaged = .passUnretained(ownedRoot) + + // The depth containing the first instance of a shared + var lastUniqueDepth = isKnownUniquelyReferenced(&ownedRoot) ? 0 : -1 + var isOnUniquePath = isKnownUniquelyReferenced(&ownedRoot) + + for d in 0.. (cursor: UnsafeCursor, found: Bool) { var slots = Index.Offsets(repeating: 0) diff --git a/Sources/SortedCollections/BTree/_BTree.Builder.swift b/Sources/SortedCollections/BTree/_BTree.Builder.swift index 12d5da8a..7104e8d8 100644 --- a/Sources/SortedCollections/BTree/_BTree.Builder.swift +++ b/Sources/SortedCollections/BTree/_BTree.Builder.swift @@ -12,6 +12,10 @@ extension _BTree { /// Provides an interface for efficiently constructing a filled B-Tree from sorted data. /// + /// A builder supports duplicate keys, in which case they are inserted in the same order they are recieved. + /// However, is the `deduplicating` parameter is passed as `true`, operations will silently drop + /// duplicates. + /// /// This type has a few advantages when constructing a B-Tree over other approaches such as manually /// inserting each element or using a cursor: /// @@ -101,11 +105,19 @@ extension _BTree { @usableFromInline internal let internalCapacity: Int + @usableFromInline + internal let deduplicating: Bool + + @usableFromInline + internal var lastKey: Key? + /// Creates a new B-Tree builder with default capacities + /// - Parameter deduplicating: Whether duplicates should be removed. @inlinable @inline(__always) - internal init() { + internal init(deduplicating: Bool = false) { self.init( + deduplicating: deduplicating, leafCapacity: _BTree.defaultLeafCapacity, internalCapacity: _BTree.defaultInternalCapacity ) @@ -113,19 +125,27 @@ extension _BTree { /// Creates a new B-Tree builder with a custom uniform capacity configuration /// - Parameters: + /// - deduplicating: Whether duplicates should be removed. /// - capacity: The amount of elements per node. @inlinable @inline(__always) - internal init(capacity: Int) { - self.init(leafCapacity: capacity, internalCapacity: capacity) + internal init(deduplicating: Bool = false, capacity: Int) { + self.init( + deduplicating: deduplicating, + leafCapacity: capacity, + internalCapacity: capacity + ) } /// Creates a new B-Tree builder with a custom capacity configuration /// - Parameters: - /// - capacity: The amount of elements per node. + /// - deduplicating: Whether duplicates should be removed. + /// - leafCapacity: The amount of elements per leaf node. + /// - internalCapacity: The amount of elements per internal node. @inlinable @inline(__always) internal init( + deduplicating: Bool = false, leafCapacity: Int, internalCapacity: Int ) { @@ -138,6 +158,8 @@ extension _BTree { self._seedling = Node(withCapacity: leafCapacity, isLeaf: true) self.leafCapacity = leafCapacity self.internalCapacity = internalCapacity + self.deduplicating = deduplicating + self.lastKey = nil } /// Pops a sapling and it's associated seperator @@ -176,8 +198,16 @@ extension _BTree { /// Appends a new element to the tree /// - Parameter element: Element which is after all previous elements in sorted order. @inlinable - @inline(__always) internal mutating func append(_ element: __owned Element) { + assert(lastKey == nil || lastKey! <= element.key, + "New element must be non-decreasing.") + defer { lastKey = element.key } + if deduplicating { + if let lastKey = lastKey { + if lastKey == element.key { return } + } + } + switch state { case .addingSeperator: completeSeedling(withSeperator: element) @@ -200,7 +230,6 @@ extension _BTree { /// Declares that the current seedling is finished with insertion and creates a new seedling to /// further operate on. @inlinable - @inline(__always) internal mutating func completeSeedling( withSeperator newSeperator: __owned Element ) { @@ -311,7 +340,6 @@ extension _BTree { /// /// - Returns: A usable, fully-filled B-Tree @inlinable - @inline(__always) internal mutating func finish() -> _BTree { var root: Node = seedling _seedling = nil @@ -331,3 +359,12 @@ extension _BTree { } } } + +extension _BTree.Builder where Value == Void { + /// Appends a value to a B-Tree builder without values. + @inlinable + @inline(__always) + internal mutating func append(_ key: __owned Key) { + self.append((key, ())) + } +} diff --git a/Sources/SortedCollections/BTree/_BTree.swift b/Sources/SortedCollections/BTree/_BTree.swift index b331388b..1970649e 100644 --- a/Sources/SortedCollections/BTree/_BTree.swift +++ b/Sources/SortedCollections/BTree/_BTree.swift @@ -19,9 +19,6 @@ @usableFromInline internal struct _BTree { - // TODO: decide node capacity. Currently exploring 470 v 1050 - // TODO: better benchmarking here - /// Internal node size in bytes for B-Tree @inlinable @inline(__always) @@ -72,6 +69,19 @@ internal struct _BTree { @usableFromInline internal var version: Int + /// Creates a dummy B-Tree with no underlying node storage class. + /// + /// It is invalid and a serious error to ever attempt to read or write to such a B-Tree. + @inlinable + @inline(__always) + internal static var dummy: _BTree { + _BTree( + _rootedAtNode: _Node.dummy, + internalCapacity: 0, + version: 0 + ) + } + /// Creates an empty B-Tree with an automatically determined optimal capacity. @inlinable @inline(__always) @@ -91,7 +101,7 @@ internal struct _BTree { ) } - /// Creates an empty BTree which creates node with specified capacities + /// Creates an empty B-Tree which creates node with specified capacities /// - Parameters: /// - leafCapacity: The capacity of the leaf nodes. This is the initial buffer used to allocate. /// - internalCapacity: The capacity of the internal nodes. Generally prefered to be less than @@ -105,7 +115,7 @@ internal struct _BTree { ) } - /// Creates a BTree rooted at a specific nodey + /// Creates a B-Tree rooted at a specific nodey /// - Parameters: /// - root: The root node. /// - internalCapacity: The key capacity of new internal nodes. @@ -116,6 +126,18 @@ internal struct _BTree { self.internalCapacity = internalCapacity self.version = ObjectIdentifier(root.storage).hashValue } + + @inlinable + @inline(__always) + internal init( + _rootedAtNode root: Node, + internalCapacity: Int, + version: Int + ) { + self.root = root + self.internalCapacity = internalCapacity + self.version = version + } } // MARK: Mutating Operations @@ -196,7 +218,9 @@ extension _BTree { invalidateIndices() defer { self.checkInvariants() } - // TODO: Don't create CoW copy until needed. + // TODO: It is possible that there is a single transient CoW copied made + // if the removal results in the CoW copied node being completely removed + // from the tree. let removedElement = self.root.update { $0.removeAnyElement(forKey: key) } // Check if the tree height needs to be reduced @@ -311,23 +335,30 @@ extension _BTree { internal func findAnyIndex(forKey key: Key) -> Index? { var childSlots = Index.Offsets(repeating: 0) var node: Unmanaged? = .passUnretained(self.root.storage) + var offset: Int = 0 while let currentNode = node { let index: Index? = currentNode._withUnsafeGuaranteedRef { storage in storage.read { handle in let keySlot = handle.startSlot(forKey: key) + offset += keySlot + if keySlot < handle.elementCount && handle[keyAt: keySlot] == key { return Index( node: .passUnretained(storage), slot: keySlot, childSlots: childSlots, - offset: 0, + offset: offset, forTree: self ) } else { if handle.isLeaf { node = nil } else { + for i in 0..( _ transform: (Value) throws -> T ) rethrows -> _BTree { - // TODO: explore forEach vs iteration speed let root = try _Node( mappingFrom: self.root, transform diff --git a/Sources/SortedCollections/BTree/_FixedSizeArray.swift b/Sources/SortedCollections/BTree/_FixedSizeArray.swift index a1743090..51a6c652 100644 --- a/Sources/SortedCollections/BTree/_FixedSizeArray.swift +++ b/Sources/SortedCollections/BTree/_FixedSizeArray.swift @@ -17,98 +17,100 @@ /// do not put non-trivial types in this. @usableFromInline internal struct _FixedSizeArray { - @inlinable - @inline(__always) - internal static var maxSize: Int8 { 16 } - - @usableFromInline - internal var depth: Int8 - - @usableFromInline - internal var values: ( - Element, Element, Element, Element, - Element, Element, Element, Element, - Element, Element, Element, Element, - Element, Element, Element, Element + @inlinable + @inline(__always) + internal static var maxSize: Int8 { 16 } + + @usableFromInline + internal var depth: Int8 + + @usableFromInline + internal var values: ( + Element, Element, Element, Element, + Element, Element, Element, Element, + Element, Element, Element, Element, + Element, Element, Element, Element + ) + + @inlinable + @inline(__always) + internal init(repeating initialValue: Element, depth: Int8 = 0) { + self.depth = depth + self.values = ( + initialValue, initialValue, initialValue, initialValue, + initialValue, initialValue, initialValue, initialValue, + initialValue, initialValue, initialValue, initialValue, + initialValue, initialValue, initialValue, initialValue ) - - @inlinable - @inline(__always) - internal init(repeating initialValue: Element, depth: Int8 = 0) { - self.depth = depth - self.values = ( - initialValue, initialValue, initialValue, initialValue, - initialValue, initialValue, initialValue, initialValue, - initialValue, initialValue, initialValue, initialValue, - initialValue, initialValue, initialValue, initialValue - ) + } + + /// Appends a value to the offset list + @inlinable + @inline(__always) + internal mutating func append(_ value: __owned Element) { + assert(depth < _FixedSizeArray.maxSize, + "Out of bounds access in fixed sized array.") + defer { self.depth &+= 1 } + self[self.depth] = value + } + + /// Pops a value from the end of offset list + @inlinable + @inline(__always) + internal mutating func pop() -> Element { + assert(depth > 0, "Cannot pop empty fixed sized array") + self.depth &-= 1 + return self[self.depth] + } + + /// If the fixed size array is empty + @inlinable + @inline(__always) + internal var isEmpty: Bool { depth == 0 } + + /// Refers to the last value in the list + @inlinable + @inline(__always) + internal var last: Element { + get { + assert(depth > 0, "Out of bounds access in fixed sized array") + return self[depth &- 1] } - /// Appends a value to the offset list - @inlinable - @inline(__always) - internal mutating func append(_ value: __owned Element) { - assert(depth < _FixedSizeArray.maxSize, + _modify { + assert(depth > 0, "Out of bounds access in fixed sized array") + yield &self[depth &- 1] + } + } + + @inlinable + @inline(__always) + internal subscript(_ position: Int8) -> Element { + get { + assert(position <= depth && depth <= _FixedSizeArray.maxSize, "Out of bounds access in fixed sized array.") - defer { self.depth &+= 1 } - self[self.depth] = value + + return withUnsafeBytes(of: self.values) { values in + let p = values.baseAddress!.assumingMemoryBound(to: Element.self) + return p.advanced(by: Int(position)).pointee + } } - /// Pops a value from the end of offset list - @inlinable - @inline(__always) - internal mutating func pop() -> Element { - assert(depth > 0, "Cannot pop empty fixed sized array") - self.depth &-= 1 - return self[self.depth] - } - - /// If the fixed size array is empty - @inlinable - @inline(__always) - internal var isEmpty: Bool { depth == 0 } - - /// Refers to the last value in the list - @inlinable - @inline(__always) - internal var last: Element { - get { - assert(depth > 0, "Out of bounds access in fixed sized array") - return self[depth - 1] + _modify { + assert(position <= depth && depth <= _FixedSizeArray.maxSize, + "Out of bounds access in fixed sized array.") + + let ptr: UnsafeMutablePointer = + withUnsafeMutableBytes(of: &self.values) { values in + let p = values.baseAddress!.assumingMemoryBound(to: Element.self) + return p.advanced(by: Int(position)) } - _modify { - yield &self[depth - 1] - } - } - - @inlinable - internal subscript(_ position: Int8) -> Element { - get { - assert(position <= depth && depth <= _FixedSizeArray.maxSize, - "Out of bounds access in fixed sized array.") - - return withUnsafeBytes(of: self.values) { values in - let p = values.baseAddress!.assumingMemoryBound(to: Element.self) - return p.advanced(by: Int(position)).pointee - } - } - - _modify { - assert(position <= depth && depth <= _FixedSizeArray.maxSize, - "Out of bounds access in fixed sized array.") - - let ptr: UnsafeMutablePointer = - withUnsafeMutableBytes(of: &self.values) { values in - let p = values.baseAddress!.assumingMemoryBound(to: Element.self) - return p.advanced(by: Int(position)) - } - - var value = ptr.move() - defer { ptr.initialize(to: value) } - yield &value - } + var value = ptr.move() + defer { ptr.initialize(to: value) } + yield &value } + } } #if DEBUG diff --git a/Sources/SortedCollections/BTree/_Node.Storage.swift b/Sources/SortedCollections/BTree/_Node.Storage.swift index 64e326d9..b9cedf0a 100644 --- a/Sources/SortedCollections/BTree/_Node.Storage.swift +++ b/Sources/SortedCollections/BTree/_Node.Storage.swift @@ -31,7 +31,16 @@ extension _Node { self.depth = depth } - // Packed integer to store all node counts. + /// Packed integer to store all node counts. + /// + /// This is represented as: + /// + /// subtreeCount + /// vvvvvvv + /// 0x0000000FFFFFFF00 + /// ^^^^^^^ ^^ + /// count depth + /// @usableFromInline internal var _internalCounts: UInt64 @@ -86,7 +95,23 @@ extension _Node { internal var children: UnsafeMutablePointer<_Node>? } - /// Represents the underlying data for a node in the heap. + /// Represents the underlying data for a node. + /// + /// Generally, this shouldn't be directly accessed. However, in performance-critical code where operating + /// on a ``_Node`` may create unwanted ARC traffic, or other concern, this provides a few low-level + /// and unsafe APIs for operations. + /// + /// A node contains a tail-allocated contiguous buffer of keys, and also may maintain pointers to buffers + /// for the corresponding values and children. + /// + /// There are two types of nodes distinguished "leaf" and "internal" nodes. Leaf nodes do not have a + /// buffer allocated for their children in the underlying storage class. + /// + /// Additionally, a node does not have a value buffer allocated in some cases. Specifically, when the + /// value type is `Void`, no value buffer is allocated. ``_Node.hasValues`` can be used to check + /// whether a value buffer exists for a given set of generic parameters. Additionally, when a value buffer + /// does not exist, ``_Node.dummyValue`` can be used to obtain a valid value within the type system + /// that can be passed to APIs. @usableFromInline internal class Storage: ManagedBuffer<_Node.Header, Key> { /// Allows **read-only** access to the underlying data behind the node. @@ -108,7 +133,13 @@ extension _Node { } } - /// Allows **mutable** access to the underlying data behind the node. + /// Dangerously allows **mutable** access to the underlying data behind the node. + /// + /// This does **not** perform CoW checks and so when calling this, one must be certain that the + /// storage class is indeed unique. Generally this is the wrong function to call, and should only be used + /// when the callee has created and is guaranteed to be the only owner during the execution of the + /// update callback, _and_ it has been identified that ``_Node.update(_:)`` or other alternatives + /// result in noticable slow-down. /// /// - Parameter body: A closure with a handle which allows interacting with the node /// - Returns: The value the closure body returns, if any. @@ -121,7 +152,10 @@ extension _Node { try self.read { try body(UnsafeHandle(mutating: $0)) } } - /// Creates a new storage instance + /// Creates a new storage object. + /// + /// It is generally recommend to use the ``_Node.init(withCapacity:, isLeaf:)`` + /// initializer instead to create a new node. @inlinable @inline(__always) internal static func create( @@ -145,7 +179,9 @@ extension _Node { return unsafeDowncast(storage, to: Storage.self) } - /// Copies an existing storage to a new storage + /// Copies an existing storage to a new storage. + /// + /// It is generally recommended to use the ``_Node.init(copyingFrom:)`` initializer. @inlinable @inline(__always) internal func copy() -> Storage { diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift index db4fdf33..39c11b49 100644 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift @@ -441,8 +441,7 @@ extension _Node.UnsafeHandle { self.subtreeCount += 1 // TODO: might be more optimal to memcpy the right child, and avoid - // potentially creating a CoW copy of it. This will require more - // thinking + // potentially creating a CoW copy of it. // Move the right child's elements into the left child // ┌─┐ diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Equatable.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Equatable.swift deleted file mode 100644 index b6d05c15..00000000 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Equatable.swift +++ /dev/null @@ -1,32 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// This source file is part of the Swift Collections open source project -// -// Copyright (c) 2021 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// -//===----------------------------------------------------------------------===// - -//extension _Node.UnsafeHandle: Equatable where Key: Equatable, Value: Equatable { -// /// Compares whether the subtree rooted at the following node is equatable to another node -// // TODO: optimized node equality checking is non-trivial -// @inlinable -// @inline(__always) -// internal static func ==(lhs: Self, rhs: Self) -> Bool { -// // Two nodes of varying sizes cannot be equal -// if lhs.subtreeCount != rhs.subtreeCount { return false } -// -// // If two nodes share the same header, they are by pointer identity the same -// // node. -// if lhs.header == rhs.header { return true } -// -// -// for i in 0.. UnsafeHandle { - assertMutable() - assert(self.isLeaf, "Already internal node.") - let children: UnsafeMutablePointer<_Node> = - .allocate(capacity: self.capacity + 1) - - self.header.pointee.children = children - return UnsafeHandle( - keys: self.keys, - values: self.values, - children: children, - header: self.header, - isMutable: self.isMutable - ) - } } } // MARK: Subscript extension _Node.UnsafeHandle { - // TODO: elementAtSlot & others @inlinable @inline(__always) internal subscript(elementAt slot: Int) -> _Node.Element { diff --git a/Sources/SortedCollections/BTree/_Node.swift b/Sources/SortedCollections/BTree/_Node.swift index d122811e..3fca2543 100644 --- a/Sources/SortedCollections/BTree/_Node.swift +++ b/Sources/SortedCollections/BTree/_Node.swift @@ -9,11 +9,36 @@ // //===----------------------------------------------------------------------===// +/// A single node within a B-Tree, containing keys, values, and children. +/// +/// A node is merely struct wrapper of the ``_Node.Storage`` class. This does not and should not +/// contain any other properties. By using a ``_Node`` over the underlying storage class, operations can +/// be performed with automatic copy-on-write (CoW) checks such as through the ``update(_:)`` +/// method. +/// +/// Refer to ``_Node.Storage`` for more information on the allocation and structure of the underlying +/// buffers of a node. +/// +/// You cannot operate or read directly from a node. Instead use `read(_:)` and `update(_:)` to make +/// modifications to a node. +/// +/// let nodeMedian = node.read { handle in +/// let medianSlot = handle.elementCount +/// return handle[elementAt: medianSlot] +/// } +/// +/// Refer to ``_Node.UnsafeHandle`` for the APIs available when operating on a node in such a +/// manner. @usableFromInline internal struct _Node { @usableFromInline typealias Element = (key: Key, value: Value) + /// An optional parameter to the storage. Use ``storage`` instead + /// + /// This will never be `nil` during a valid access of ``_Node``. However, to support moving the + /// underlying storage instance for internal and unsafe operations, this is made optional as an + /// implementation artifact. @usableFromInline internal var _storage: Storage? @@ -22,6 +47,22 @@ internal struct _Node { @inline(__always) internal var storage: Storage { _storage.unsafelyUnwrapped } + /// An instance of a ``_Node`` with no underlying storage allocated. + /// + /// Use this when you need a dummy node. It is invalid to ever attempt to read or write to this node. + @inlinable + @inline(__always) + internal static var dummy: _Node { + _Node(_underlyingStorage: nil) + } + + /// Creates a node with a potentially empty underlying storage. + @inlinable + @inline(__always) + internal init(_underlyingStorage storage: Storage?) { + self._storage = storage + } + /// Creates a node wrapping a Storage object in order to interact with it. /// - Parameter storage: Underlying node storage. @inlinable @@ -310,6 +351,8 @@ extension _Node { // MARK: Equatable extension _Node: Equatable { + /// Whether two nodes are the same underlying reference in memory. + /// - Warning: This **does not** compare the keys at all. @inlinable @inline(__always) internal static func ==(lhs: _Node, rhs: _Node) -> Bool { diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomReflectable.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomReflectable.swift index b4f6c9f9..7f34e156 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomReflectable.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomReflectable.swift @@ -10,9 +10,6 @@ //===----------------------------------------------------------------------===// extension SortedDictionary: CustomReflectable { - // TODO: Review this implementation - // TODO: Implement nice playground output. - /// The custom mirror for this instance. public var customMirror: Mirror { Mirror(self, unlabeledChildren: self, displayStyle: .dictionary) diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomStringConvertible.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomStringConvertible.swift index 13eae744..49b63d2e 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomStringConvertible.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+CustomStringConvertible.swift @@ -10,8 +10,6 @@ //===----------------------------------------------------------------------===// extension SortedDictionary: CustomStringConvertible, CustomDebugStringConvertible { - // TODO: see if there is way to reduce boilerplate here - @inlinable public var description: String { if isEmpty { return "[:]" } diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Equatable.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Equatable.swift index fe8d03ab..cec7ae10 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Equatable.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Equatable.swift @@ -10,8 +10,6 @@ //===----------------------------------------------------------------------===// extension SortedDictionary: Equatable where Value: Equatable { - // TODO: look into more efficient ways to implement this - /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, @@ -23,7 +21,7 @@ extension SortedDictionary: Equatable where Value: Equatable { /// - Complexity: O(`self.count`) @inlinable public static func ==(lhs: SortedDictionary, rhs: SortedDictionary) -> Bool { - // TODO: optimize/benchmarking by comparing node identity. + // TODO: optimize/benchmarking by comparing node identity/shared subtrees. if lhs.count != rhs.count { return false } for ((k1, v1), (k2, v2)) in zip(lhs, rhs) { if k1 != k2 || v1 != v2 { diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift index 44f266fc..6916a6b4 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift @@ -71,7 +71,7 @@ extension SortedDictionary { var previousKey: Key? = nil for (key, value) in keysAndValues { - precondition(previousKey == nil || previousKey.unsafelyUnwrapped < key, + precondition(previousKey == nil || previousKey! < key, "Sequence out of order.") builder.append((key, value)) previousKey = key @@ -99,7 +99,7 @@ extension SortedDictionary { var previousKey: Key? = nil for (key, value) in keysAndValues { - assert(previousKey != nil && previousKey.unsafelyUnwrapped < key, + precondition(previousKey == nil || previousKey! < key, "Sequence out of order.") builder.append((key, value)) previousKey = key @@ -134,16 +134,10 @@ extension SortedDictionary { by keyForValue: (S.Element) throws -> Key ) rethrows where Value == [S.Element], S : Sequence { self.init() - // TODO: implement some way to take advantage of S.underestimateCapacity for value in values { let key = try keyForValue(value) - - // TODO: optimize to avoid CoW copying the array - if var group = self._root.findAnyValue(forKey: key) { + self.modifyValue(forKey: key, default: []) { group in group.append(value) - self._root.updateAnyValue(group, forKey: key) - } else { - self._root.updateAnyValue([value], forKey: key) } } } diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift index cf27383e..e23de48b 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift @@ -30,7 +30,7 @@ extension SortedDictionary { } _modify { - var (cursor, found) = self._root.findAnyCursor(forKey: key) + var (cursor, found) = self._root.takeCursor(forKey: key) var value: Value? if found { @@ -97,7 +97,7 @@ extension SortedDictionary { } _modify { - var (cursor, found) = self._root.findAnyCursor(forKey: key) + var (cursor, found) = self._root.takeCursor(forKey: key) var value: Value if found { @@ -152,8 +152,10 @@ extension SortedDictionary { /// - Complexity: O(1) @inlinable public subscript(position: Index) -> Element { - position._index.ensureValid(forTree: self._root) - return self._root[position._index] + get { + position._index.ensureValid(forTree: self._root) + return self._root[position._index] + } } /// Accesses a contiguous subrange of the collection's elements. diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Values.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Values.swift index a3fd112d..d185d724 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Values.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Values.swift @@ -210,10 +210,27 @@ extension SortedDictionary.Values { /// /// - Complexity: O(1) @inlinable - @inline(__always) public subscript(position: Index) -> Value { - // TODO: add setter & _modify attributes - self._base[position].value + get { + self._base[position].value + } + + _modify { + position._index.ensureValid(forTree: self._base._root) + + // Ensure we don't attempt to dereference the endIndex + precondition(position != endIndex, "Attempt to subscript out of range index.") + + var cursor = self._base._root.takeCursor(at: position._index) + var value = cursor.moveValue() + + defer { + cursor.initializeValue(to: value) + cursor.apply(to: &self._base._root) + } + + yield &value + } } } diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary.Index.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary.Index.swift index 2130c064..a8682110 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary.Index.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary.Index.swift @@ -36,7 +36,6 @@ extension SortedDictionary { // MARK: Equatable extension SortedDictionary.Index: Equatable { - // TODO: Potentially validate if lhs & rhs aren't pointing to deallocated dictionaries. @inlinable public static func ==(lhs: SortedDictionary.Index, rhs: SortedDictionary.Index) -> Bool { lhs._index.ensureValid(with: rhs._index) diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift index f16d0155..5c72e9d6 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift @@ -62,8 +62,8 @@ extension SortedDictionary { } _modify { - // TODO: avoid allocating a new node - var values = Values(_base: SortedDictionary()) + let dummyDict = SortedDictionary(_rootedAt: _BTree.dummy) + var values = Values(_base: dummyDict) swap(&self, &values._base) defer { self = values._base } yield &values @@ -108,7 +108,7 @@ extension SortedDictionary { default defaultValue: @autoclosure () -> Value, _ body: (inout Value) throws -> R ) rethrows -> R { - var (cursor, found) = self._root.findAnyCursor(forKey: key) + var (cursor, found) = self._root.takeCursor(forKey: key) let r: R if found { diff --git a/Sources/SortedCollections/SortedSet/SortedSet+CustomStringConvertible.swift b/Sources/SortedCollections/SortedSet/SortedSet+CustomStringConvertible.swift index ca877ae9..eeade805 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet+CustomStringConvertible.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet+CustomStringConvertible.swift @@ -10,8 +10,6 @@ //===----------------------------------------------------------------------===// extension SortedSet: CustomStringConvertible, CustomDebugStringConvertible { - // TODO: see if there is way to reduce boilerplate here - @inlinable public var description: String { var result = "[" diff --git a/Sources/SortedCollections/SortedSet/SortedSet+Equatable.swift b/Sources/SortedCollections/SortedSet/SortedSet+Equatable.swift index 907f684f..1818c1e1 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet+Equatable.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet+Equatable.swift @@ -10,8 +10,6 @@ //===----------------------------------------------------------------------===// extension SortedSet: Equatable { - // TODO: look into more efficient ways to implement this - /// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, diff --git a/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift b/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift index 8524996a..c5655710 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift @@ -24,5 +24,30 @@ extension SortedSet { } } - // TODO: potentially add unconditional + /// Creates a dictionary from a sequence of **sorted** elements. + /// + /// This is a more efficient alternative to ``init(_:)`` which offers + /// better asymptotic performance, and also reduces memory usage when constructing a + /// sorted set on a pre-sorted sequence. + /// + /// - Parameter elements: A sequence of elements in non-decreasing comparison order for the + /// new set. + /// - Complexity: O(`n`) where `n` is the number of elements in the + /// sequence. + @inlinable + public init( + sortedElements elements: S + ) where S.Element == Element { + var builder = _Tree.Builder() + + var previousElement: Element? = nil + for element in elements { + precondition(previousElement != nil && previousElement! < element, + "Sequence out of order.") + builder.append(element) + previousElement = element + } + + self.init(_rootedAt: builder.finish()) + } } diff --git a/Sources/SortedCollections/SortedSet/SortedSet+SetAlgebra.swift b/Sources/SortedCollections/SortedSet/SortedSet+SetAlgebra.swift index 1a17b321..f05df312 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet+SetAlgebra.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet+SetAlgebra.swift @@ -85,64 +85,201 @@ extension SortedSet: SetAlgebra { /// - Returns: A new sorted set with the unique elements of this set and `other`. /// - Note: if this set and `other` contain elements that are equal but /// distinguishable (e.g. via `===`), the element from the second set is inserted. - /// - Complexity: O(max(`self.count`, `other.count`)) + /// - Complexity: O(`self.count` + `other.count`) @inlinable public func union(_ other: __owned Self) -> Self { - var builder = _Tree.Builder() + var builder = _Tree.Builder(deduplicating: true) + + var it1 = self.makeIterator() + var it2 = other.makeIterator() + + var e1 = it1.next() + var e2 = it2.next() + + // While both sequences have a value, consume the smallest element. + while let el1 = e1, let el2 = e2 { + if el1 < el2 { + builder.append(el1) + e1 = it1.next() + } else { + builder.append(el2) + e2 = it2.next() + } + } + + while let el1 = e1 { + builder.append(el1) + e1 = it1.next() + } + + while let el2 = e2 { + builder.append(el2) + e2 = it2.next() + } + + return SortedSet(_rootedAt: builder.finish()) + } + + /// Adds the elements of the given set to the set. + /// + /// - Parameter other: A set of the same type as the current set. + /// - Note: if this set and `other` contain elements that are equal but + /// distinguishable (e.g. via `===`), the element from the second set is inserted. + /// - Complexity: O(`self.count` + `other.count`) + @inlinable + public mutating func formUnion(_ other: __owned Self) { + self = union(other) + } + + /// Returns a new set with the elements that are common to both this set and + /// the given set. + /// + /// - Parameter other: A set of the same type as the current set. + /// - Returns: A new set. + /// - Note: if this set and `other` contain elements that are equal but + /// distinguishable (e.g. via `===`), which of these elements is present + /// in the result is unspecified. + /// - Complexity: O(`self.count` + `other.count`) + @inlinable + public func intersection(_ other: Self) -> Self { + // We'll run this such that 'self' is the smallest array + // TODO: might want to consider uniqueness to minimize CoW copies. + var builder = _Tree.Builder(deduplicating: true) var it1 = self.makeIterator() var it2 = other.makeIterator() - while let e1 = it1.next(), let e2 = it2.next() { - if e1 <= e2 { - builder.append((e1, ())) -// while + var e1 = it1.next() + var e2 = it2.next() + + // While both sequences have a value, consume the smallest element. + while let el1 = e1, let el2 = e2 { + if el1 < el2 { + e1 = it1.next() + } else if el1 == el2 { + builder.append(el2) + e1 = it1.next() + e2 = it2.next() } else { - builder.append((e2, ())) + // el1 > el1 + e2 = it2.next() } } return SortedSet(_rootedAt: builder.finish()) } - @inlinable - public mutating func formUnion(_ other: __owned Self) { - for element in other { - self.insert(element) - } - } - - @inlinable - public func intersection(_ other: Self) -> Self { - var newSet = SortedSet() - for element in self { - if other.contains(element) { - newSet.insert(element) - } - } - return newSet - } - + /// Removes the elements of this set that aren't also in the given set. + /// + /// - Parameter other: A set of the same type as the current set. + /// - Note: if this set and `other` contain elements that are equal but + /// distinguishable (e.g. via `===`), which of these elements is present + /// in the result is unspecified. + /// - Complexity: O(`self.count` + `other.count`) @inlinable public mutating func formIntersection(_ other: Self) { - for element in self { - if !other.contains(element) { - self.remove(element) - } - } + self = intersection(other) } + /// Returns a new set with the elements that are either in this set or in the + /// given set, but not in both. + /// + /// - Parameter other: A set of the same type as the current set. + /// - Returns: A new set. + /// - Complexity: O(`self.count` + `other.count`) @inlinable public func symmetricDifference(_ other: Self) -> Self { - var newSet = self.union(other) - newSet.subtract(self.intersection(other)) - return newSet + var builder = _Tree.Builder(deduplicating: true) + + var it1 = self.makeIterator() + var it2 = other.makeIterator() + + var e1 = it1.next() + var e2 = it2.next() + + // While both sequences have a value, consume the smallest element. + while let el1 = e1, let el2 = e2 { + if el1 < el2 { + builder.append(el1) + e1 = it1.next() + } else if el2 < el1 { + builder.append(el2) + e2 = it2.next() + } else { + // e1 == e2 + e1 = it1.next() + e2 = it2.next() + } + } + + while let el1 = e1 { + builder.append(el1) + e1 = it1.next() + } + + while let el2 = e2 { + builder.append(el2) + e2 = it2.next() + } + + return SortedSet(_rootedAt: builder.finish()) } + /// Removes the elements of the set that are also in the given set and adds + /// the members of the given set that are not already in the set. + /// + /// - Parameter other: A set of the same type. + /// - Complexity: O(`self.count` + `other.count`) @inlinable public mutating func formSymmetricDifference(_ other: Self) { - self.formUnion(other) - self.subtract(self.intersection(other)) + self = self.symmetricDifference(other) + } + + /// Returns a new set containing the elements of this set that do not occur + /// in the given set. + /// + /// - Parameter other: A set of the same type as the current set. + /// - Returns: A new set. + /// - Complexity: O(`self.count` + `other.count`) + @inlinable + public func subtracting(_ other: Self) -> Self { + var builder = _Tree.Builder(deduplicating: true) + + var it1 = self.makeIterator() + var it2 = other.makeIterator() + + var e1 = it1.next() + var e2 = it2.next() + + // While both sequences have a value, consume the smallest element. + while let el1 = e1, let el2 = e2 { + if el1 < el2 { + builder.append(el1) + e1 = it1.next() + } else if el2 < el1 { + e2 = it2.next() + } else { + // e1 == e2 + e1 = it1.next() + e2 = it2.next() + } + } + + while let el1 = e1 { + builder.append(el1) + e1 = it1.next() + } + + return SortedSet(_rootedAt: builder.finish()) + } + + /// Removes the elements of the given set from this set. + /// + /// - Parameter other: A set of the same type as the current set. + /// - Complexity: O(`self.count` + `other.count`) + @inlinable + public mutating func subtract(_ other: SortedSet) { + self = self.subtracting(other) } // MARK: Comparing Sets @@ -156,6 +293,11 @@ extension SortedSet: SetAlgebra { @inlinable public func isSubset(of other: SortedSet) -> Bool { // TODO: could be worthwhile to evaluate recursive approach + // TODO: in some cases, it could be faster to search from the root each time + // Searching from the root is faster when: + // self.count < other.count / (log(other.count) - 1) + // This means when `other` is significantly larger than `self`, it may be + // faster to search from the root each time. if self.count > other.count { return false } var superIterator = other.makeIterator() @@ -178,4 +320,51 @@ extension SortedSet: SetAlgebra { return true } + + /// Returns a Boolean value that indicates whether this set is a strict + /// subset of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. + /// + /// - Parameter other: A set of the same type as the current set. + /// - Returns: `true` if the set is a strict subset of `other`; otherwise, + /// `false`. + /// - Complexity: O(`self.count` + `other.count`). + @inlinable + public func isStrictSubset(of other: SortedSet) -> Bool { + if self.count >= other.count { return false } + return self.isSubset(of: other) + } + + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// - Parameter other: A set of the same type as the current set. + /// - Returns: `true` if the set has no elements in common with `other`; + /// otherwise, `false`. + /// - Complexity: O(`self.count` + `other.count`). + @inlinable + public func isDisjoint(with other: SortedSet) -> Bool { + var it1 = self.makeIterator() + var it2 = other.makeIterator() + + var e1 = it1.next() + var e2 = it2.next() + + // While both sequences have a value, consume the smallest element. + while let el1 = e1, let el2 = e2 { + if el1 < el2 { + e1 = it1.next() + } else if el1 == el2 { + return false + } else { + // el1 > el2 + e2 = it2.next() + } + } + + return true + } } diff --git a/Sources/SortedCollections/SortedSet/SortedSet.Index.swift b/Sources/SortedCollections/SortedSet/SortedSet.Index.swift index d9de16b6..cfc48e8a 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet.Index.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet.Index.swift @@ -36,7 +36,6 @@ extension SortedSet { // MARK: Equatable extension SortedSet.Index: Equatable { - // TODO: Potentially validate if lhs & rhs aren't pointing to deallocated dictionaries. @inlinable public static func ==(lhs: SortedSet.Index, rhs: SortedSet.Index) -> Bool { lhs._index.ensureValid(with: rhs._index) diff --git a/Sources/SortedCollections/SortedSet/SortedSet.swift b/Sources/SortedCollections/SortedSet/SortedSet.swift index 03370484..e5bab54b 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet.swift @@ -35,23 +35,3 @@ public struct SortedSet { self._root = tree } } - -// MARK: Testing for Membership - -// MARK: Adding Elements -extension SortedSet { - // TODO: document - @inlinable - @inline(__always) - @discardableResult - public mutating func remove(atOffset offset: Int) -> Element { - return self._root.remove(atOffset: offset).key - } - - // TODO: document - @inlinable - @inline(__always) - public subscript(offset absoluteOffset: Int) -> Element { - return self._root.index(atOffset: absoluteOffset).element.key - } -}