diff --git a/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift b/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift index 28611d77..3b467254 100644 --- a/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift +++ b/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift @@ -20,11 +20,11 @@ extension _BTree { _ isIncluded: (Element) throws -> Bool ) rethrows -> _BTree { // TODO: optimize implementation to O(n) - var newTree: _BTree = _BTree() + var builder = Builder() for element in self where try isIncluded(element) { - newTree.updateAnyValue(element.value, forKey: element.key) + builder.append(element) } - return newTree + return builder.finish() } diff --git a/Sources/SortedCollections/BTree/_BTree+Sequence.swift b/Sources/SortedCollections/BTree/_BTree+Sequence.swift index de8de647..7ea459a5 100644 --- a/Sources/SortedCollections/BTree/_BTree+Sequence.swift +++ b/Sources/SortedCollections/BTree/_BTree+Sequence.swift @@ -10,106 +10,159 @@ //===----------------------------------------------------------------------===// extension _BTree: Sequence { + @inlinable + internal func forEach(_ body: (Element) throws -> Void) rethrows { + func loop(node: Unmanaged) throws { + try node._withUnsafeGuaranteedRef { storage in + try storage.read { handle in + for i in 0.. @usableFromInline - internal var parents: FixedSizeArray> - - @usableFromInline - internal var currentNode: Unmanaged - - @usableFromInline - internal var slot: Int + internal var path: FixedSizeArray> + /// Creates an iterator to the element within a tree corresponding to a specific index @inlinable @inline(__always) - internal init(tree: _BTree) { + internal init(forTree tree: _BTree, startingAt index: Index) { + self.tree = tree + self.slots = index.childSlots + self.slots.append(UInt16(index.slot)) + + self.path = .init(repeating: .passUnretained(tree.root.storage)) + + if self.tree.isEmpty { + return + } + + var node: Unmanaged = .passUnretained(tree.root.storage) + for depth in 0.. Element? { // Check slot sentinel value for end of tree. - if _slowPath(self.slot == -1) { + if _slowPath(path.isEmpty) { return nil } - return self.currentNode._withUnsafeGuaranteedRef { storage in + return path.last._withUnsafeGuaranteedRef { storage in storage.read({ handle in defer { // If we're not a leaf, descend to the next child if !handle.isLeaf { - self.parents.append(self.currentNode) - self.offsets.append(UInt16(self.slot + 1)) + // Go to the right child + slots.last += 1 + var nextNode: Unmanaged? = .passUnretained(handle[childAt: Int(slots.last)].storage) - // TODO: make these descents Unmanaged - var node = handle[childAt: self.slot + 1] - - while !node.read({ $0.isLeaf }) { - self.parents.append(.passUnretained(node.storage)) - self.offsets.append(0) - node = node.read({ $0[childAt: 0] }) + while let node = nextNode { + self.path.append(node) + self.slots.append(0) + + node._withUnsafeGuaranteedRef { + $0.read { handle in + if handle.isLeaf { + nextNode = nil + } else { + nextNode = .passUnretained(handle[childAt: 0].storage) + } + } + } } - - self.currentNode = .passUnretained(node.storage) - self.slot = 0 } else { - if self.slot < handle.elementCount - 1 { - self.slot += 1 + if slots.last < handle.elementCount - 1 { + slots.last += 1 } else { - while true { - if self.parents.depth == 0 { - self.slot = -1 - break + _ = path.pop() + _ = slots.pop() + + while !path.isEmpty { + let parent = path.last + let slot = slots.last + + let parentElementCount = parent._withUnsafeGuaranteedRef { + $0.read({ $0.elementCount }) } - // If we are at a leaf, then ascend to the - let parent = self.parents.pop() - let offset = self.offsets.pop() - - let parentElements = parent._withUnsafeGuaranteedRef { $0.read({ $0.elementCount }) } - - if offset < parentElements { - self.currentNode = parent - self.slot = Int(offset) + if slot < parentElementCount { break + } else { + _ = path.pop() + _ = slots.pop() } } } } } - return storage.read({ $0[elementAtSlot: self.slot] }) + return storage.read({ $0[elementAt: Int(slots.last)] }) }) } } @@ -117,6 +170,6 @@ extension _BTree: Sequence { @inlinable internal func makeIterator() -> Iterator { - return Iterator(tree: self) + return Iterator(forTree: self) } } diff --git a/Sources/SortedCollections/BTree/_BTree+SubSequence.swift b/Sources/SortedCollections/BTree/_BTree+SubSequence.swift new file mode 100644 index 00000000..246ae497 --- /dev/null +++ b/Sources/SortedCollections/BTree/_BTree+SubSequence.swift @@ -0,0 +1,181 @@ +//===----------------------------------------------------------------------===// +// +// 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 { + @usableFromInline + internal struct SubSequence { + @usableFromInline + internal let _base: _BTree + + @usableFromInline + internal var _startIndex: Index + + @usableFromInline + internal var _endIndex: Index + + @inlinable + @inline(__always) + internal init(base: _BTree, bounds: Range) { + self._base = base + self._startIndex = bounds.lowerBound + self._endIndex = bounds.upperBound + } + + /// The underlying collection of the subsequence. + @inlinable + @inline(__always) + internal var base: _BTree { _base } + } +} + +extension _BTree.SubSequence: Sequence { + @usableFromInline + internal typealias Element = _BTree.Element + + + @usableFromInline + internal struct Iterator: IteratorProtocol { + @usableFromInline + internal typealias Element = SubSequence.Element + + @usableFromInline + internal var _iterator: _BTree.Iterator + + @usableFromInline + internal var distanceRemaining: Int + + @inlinable + @inline(__always) + internal init(_iterator: _BTree.Iterator, distance: Int) { + self._iterator = _iterator + self.distanceRemaining = distance + } + + @inlinable + @inline(__always) + internal mutating func next() -> Element? { + if distanceRemaining == 0 { + return nil + } else { + distanceRemaining -= 1 + return _iterator.next() + } + } + } + + @inlinable + @inline(__always) + internal func makeIterator() -> Iterator { + let it = _BTree.Iterator(forTree: _base, startingAt: _startIndex) + let distance = _base.distance(from: _startIndex, to: _endIndex) + return Iterator(_iterator: it, distance: distance) + } +} + +extension _BTree.SubSequence: BidirectionalCollection { + @usableFromInline + internal typealias Index = _BTree.Index + + @usableFromInline + internal typealias SubSequence = Self + + + @inlinable + @inline(__always) + internal var startIndex: Index { _startIndex } + + @inlinable + @inline(__always) + internal var endIndex: Index { _endIndex } + + @inlinable + @inline(__always) + internal var count: Int { _base.distance(from: _startIndex, to: _endIndex) } + + @inlinable + @inline(__always) + internal func distance(from start: Index, to end: Index) -> Int { + _base.distance(from: start, to: end) + } + + @inlinable + @inline(__always) + internal func index(before i: Index) -> Index { + _base.index(before: i) + } + + @inlinable + @inline(__always) + internal func formIndex(before i: inout Index) { + _base.formIndex(before: &i) + } + + + @inlinable + @inline(__always) + internal func index(after i: Index) -> Index { + _base.index(after: i) + } + + @inlinable + @inline(__always) + internal func formIndex(after i: inout Index) { + _base.formIndex(after: &i) + } + + @inlinable + @inline(__always) + internal func index(_ i: Index, offsetBy distance: Int) -> Index { + _base.index(i, offsetBy: distance) + } + + @inlinable + @inline(__always) + internal func formIndex(_ i: inout Index, offsetBy distance: Int) { + _base.formIndex(&i, offsetBy: distance) + } + + @inlinable + @inline(__always) + internal func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + _base.index(i, offsetBy: distance, limitedBy: limit) + } + + @inlinable + @inline(__always) + internal func formIndex(_ i: inout Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool { + _base.formIndex(&i, offsetBy: distance, limitedBy: limit) + } + + + @inlinable + @inline(__always) + internal subscript(position: Index) -> Element { + _failEarlyRangeCheck(position, bounds: startIndex..) { + _base._failEarlyRangeCheck(index, bounds: bounds) + } + + @inlinable + @inline(__always) + public func _failEarlyRangeCheck(_ range: Range, bounds: Range) { + _base._failEarlyRangeCheck(range, bounds: bounds) + } +} + +// TODO: implement partial RangeReplaceableCollection methods diff --git a/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift b/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift index a5618adc..6af00bad 100644 --- a/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift +++ b/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift @@ -238,6 +238,28 @@ extension _BTree { return result } + /// Moves the value from the cursor's position + @inlinable + @inline(__always) + internal mutating func moveValue() -> Value { + guard Node.hasValues else { return Node.dummyValue } + + return self.updateCurrentNode { handle, slot in + handle.pointerToValue(atSlot: slot).move() + } + } + + /// Initializes a value for a cursor that points to an element that has a hole for its value. + @inlinable + @inline(__always) + internal mutating func initializeValue(to value: Value) { + guard Node.hasValues else { return } + + self.updateCurrentNode { handle, slot in + handle.pointerToValue(atSlot: slot).initialize(to: value) + } + } + /// Inserts a key-value pair at a position within the tree. /// /// Invalidates the cursor. Returns a splinter object which owning the new tree. @@ -256,8 +278,6 @@ extension _BTree { assertValid() defer { self._declareUnique() } - // TODO: make this not invalidate the cursor by updating slots - var (node, splinter) = self.updateNode(at: path.depth - 1) { handle, slot in handle.insertElement(element, withRightChild: nil, atSlot: slot) } @@ -265,8 +285,6 @@ extension _BTree { // Start the node above the bottom-most node, and propogate up the change var depth = path.depth - 2 while depth >= 0 { - // TODO: optimize this by stopping descent once we reach the unique - // section if splinter == nil && depth < lastUniqueDepth { return } let (newNode, _) = self.updateNode(at: depth) { (handle, slot) in @@ -410,7 +428,7 @@ extension _BTree { slots.append(UInt16(slot)) node = .passUnretained(handle[childAt: slot].storage) - if isOnUniquePath && isKnownUniquelyReferenced(&handle[childAt: slot].storage) { + if isOnUniquePath && handle.isChildUnique(atSlot: slot) { lastUniqueDepth += 1 } else { isOnUniquePath = false diff --git a/Sources/SortedCollections/BTree/_BTree.FixedSizeArray.swift b/Sources/SortedCollections/BTree/_BTree.FixedSizeArray.swift index 1e7d3237..247a5bce 100644 --- a/Sources/SortedCollections/BTree/_BTree.FixedSizeArray.swift +++ b/Sources/SortedCollections/BTree/_BTree.FixedSizeArray.swift @@ -10,6 +10,7 @@ //===----------------------------------------------------------------------===// extension _BTree { + /// A stack-allocated deque of some values. /// /// The supports efficient removals from and insertions to the beginning and end. @@ -105,6 +106,25 @@ extension _BTree { return self[0] } + /// 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: Value { + get { + assert(depth > 0, "Out of bounds access in fixed sized array") + return self[depth - 1] + } + + _modify { + yield &self[depth - 1] + } + } + @inlinable @inline(__always) internal subscript(_ position: Int8) -> Value { @@ -114,51 +134,25 @@ extension _BTree { let offset = _underlyingOffset(for: position) - switch offset { - case 0: return self.values.0 - case 1: return self.values.1 - case 2: return self.values.2 - case 3: return self.values.3 - case 4: return self.values.4 - case 5: return self.values.5 - case 6: return self.values.6 - case 7: return self.values.7 - case 8: return self.values.8 - case 9: return self.values.9 - case 10: return self.values.10 - case 11: return self.values.11 - case 12: return self.values.12 - case 13: return self.values.13 - case 14: return self.values.14 - case 15: return self.values.15 - default: preconditionFailure("Packed offset list too small.") + return withUnsafePointer(to: self.values) { values in + values.withMemoryRebound(to: Value.self, capacity: Int(FixedSizeArray.maxSize)) { buffer in + buffer.advanced(by: Int(offset)).pointee + } } } - _modify { + set { assert(position <= depth && depth <= FixedSizeArray.maxSize, "Out of bounds access in fixed sized array.") let offset = _underlyingOffset(for: position) - switch offset { - case 0: yield &self.values.0 - case 1: yield &self.values.1 - case 2: yield &self.values.2 - case 3: yield &self.values.3 - case 4: yield &self.values.4 - case 5: yield &self.values.5 - case 6: yield &self.values.6 - case 7: yield &self.values.7 - case 8: yield &self.values.8 - case 9: yield &self.values.9 - case 10: yield &self.values.10 - case 11: yield &self.values.11 - case 12: yield &self.values.12 - case 13: yield &self.values.13 - case 14: yield &self.values.14 - case 15: yield &self.values.15 - default: preconditionFailure("Packed offset list too small.") + return withUnsafeMutablePointer(to: &self.values) { values in + values.withMemoryRebound(to: Value.self, capacity: Int(FixedSizeArray.maxSize)) { buffer in + let ptr = buffer.advanced(by: Int(offset)) + ptr.deinitialize(count: 1) + ptr.initialize(to: newValue) + } } } } diff --git a/Sources/SortedCollections/BTree/_BTree.Index.swift b/Sources/SortedCollections/BTree/_BTree.Index.swift index 38c60d10..5c486fe5 100644 --- a/Sources/SortedCollections/BTree/_BTree.Index.swift +++ b/Sources/SortedCollections/BTree/_BTree.Index.swift @@ -116,7 +116,7 @@ extension _BTree.Index { @inline(__always) internal var element: _BTree.Element { assert(self.slot != -1, "Cannot dereference out-of-bounds slot.") - return self.readNode { $0[elementAtSlot: self.slot] } + return self.readNode { $0[elementAt: self.slot] } } } diff --git a/Sources/SortedCollections/BTree/_BTree.swift b/Sources/SortedCollections/BTree/_BTree.swift index 6fe4e58d..95680fd1 100644 --- a/Sources/SortedCollections/BTree/_BTree.swift +++ b/Sources/SortedCollections/BTree/_BTree.swift @@ -521,3 +521,20 @@ extension _BTree { } } + +// MARK: Immutable Operatoins +extension _BTree { + @inlinable + @inline(__always) + public func mapValues( + _ transform: (Value) throws -> T + ) rethrows -> _BTree { + // TODO: explore forEach vs iteration speed + let root = try _Node( + mappingFrom: self.root, + transform + ) + + return _BTree(rootedAt: root, internalCapacity: internalCapacity) + } +} diff --git a/Sources/SortedCollections/BTree/_Node+Testing.swift b/Sources/SortedCollections/BTree/_Node+Testing.swift index 54c79fe3..453dffb9 100644 --- a/Sources/SortedCollections/BTree/_Node+Testing.swift +++ b/Sources/SortedCollections/BTree/_Node+Testing.swift @@ -26,7 +26,7 @@ extension _Node { 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) + handle.values?.advanced(by: index).initialize(to: value) } if let children = children { @@ -47,12 +47,12 @@ extension _Node { public func toArray() -> [Element] { self.read { handle in if handle.isLeaf { - return Array((0.., + values: UnsafeMutablePointer?, children: UnsafeMutablePointer<_Node>? ) { self.capacity = capacity @@ -40,7 +40,7 @@ extension _Node { /// Pointer to the buffer containing the corresponding values. @usableFromInline - internal var values: UnsafeMutablePointer + internal var values: UnsafeMutablePointer? /// Pointer to the buffer containing the elements. @usableFromInline @@ -94,7 +94,9 @@ extension _Node { capacity: capacity, count: 0, totalElements: 0, - values: UnsafeMutablePointer.allocate(capacity: capacity), + values: + Value.self == Void.self ? nil + : UnsafeMutablePointer.allocate(capacity: capacity), children: isLeaf ? nil : UnsafeMutablePointer<_Node>.allocate(capacity: capacity + 1) ) @@ -123,8 +125,13 @@ extension _Node { } } - newStorage.header.values - .initialize(from: self.header.values, count: count) + if _Node.hasValues { + newStorage.header.values.unsafelyUnwrapped + .initialize( + from: self.header.values.unsafelyUnwrapped, + count: count + ) + } newStorage.header.children? .initialize( @@ -138,7 +145,7 @@ extension _Node { @inlinable deinit { self.withUnsafeMutablePointers { header, elements in - header.pointee.values.deallocate() + header.pointee.values?.deallocate() header.pointee.children?.deallocate() elements.deinitialize(count: header.pointee.count) diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift index 1720b495..7a65642b 100644 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift @@ -92,8 +92,12 @@ extension _Node.UnsafeHandle: CustomDebugStringConvertible { result += "┣━ " } - debugPrint(_node[keyAt: slot], terminator: ": ", to: &result) - debugPrint(_node[valueAt: slot], terminator: "", to: &result) + if _Node.hasValues { + debugPrint(_node[keyAt: slot], terminator: ": ", to: &result) + debugPrint(_node[valueAt: slot], terminator: "", to: &result) + } else { + debugPrint(_node[keyAt: slot], terminator: "", to: &result) + } if !_node.isLeaf && slot == _node.elementCount - 1 { let childDescription = _node[childAt: slot + 1].read { @@ -122,9 +126,13 @@ extension _Node.UnsafeHandle: CustomDebugStringConvertible { } else { result += ", " } - result += "(" - debugPrint(self[keyAt: slot], terminator: ", ", to: &result) - debugPrint(self[valueAt: slot], terminator: ")", to: &result) + if _Node.hasValues { + result += "(" + debugPrint(self[keyAt: slot], terminator: ", ", to: &result) + debugPrint(self[valueAt: slot], terminator: ")", to: &result) + } else { + debugPrint(self[keyAt: slot], terminator: "", to: &result) + } } result += "], " if let children = self.children { diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift index 263b8289..aa644148 100644 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift @@ -13,7 +13,7 @@ extension _Node.UnsafeHandle { @usableFromInline @frozen - internal enum InsertionResult { + internal enum UpdateResult { case updated(previousElement: _Node.Element) case splintered(_Node.Splinter) case inserted @@ -50,7 +50,7 @@ extension _Node.UnsafeHandle { _ value: Value, forKey key: Key, updatingKey: Bool - ) -> InsertionResult { + ) -> UpdateResult { assertMutable() let insertionIndex = self.endSlot(forKey: key) @@ -61,8 +61,13 @@ extension _Node.UnsafeHandle { // TODO: concerned about copy here let oldKey = self.keys.advanced(by: insertionIndex - 1).pointee - let oldValue = self.values.advanced(by: insertionIndex - 1).move() - self.values.advanced(by: insertionIndex - 1).initialize(to: value) + let oldValue: Value + if _Node.hasValues { + oldValue = self.pointerToValue(atSlot: insertionIndex - 1).move() + self.pointerToValue(atSlot: insertionIndex - 1).initialize(to: value) + } else { + oldValue = _Node.dummyValue + } return .updated(previousElement: (oldKey, oldValue)) } else { @@ -83,7 +88,7 @@ extension _Node.UnsafeHandle { withRightChild: nil, atSlot: insertionIndex ) - return InsertionResult(from: maybeSplinter) + return UpdateResult(from: maybeSplinter) } else { let result = self[childAt: insertionIndex].update { $0.updateAnyValue(value, forKey: key, updatingKey: updatingKey) @@ -94,7 +99,7 @@ extension _Node.UnsafeHandle { return result case .splintered(let splinter): let splinter = self.insertSplinter(splinter, atSlot: insertionIndex) - return InsertionResult(from: splinter) + return UpdateResult(from: splinter) case .inserted: self.subtreeCount += 1 return .inserted @@ -167,9 +172,9 @@ extension _Node.UnsafeHandle { // This branch is almost certainly correct splinterElement = self.moveElement(atSlot: rightMedian) + let insertionSlotInRightNode = insertionSlot - (rightMedian + 1) + rightNode.update { rightHandle in - let insertionSlotInRightNode = insertionSlot - (rightMedian + 1) - self.moveInitializeElements( count: insertionSlotInRightNode, fromSlot: rightMedian + 1, diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle.swift index e81aef7b..ab304816 100644 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle.swift +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle.swift @@ -19,7 +19,7 @@ extension _Node { internal let keys: UnsafeMutablePointer @usableFromInline - internal let values: UnsafeMutablePointer + internal let values: UnsafeMutablePointer? @usableFromInline internal let children: UnsafeMutablePointer<_Node>? @@ -28,7 +28,7 @@ extension _Node { @inline(__always) internal init( keys: UnsafeMutablePointer, - values: UnsafeMutablePointer, + values: UnsafeMutablePointer?, children: UnsafeMutablePointer<_Node>?, header: UnsafeMutablePointer
, isMutable: Bool @@ -118,8 +118,8 @@ extension _Node { @inlinable @inline(__always) internal var childCount: Int { - assert(!self.isLeaf, "Cannot access the child count on a leaf.") - return self.elementCount &+ 1 + assert(!isLeaf, "Cannot access the child count on a leaf.") + return elementCount &+ 1 } /// Whether the node is the bottom-most node (a leaf) within its tree. @@ -147,8 +147,25 @@ extension _Node { @inline(__always) internal var isBalanced: Bool { elementCount >= minimumElementCount } + /// Whether the immediate node does not have space for an additional element + @inlinable + @inline(__always) + internal var isFull: Bool { elementCount == capacity } + // TODO: see if deinitializer can add 0 element check for internal nodes. + /// Checks uniqueness of a child. + /// + /// - Warning: Will trap if executed on leaf nodes + @inlinable + @inline(__always) + internal func isChildUnique(atSlot slot: Int) -> Bool { + assert(!self.isLeaf, "Cannot access children on leaf.") + return isKnownUniquelyReferenced( + &self.pointerToChild(atSlot: slot).pointee._storage + ) + } + /// Indicates that the node has no more children and is ready for deallocation /// /// It is critical to ensure that there are absolutely no children or element references @@ -156,9 +173,33 @@ extension _Node { @inlinable @inline(__always) internal func drop() { + assertMutable() assert(self.elementCount == 0, "Cannot drop non-empty node") + self.header.pointee.children?.deallocate() self.header.pointee.children = nil } + + // TODO: test performance between __consuming and passing UnsafeHandle as + // inout. + /// Converts a leaf node into an internal node, without adjusting its capacity. + /// - Returns: A new unsafe handle to operate on. The old node is still mutated. + @inlinable + @inline(__always) + internal __consuming func convertToInternalNode() -> UnsafeHandle { + assertMutable() + assert(self.isLeaf, "Already internal node.") + let children: UnsafeMutablePointer<_Node> = + .allocate(capacity: self.capacity + 1) + + self.header.pointee.children = children + return UnsafeHandle( + keys: self.keys, + values: self.values, + children: children, + header: self.header, + isMutable: self.isMutable + ) + } } } @@ -167,11 +208,11 @@ extension _Node.UnsafeHandle { // TODO: elementAtSlot & others @inlinable @inline(__always) - internal subscript(elementAtSlot slot: Int) -> _Node.Element { + internal subscript(elementAt slot: Int) -> _Node.Element { get { assert(0 <= slot && slot < self.elementCount, "Node element subscript out of bounds.") - return (key: self.keys[slot], value: self.values[slot]) + return (key: self[keyAt: slot], value: self[valueAt: slot]) } } @@ -202,9 +243,10 @@ extension _Node.UnsafeHandle { internal func pointerToValue( atSlot slot: Int ) -> UnsafeMutablePointer { - assert(0 <= slot && slot < self.elementCount, + assert(0 <= slot && slot < elementCount, "Node value slot out of bounds.") - return self.values.advanced(by: slot) + assert(_Node.hasValues, "Node does not have value buffer.") + return values.unsafelyUnwrapped.advanced(by: slot) } @inlinable @@ -213,7 +255,18 @@ extension _Node.UnsafeHandle { get { assert(0 <= slot && slot < self.elementCount, "Node values subscript out of bounds.") - return self.values[slot] + assert(_Node.hasValues, "Node does not have value buffer.") + return self.pointerToValue(atSlot: slot).pointee + } + + nonmutating _modify { + assertMutable() + assert(0 <= slot && slot < self.elementCount, + "Node values subscript out of bounds.") + assert(_Node.hasValues, "Node does not have value buffer.") + var value = self.pointerToValue(atSlot: slot).move() + yield &value + self.pointerToValue(atSlot: slot).initialize(to: value) } } @@ -241,6 +294,7 @@ extension _Node.UnsafeHandle { } nonmutating _modify { + assertMutable() assert(!isLeaf, "Cannot modify children of leaf node.") assert(0 <= slot && slot < self.childCount, "Node child subscript out of bounds") @@ -338,8 +392,13 @@ extension _Node.UnsafeHandle { target.keys.advanced(by: destinationSlot) .moveInitialize(from: self.keys.advanced(by: sourceSlot), count: count) - target.values.advanced(by: destinationSlot) - .moveInitialize(from: self.values.advanced(by: sourceSlot), count: count) + if _Node.hasValues { + target.values.unsafelyUnwrapped.advanced(by: destinationSlot) + .moveInitialize( + from: self.values.unsafelyUnwrapped.advanced(by: sourceSlot), + count: count + ) + } } /// Moves children from the current handle to a new handle @@ -462,7 +521,9 @@ extension _Node.UnsafeHandle { "Cannot insert beyond node capacity.") self.keys.advanced(by: slot).initialize(to: element.key) - self.values.advanced(by: slot).initialize(to: element.value) + if _Node.hasValues { + self.values.unsafelyUnwrapped.advanced(by: slot).initialize(to: element.value) + } } /// Moves an element out of the handle and returns it. @@ -484,8 +545,10 @@ extension _Node.UnsafeHandle { "Attempted to move out-of-bounds element.") return ( - key: self.keys.advanced(by: slot).move(), - value: self.values.advanced(by: slot).move() + key: self.pointerToKey(atSlot: slot).move(), + value: _Node.hasValues + ? self.pointerToValue(atSlot: slot).move() + : _Node.dummyValue ) } @@ -508,6 +571,56 @@ extension _Node.UnsafeHandle { return self.children.unsafelyUnwrapped.advanced(by: slot).move() } + /// Inserts an element at the end of the node + /// + /// This adjusts element counts. + /// + /// - Parameter newElement: The new element to insert. + @inlinable + @inline(__always) + internal func appendElement(_ element: _Node.Element) { + assertMutable() + assert(elementCount < capacity, "Cannot append into full node") + assert(elementCount == 0 || self[keyAt: elementCount - 1] <= element.key, + "Cannot append out-of-order element.") + + initializeElement( + atSlot: capacity - 1, + to: element + ) + + elementCount += 1 + subtreeCount += 1 + } + + /// Inserts a splinter at the end of the node + @inlinable + @inline(__always) + internal func appendSplinter(_ splinter: _Node.Splinter) -> _Node.Splinter? { + assertMutable() + return self.appendElement( + splinter.element, + withRightChild: splinter.rightChild + ) + } + + /// Appends a new element with a provided right child. + @inlinable + @inline(__always) + internal func appendElement( + _ element: _Node.Element, + withRightChild rightChild: _Node) -> _Node.Splinter? { + assertMutable() + assert(elementCount < capacity, "Cannot append into full node") + assert(elementCount == 0 || self[keyAt: elementCount - 1] <= element.key, + "Cannot append out-of-order element.") + return insertElement( + element, + withRightChild: rightChild, + atSlot: elementCount + ) + } + /// Swaps the element at a given slot, returning the old one. /// - Parameters: /// - slot: The initialized slot at which to swap the element diff --git a/Sources/SortedCollections/BTree/_Node.swift b/Sources/SortedCollections/BTree/_Node.swift index 130f1a8a..0c8ebedd 100644 --- a/Sources/SortedCollections/BTree/_Node.swift +++ b/Sources/SortedCollections/BTree/_Node.swift @@ -20,24 +20,80 @@ internal struct _Node { /// Strong reference to the node's underlying data @inlinable @inline(__always) - internal var storage: Storage { - get { _storage.unsafelyUnwrapped } - set { _storage = newValue } - } + internal var storage: Storage { _storage.unsafelyUnwrapped } /// 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 + self._storage = storage + } + + /// Creates a new node with values modified by a transformation closure + @inlinable + @inline(__always) + internal init( + mappingFrom existingNode: _Node, + _ transform: (T) throws -> Value + ) rethrows { + let isLeaf = existingNode.storage.header.children == nil + _storage = .create( + withCapacity: existingNode.storage.header.capacity, + isLeaf: isLeaf + ) + + let elementCount = existingNode.storage.header.count + storage.header.count = elementCount + storage.header.subtreeCount = existingNode.storage.header.subtreeCount + + storage.withUnsafeMutablePointerToElements { keys in + existingNode.storage.withUnsafeMutablePointerToElements { sourceKeys in + keys.initialize(from: sourceKeys, count: existingNode.storage.header.count) + } + } + + for i in 0...dummyValue + ) + + storage.header.values.unsafelyUnwrapped + .advanced(by: i) + .initialize(to: newValue) + } + + if !isLeaf { + let oldChild = existingNode.storage.header + .children.unsafelyUnwrapped + .advanced(by: i) + .pointee + + storage.header.children.unsafelyUnwrapped + .advanced(by: i) + .initialize(to: try _Node(mappingFrom: oldChild, transform)) + } + } + + if !isLeaf { + let oldChild = existingNode.storage.header + .children.unsafelyUnwrapped + .advanced(by: elementCount) + .pointee + + storage.header.children.unsafelyUnwrapped + .advanced(by: elementCount) + .initialize(to: try _Node(mappingFrom: oldChild, transform)) + } } /// Creates a node which copies the storage of an existing node. @inlinable @inline(__always) internal init(copyingFrom oldNode: _Node) { - self.storage = oldNode.storage.copy() + self._storage = oldNode.storage.copy() } /// Creates and allocates a new node. @@ -46,7 +102,22 @@ internal struct _Node { /// - isLeaf: whether or not the node is a leaf (it does not have any children). @inlinable internal init(withCapacity capacity: Int, isLeaf: Bool) { - self.storage = Storage.create(withCapacity: capacity, isLeaf: isLeaf) + self._storage = Storage.create(withCapacity: capacity, isLeaf: isLeaf) + } + + /// Whether the B-Tree has values associated with the keys + @inlinable + @inline(__always) + internal static var hasValues: Bool { _fastPath(Value.self != Void.self) } + + /// Dummy value for when a B-Tree does not maintain a value buffer. + /// + /// - Warning: Traps when used on a tree with a value buffer. + @inlinable + @inline(__always) + internal static var dummyValue: Value { + assert(!hasValues, "Cannot get dummy value on tree with value buffer.") + return unsafeBitCast((), to: Value.self) } } @@ -103,7 +174,7 @@ extension _Node { /// elements if necessary. @inlinable internal mutating func ensureUnique() { - if !isKnownUniquelyReferenced(&self.storage) { + if !isKnownUniquelyReferenced(&self._storage) { self = _Node(copyingFrom: self) } } diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+BidirectionalCollection.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+BidirectionalCollection.swift index b699ad26..a9027a3f 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+BidirectionalCollection.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+BidirectionalCollection.swift @@ -11,12 +11,15 @@ 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. + /// + /// - Complexity: O(1) @inlinable @inline(__always) public var isEmpty: Bool { self._root.isEmpty } @@ -25,7 +28,7 @@ extension SortedDictionary: BidirectionalCollection { /// /// If the collection is empty, `startIndex` is equal to `endIndex`. /// - /// - Complexity: O(`log n`) + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public var startIndex: Index { Index(self._root.startIndex) } @@ -40,6 +43,13 @@ extension SortedDictionary: BidirectionalCollection { @inline(__always) public var endIndex: Index { Index(self._root.endIndex) } + /// 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. + /// - Complexity: O(1) @inlinable public func distance(from start: Index, to end: Index) -> Int { start._index.ensureValid(forTree: self._root) @@ -47,39 +57,119 @@ extension SortedDictionary: BidirectionalCollection { return self._root.distance(from: start._index, to: end._index) } + /// Replaces the given index with its successor. + /// + /// - Parameter index: A valid index of the collection. `index` must be less than `endIndex`. + /// - Complexity: O(log(`self.count`)) in the worst-case. @inlinable public func formIndex(after index: inout Index) { index._index.ensureValid(forTree: self._root) self._root.formIndex(after: &index._index) } + /// Returns the position immediately after the given index. + /// + /// - Parameter index: A valid index of the collection. `index` must be less than `endIndex`. + /// - Returns: The index value immediately after `index`. + /// - Complexity: O(log(`self.count`)) in the worst-case. @inlinable public func index(after index: Index) -> Index { index._index.ensureValid(forTree: self._root) return Index(self._root.index(after: index._index)) } + /// Replaces the given index with its predecessor. + /// + /// - Parameter index: A valid index of the collection. `index` must be greater + /// than `startIndex`. + /// - Complexity: O(log(`self.count`)) in the worst-case. @inlinable public func formIndex(before index: inout Index) { index._index.ensureValid(forTree: self._root) self._root.formIndex(before: &index._index) } + /// Returns the position immediately before the given index. + /// + /// - Parameter index: A valid index of the collection. `index` must be greater + /// than `startIndex`. + /// - Returns: The index value immediately before `index`. + /// - Complexity: O(log(`self.count`)) in the worst-case. @inlinable public func index(before index: Index) -> Index { index._index.ensureValid(forTree: self._root) return Index(self._root.index(before: index._index)) } + /// 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(`self.count`)) in the worst-case. @inlinable public func formIndex(_ i: inout Index, offsetBy distance: Int) { i._index.ensureValid(forTree: self._root) self._root.formIndex(&i._index, offsetBy: distance) } + /// 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:)`. + /// - Complexity: O(log(`self.count`)) in the worst-case. @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index { i._index.ensureValid(forTree: self._root) return Index(self._root.index(i._index, offsetBy: distance)) } + + /// 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 than `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`. + /// - Complexity: O(log(`self.count`)) in the worst-case. + @inlinable + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + i._index.ensureValid(forTree: self._root) + limit._index.ensureValid(forTree: self._root) + if let i = self._root.index(i._index, offsetBy: distance, limitedBy: limit._index) { + return Index(i) + } else { + return nil + } + } + + /// 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(`self.count`)) in the worst-case. + @inlinable + internal func formIndex(_ i: inout Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool { + i._index.ensureValid(forTree: self._root) + limit._index.ensureValid(forTree: self._root) + return self._root.formIndex(&i._index, offsetBy: distance, limitedBy: limit._index) + } } diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+ExpressibleByDictionaryLiteral.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+ExpressibleByDictionaryLiteral.swift index 730a3ceb..289b1761 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+ExpressibleByDictionaryLiteral.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+ExpressibleByDictionaryLiteral.swift @@ -28,6 +28,6 @@ extension SortedDictionary: ExpressibleByDictionaryLiteral { /// - Complexity: O(`n log n`) @inlinable public init(dictionaryLiteral elements: (Key, Value)...) { - self.init(uniqueKeysWithValues: elements) + self.init(keysWithValues: elements) } } diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift index 8c5eb280..8f33681a 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift @@ -12,11 +12,11 @@ extension SortedDictionary { /// Creates a dictionary from a sequence of key-value pairs which must /// be unique. - /// - Complexity: O(`n log n`) + /// - Complexity: O(`self.count` * log(`self.count`)) @inlinable @inline(__always) public init( - uniqueKeysWithValues keysAndValues: S + keysWithValues keysAndValues: S ) where S: Sequence, S.Element == Element { self.init() @@ -31,17 +31,21 @@ extension SortedDictionary { @inlinable @inline(__always) public init( - uniqueSortedKeysWithValues keysAndValues: S + sortedKeysWithValues keysAndValues: S ) where S: Sequence, S.Element == Element { self.init() - // TODO: implement O(n) version using BTree - // TODO: should this validate the sorted invariant - // in debug v production v unchecked builds? + var builder = _Tree.Builder() + var previousKey: Key? = nil for (key, value) in keysAndValues { - self._root.updateAnyValue(value, forKey: key) + assert(previousKey != nil && previousKey.unsafelyUnwrapped < key, + "Sequence out of order.") + builder.append((key, value)) + previousKey = key } + + self.init(_rootedAt: builder.finish()) } /// Creates a new sorted dictionary whose keys are the groupings returned diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Keys.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Keys.swift index 2fdc78d2..4c1d955a 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Keys.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Keys.swift @@ -28,7 +28,28 @@ extension SortedDictionary.Keys: Sequence { public typealias Element = Key /// The type that allows iteration over the collection's elements. - public typealias Iterator = IndexingIterator + public struct Iterator: IteratorProtocol { + @usableFromInline + internal var _iterator: SortedDictionary.Iterator + + @inlinable + @inline(__always) + internal init(_ _iterator: SortedDictionary.Iterator) { + self._iterator = _iterator + } + + @inlinable + @inline(__always) + public mutating func next() -> Element? { + _iterator.next()?.key + } + } + + @inlinable + @inline(__always) + public __consuming func makeIterator() -> Iterator { + Iterator(_base.makeIterator()) + } } extension SortedDictionary.Keys: BidirectionalCollection { @@ -51,8 +72,7 @@ extension SortedDictionary.Keys: BidirectionalCollection { /// /// If the collection is empty, `startIndex` is equal to `endIndex`. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public var startIndex: Index { self._base.startIndex } @@ -90,8 +110,7 @@ extension SortedDictionary.Keys: BidirectionalCollection { /// /// - Parameter i: A valid index of the collection. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public func formIndex(after index: inout Index) { @@ -107,8 +126,7 @@ extension SortedDictionary.Keys: BidirectionalCollection { /// /// - Returns: The index immediately after `i`. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public func index(after index: Index) -> Index { @@ -122,8 +140,7 @@ extension SortedDictionary.Keys: BidirectionalCollection { /// /// - Parameter i: A valid index of the collection. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public func formIndex(before index: inout Index) { @@ -139,8 +156,7 @@ extension SortedDictionary.Keys: BidirectionalCollection { /// /// - Returns: The index immediately before `i`. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public func index(before index: Index) -> Index { @@ -156,8 +172,7 @@ extension SortedDictionary.Keys: BidirectionalCollection { /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public func formIndex(_ i: inout Index, offsetBy distance: Int) { @@ -178,8 +193,7 @@ extension SortedDictionary.Keys: BidirectionalCollection { /// `index(after:)`. If `distance` is negative, this is the same value as /// the result of `abs(distance)` calls to `index(before:)`. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public func index(_ i: Index, offsetBy distance: Int) -> Index { diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Sequence.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Sequence.swift index b464634d..dac9fd9f 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Sequence.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Sequence.swift @@ -9,21 +9,31 @@ // //===----------------------------------------------------------------------===// -// TODO: add custom forEach? -// TODO: benchmark - extension SortedDictionary: Sequence { + @inlinable + @inline(__always) + public func forEach(_ body: (Element) throws -> Void) rethrows { + try self._root.forEach(body) + } + /// An iterator over the elements of the sorted dictionary public struct Iterator: IteratorProtocol { @usableFromInline internal var _iterator: _Tree.Iterator @inlinable + @inline(__always) internal init(_base: SortedDictionary) { self._iterator = _base._root.makeIterator() } + /// Advances to the next element and returns it, or nil if no next element exists. + /// + /// - Returns: The next element in the underlying sequence, if a next element exists; + /// otherwise, `nil`. + /// - Complexity: O(1) amortized over the entire sequence. @inlinable + @inline(__always) public mutating func next() -> Element? { return self._iterator.next() } @@ -31,8 +41,9 @@ extension SortedDictionary: Sequence { /// Returns an iterator over the elements of the sorted dictionary. /// - /// - Complexity: O(1) + /// - Complexity: O(log(`self.count`)) @inlinable + @inline(__always) public __consuming func makeIterator() -> Iterator { return Iterator(_base: self) } diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+SubSequence.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+SubSequence.swift new file mode 100644 index 00000000..c8088e7d --- /dev/null +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+SubSequence.swift @@ -0,0 +1,268 @@ +//===----------------------------------------------------------------------===// +// +// 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 { + public struct SubSequence { + @usableFromInline + internal typealias _TreeSubSequence = _Tree.SubSequence + + @usableFromInline + internal let _subSequence: _TreeSubSequence + + @inlinable + @inline(__always) + internal init(_ _subSequence: _TreeSubSequence) { + self._subSequence = _subSequence + } + + /// The underlying collection of the subsequence. + @inlinable + @inline(__always) + internal var base: SortedDictionary { SortedDictionary(_rootedAt: _subSequence.base) } + } +} + +extension SortedDictionary.SubSequence: Sequence { + public typealias Element = SortedDictionary.Element + + + public struct Iterator: IteratorProtocol { + @usableFromInline + internal var _iterator: _TreeSubSequence.Iterator + + @inlinable + @inline(__always) + internal init(_ _iterator: _TreeSubSequence.Iterator) { + self._iterator = _iterator + } + + /// Advances to the next element and returns it, or nil if no next element exists. + /// + /// - Returns: The next element in the underlying sequence, if a next element exists; + /// otherwise, `nil`. + /// - Complexity: O(1) amortized over the entire sequence. + @inlinable + @inline(__always) + public mutating func next() -> Element? { + _iterator.next() + } + } + + /// Returns an iterator over the elements of the subsequence. + /// + /// - Complexity: O(log(`self.count`)) + @inlinable + @inline(__always) + public __consuming func makeIterator() -> Iterator { + Iterator(_subSequence.makeIterator()) + } +} + +extension SortedDictionary.SubSequence: BidirectionalCollection { + public typealias Index = SortedDictionary.Index + public typealias SubSequence = Self + + /// The position of the first element in a nonempty subsequence. + /// + /// If the collection is empty, `startIndex` is equal to `endIndex`. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var startIndex: Index { Index(_subSequence.startIndex) } + + /// The subsequence'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(_subSequence.endIndex) } + + /// The number of elements in the subsequence. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var count: Int { _subSequence.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. + /// - Complexity: O(1) + @inlinable + @inline(__always) + public func distance(from start: Index, to end: Index) -> Int { + start._index.ensureValid(forTree: _subSequence.base) + end._index.ensureValid(forTree: _subSequence.base) + return _subSequence.distance(from: start._index, to: end._index) + } + + + /// 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(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func index(after i: Index) -> Index { + i._index.ensureValid(forTree: _subSequence.base) + return Index(_subSequence.index(after: i._index)) + } + + /// Replaces the given index with its successor. + /// + /// - Parameter i: A valid index of the collection. `i` must be less than `endIndex`. + /// - Complexity: O(log(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func formIndex(after i: inout Index) { + i._index.ensureValid(forTree: _subSequence.base) + return _subSequence.formIndex(after: &i._index) + } + + + /// 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(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func index(before i: Index) -> Index { + i._index.ensureValid(forTree: _subSequence.base) + return Index(_subSequence.index(before: i._index)) + } + + /// Replaces the given index with its predecessor. + /// + /// - Parameter i: A valid index of the collection. `i` must be greater + /// than `startIndex`. + /// - Complexity: O(log(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func formIndex(before i: inout Index) { + i._index.ensureValid(forTree: _subSequence.base) + _subSequence.formIndex(before: &i._index) + } + + + /// 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:)`. + /// - Complexity: O(log(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func index(_ i: Index, offsetBy distance: Int) -> Index { + i._index.ensureValid(forTree: _subSequence.base) + return Index(_subSequence.index(i._index, offsetBy: distance)) + } + + /// 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(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + internal func formIndex(_ i: inout Index, offsetBy distance: Int) { + i._index.ensureValid(forTree: _subSequence.base) + _subSequence.formIndex(&i._index, offsetBy: distance) + } + + + /// 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 than `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`. + /// - Complexity: O(log(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + i._index.ensureValid(forTree: _subSequence.base) + limit._index.ensureValid(forTree: _subSequence.base) + + if let i = _subSequence.index(i._index, offsetBy: distance, limitedBy: limit._index) { + return Index(i) + } else { + return nil + } + } + + /// 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(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + internal func formIndex(_ i: inout Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool { + i._index.ensureValid(forTree: _subSequence.base) + limit._index.ensureValid(forTree: _subSequence.base) + return _subSequence.formIndex(&i._index, offsetBy: distance, limitedBy: limit._index) + } + + @inlinable + @inline(__always) + public subscript(position: Index) -> Element { + position._index.ensureValid(forTree: _subSequence.base) + return _subSequence[position._index] + } + + @inlinable + @inline(__always) + public func _failEarlyRangeCheck(_ index: Index, bounds: Range) { + _subSequence._failEarlyRangeCheck( + index._index, + bounds: bounds.lowerBound._index.., bounds: Range) { + _subSequence._failEarlyRangeCheck( + range.lowerBound._index.. + public struct Iterator: IteratorProtocol { + @usableFromInline + internal var _iterator: SortedDictionary.Iterator + + @inlinable + @inline(__always) + internal init(_ _iterator: SortedDictionary.Iterator) { + self._iterator = _iterator + } + + @inlinable + @inline(__always) + public mutating func next() -> Element? { + _iterator.next()?.value + } + } + + @inlinable + @inline(__always) + public __consuming func makeIterator() -> Iterator { + Iterator(_base.makeIterator()) + } } extension SortedDictionary.Values: BidirectionalCollection { @@ -51,8 +72,7 @@ extension SortedDictionary.Values: BidirectionalCollection { /// /// If the collection is empty, `startIndex` is equal to `endIndex`. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public var startIndex: Index { self._base.startIndex } @@ -90,8 +110,7 @@ extension SortedDictionary.Values: BidirectionalCollection { /// /// - Parameter i: A valid index of the collection. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public func formIndex(after index: inout Index) { @@ -107,8 +126,7 @@ extension SortedDictionary.Values: BidirectionalCollection { /// /// - Returns: The index immediately after `i`. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public func index(after index: Index) -> Index { @@ -122,8 +140,7 @@ extension SortedDictionary.Values: BidirectionalCollection { /// /// - Parameter i: A valid index of the collection. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public func formIndex(before index: inout Index) { @@ -156,8 +173,7 @@ extension SortedDictionary.Values: BidirectionalCollection { /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public func formIndex(_ i: inout Index, offsetBy distance: Int) { @@ -178,8 +194,7 @@ extension SortedDictionary.Values: BidirectionalCollection { /// `index(after:)`. If `distance` is negative, this is the same value as /// the result of `abs(distance)` calls to `index(before:)`. /// - /// - Complexity: O(`log n`) where `n` is the number of key-value pairs in the - /// sorted dictionary. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public func index(_ i: Index, offsetBy distance: Int) -> Index { diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift index 7070077b..f16d0155 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift @@ -73,6 +73,60 @@ extension SortedDictionary { // MARK: Mutations extension SortedDictionary { + /// Ensures that the specified key exists in the dictionary (by appending one + /// with the supplied default value if necessary), then calls `body` to update + /// it in place. + /// + /// You can use this method to perform in-place operations on values in the + /// dictionary, whether or not `Value` has value semantics. The following + /// example uses this method while counting the occurrences of each letter + /// in a string: + /// + /// let message = "Hello, Elle!" + /// var letterCounts: SortedDictionary = [:] + /// for letter in message { + /// letterCounts.modifyValue(forKey: letter, default: 0) { count in + /// count += 1 + /// } + /// } + /// // letterCounts == ["H": 1, "e": 2, "l": 4, "o": 1, ...] + /// + /// - Parameters: + /// - key: The key to look up. If `key` does not already exist + /// in the dictionary, it is inserted with the supplied default value. + /// - defaultValue: The default value to append if `key` doesn't exist in + /// the dictionary. + /// - body: A function that performs an in-place mutation on the dictionary + /// value. + /// + /// - Returns: The return value of `body`. + /// + /// - Complexity: O(log(`self.count`)) + @inlinable + public mutating func modifyValue( + forKey key: Key, + default defaultValue: @autoclosure () -> Value, + _ body: (inout Value) throws -> R + ) rethrows -> R { + var (cursor, found) = self._root.findAnyCursor(forKey: key) + let r: R + + if found { + r = try cursor.updateCurrentNode { handle, slot in + try body(&handle[valueAt: slot]) + } + } else { + var value = defaultValue() + r = try body(&value) + cursor.insertElement((key, value), capacity: self._root.internalCapacity) + } + + cursor.apply(to: &self._root) + + return r + } + + /// Updates the value stored in the dictionary for the given key, or /// adds a new key-value pair if the key does not exist. /// @@ -132,16 +186,8 @@ extension SortedDictionary { public func mapValues( _ transform: (Value) throws -> T ) rethrows -> SortedDictionary { - // TODO: Optimize to reuse dictionary structure. - // TODO: optimize to use identify fastest iteration method - // TODO: optimize CoW checks - var newDictionary = SortedDictionary() - - for (key, value) in self { - newDictionary.updateValue(try transform(value), forKey: key) - } - - return newDictionary + let tree = try self._root.mapValues(transform) + return SortedDictionary(_rootedAt: tree) } /// Returns a new dictionary containing only the key-value pairs that have non-nil values @@ -162,14 +208,14 @@ extension SortedDictionary { // TODO: Optimize to reuse dictionary structure. // TODO: optimize to use identify fastest iteration method // TODO: optimize CoW checks - var newDictionary = SortedDictionary() + var builder = _BTree.Builder() for (key, value) in self { - if let value = try transform(value) { - newDictionary.updateValue(value, forKey: key) + if let newValue = try transform(value) { + builder.append((key, newValue)) } } - return newDictionary + return SortedDictionary(_rootedAt: builder.finish()) } } diff --git a/Sources/SortedCollections/SortedSet/SortedSet+BidirectionalCollection.swift b/Sources/SortedCollections/SortedSet/SortedSet+BidirectionalCollection.swift index 8da5d9c4..a108ff24 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet+BidirectionalCollection.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet+BidirectionalCollection.swift @@ -11,12 +11,15 @@ extension SortedSet: BidirectionalCollection { /// The number of elements in the sorted set. + /// /// - Complexity: O(1) @inlinable @inline(__always) public var count: Int { self._root.count } /// A Boolean value that indicates whether the set is empty. + /// + /// - Complexity: O(1) @inlinable @inline(__always) public var isEmpty: Bool { self._root.isEmpty } @@ -25,12 +28,12 @@ extension SortedSet: BidirectionalCollection { /// /// If the collection is empty, `startIndex` is equal to `endIndex`. /// - /// - Complexity: O(`log n`) + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) public var startIndex: Index { Index(self._root.startIndex) } - /// The dictionary's "past the end" position---that is, the position one + /// The set'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`. @@ -40,44 +43,133 @@ extension SortedSet: BidirectionalCollection { @inline(__always) public var endIndex: Index { Index(self._root.endIndex) } + /// 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. + /// - Complexity: O(1) @inlinable public func distance(from start: Index, to end: Index) -> Int { + start._index.ensureValid(forTree: self._root) + end._index.ensureValid(forTree: self._root) return self._root.distance(from: start._index, to: end._index) } + /// Replaces the given index with its successor. + /// + /// - Parameter index: A valid index of the collection. `index` must be less than `endIndex`. + /// - Complexity: O(log(`self.count`)) in the worst-case. @inlinable public func formIndex(after index: inout Index) { index._index.ensureValid(forTree: self._root) self._root.formIndex(after: &index._index) } + /// Returns the position immediately after the given index. + /// + /// - Parameter index: A valid index of the collection. `index` must be less than `endIndex`. + /// - Returns: The index value immediately after `index`. + /// - Complexity: O(log(`self.count`)) in the worst-case. @inlinable public func index(after index: Index) -> Index { index._index.ensureValid(forTree: self._root) return Index(self._root.index(after: index._index)) } + /// Replaces the given index with its predecessor. + /// + /// - Parameter index: A valid index of the collection. `index` must be greater + /// than `startIndex`. + /// - Complexity: O(log(`self.count`)) in the worst-case. @inlinable public func formIndex(before index: inout Index) { index._index.ensureValid(forTree: self._root) self._root.formIndex(before: &index._index) } + /// Returns the position immediately before the given index. + /// + /// - Parameter index: A valid index of the collection. `index` must be greater + /// than `startIndex`. + /// - Returns: The index value immediately before `index`. + /// - Complexity: O(log(`self.count`)) in the worst-case. @inlinable public func index(before index: Index) -> Index { index._index.ensureValid(forTree: self._root) return Index(self._root.index(before: index._index)) } + /// 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(`self.count`)) in the worst-case. @inlinable public func formIndex(_ i: inout Index, offsetBy distance: Int) { i._index.ensureValid(forTree: self._root) self._root.formIndex(&i._index, offsetBy: distance) } + /// 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:)`. + /// - Complexity: O(log(`self.count`)) in the worst-case. @inlinable public func index(_ i: Index, offsetBy distance: Int) -> Index { i._index.ensureValid(forTree: self._root) return Index(self._root.index(i._index, offsetBy: distance)) } + + /// 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 than `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`. + /// - Complexity: O(log(`self.count`)) in the worst-case. + @inlinable + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + i._index.ensureValid(forTree: self._root) + limit._index.ensureValid(forTree: self._root) + if let i = self._root.index(i._index, offsetBy: distance, limitedBy: limit._index) { + return Index(i) + } else { + return nil + } + } + + /// 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(`self.count`)) in the worst-case. + @inlinable + internal func formIndex(_ i: inout Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool { + i._index.ensureValid(forTree: self._root) + limit._index.ensureValid(forTree: self._root) + return self._root.formIndex(&i._index, offsetBy: distance, limitedBy: limit._index) + } } diff --git a/Sources/SortedCollections/SortedSet/SortedSet+Sequence.swift b/Sources/SortedCollections/SortedSet/SortedSet+Sequence.swift index 9cf86071..e9f3bac9 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet+Sequence.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet+Sequence.swift @@ -9,30 +9,42 @@ // //===----------------------------------------------------------------------===// -// TODO: add custom forEach? -// TODO: benchmark - extension SortedSet: Sequence { + @inlinable + @inline(__always) + public func forEach(_ body: (Element) throws -> Void) rethrows { + try self._root.forEach({ try body($0.key) }) + } + /// An iterator over the elements of the sorted set + @frozen public struct Iterator: IteratorProtocol { @usableFromInline internal var _iterator: _Tree.Iterator @inlinable + @inline(__always) internal init(_base: SortedSet) { self._iterator = _base._root.makeIterator() } + /// Advances to the next element and returns it, or nil if no next element exists. + /// + /// - Returns: The next element in the underlying sequence, if a next element exists; + /// otherwise, `nil`. + /// - Complexity: O(1) amortized over the entire sequence. @inlinable + @inline(__always) public mutating func next() -> Element? { return self._iterator.next()?.key } } - /// Returns an iterator over the elements of the sorted dictionary. + /// Returns an iterator over the elements of the sorted set. /// - /// - Complexity: O(1) + /// - Complexity: O(log(`self.count`)) @inlinable + @inline(__always) public __consuming func makeIterator() -> Iterator { return Iterator(_base: self) } diff --git a/Sources/SortedCollections/SortedSet/SortedSet+SetAlgebra.swift b/Sources/SortedCollections/SortedSet/SortedSet+SetAlgebra.swift index 19ae0b2d..1a17b321 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet+SetAlgebra.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet+SetAlgebra.swift @@ -33,8 +33,7 @@ extension SortedSet: SetAlgebra { /// method returns `(false, oldMember)`, where `oldMember` is the element /// that was equal to `newMember`. In some cases, `oldMember` may be /// distinguishable from `newMember` by identity comparison or some other means. - /// - Complexity: O(`log n`) where `n` is the number of members in the - /// sorted set. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) @discardableResult @@ -54,6 +53,7 @@ extension SortedSet: SetAlgebra { /// - Returns: An element equal to `newMember` if the set already contained such a /// member; otherwise, `nil`. In some cases, the returned element may be distinguishable /// from `newMember` by identity comparison or some other means. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) @discardableResult @@ -70,8 +70,7 @@ extension SortedSet: SetAlgebra { /// distinguishable from `newMember` by identity comparison or some other /// means. /// - /// - Complexity: O(`log n`) where `n` is the number of members in the - /// sorted set. + /// - Complexity: O(log(`self.count`)) @inlinable @inline(__always) @discardableResult @@ -80,12 +79,30 @@ extension SortedSet: SetAlgebra { } // MARK: Combining Sets - // TODO: add optimized implementations + /// Returns a new set with the elements of both this and the given set. + /// + /// - Parameter other: A sorted set of the same type as the current set. + /// - 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`)) @inlinable public func union(_ other: __owned Self) -> Self { - var newSet = self - newSet.formUnion(other) - return newSet + var builder = _Tree.Builder() + + var it1 = self.makeIterator() + var it2 = other.makeIterator() + + while let e1 = it1.next(), let e2 = it2.next() { + if e1 <= e2 { + builder.append((e1, ())) +// while + } else { + builder.append((e2, ())) + } + } + + return SortedSet(_rootedAt: builder.finish()) } @inlinable @@ -135,8 +152,10 @@ extension SortedSet: SetAlgebra { /// /// - Parameter other: A set of the same type as the current set. /// - Returns: `true` if the set is a subset of other; otherwise, `false`. + /// - Complexity: O(max(`self.count`, `other.count`)) @inlinable public func isSubset(of other: SortedSet) -> Bool { + // TODO: could be worthwhile to evaluate recursive approach if self.count > other.count { return false } var superIterator = other.makeIterator() diff --git a/Sources/SortedCollections/SortedSet/SortedSet+SubSequence.swift b/Sources/SortedCollections/SortedSet/SortedSet+SubSequence.swift new file mode 100644 index 00000000..74d57918 --- /dev/null +++ b/Sources/SortedCollections/SortedSet/SortedSet+SubSequence.swift @@ -0,0 +1,268 @@ +//===----------------------------------------------------------------------===// +// +// 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 SortedSet { + public struct SubSequence { + @usableFromInline + internal typealias _TreeSubSequence = _Tree.SubSequence + + @usableFromInline + internal let _subSequence: _TreeSubSequence + + @inlinable + @inline(__always) + internal init(_ _subSequence: _TreeSubSequence) { + self._subSequence = _subSequence + } + + /// The underlying collection of the subsequence. + @inlinable + @inline(__always) + internal var base: SortedSet { SortedSet(_rootedAt: _subSequence.base) } + } +} + +extension SortedSet.SubSequence: Sequence { + public typealias Element = SortedSet.Element + + + public struct Iterator: IteratorProtocol { + @usableFromInline + internal var _iterator: _TreeSubSequence.Iterator + + @inlinable + @inline(__always) + internal init(_ _iterator: _TreeSubSequence.Iterator) { + self._iterator = _iterator + } + + /// Advances to the next element and returns it, or nil if no next element exists. + /// + /// - Returns: The next element in the underlying sequence, if a next element exists; + /// otherwise, `nil`. + /// - Complexity: O(1) amortized over the entire sequence. + @inlinable + @inline(__always) + public mutating func next() -> Element? { + _iterator.next()?.key + } + } + + /// Returns an iterator over the elements of the subsequence. + /// + /// - Complexity: O(log(`self.count`)) + @inlinable + @inline(__always) + public __consuming func makeIterator() -> Iterator { + Iterator(_subSequence.makeIterator()) + } +} + +extension SortedSet.SubSequence: BidirectionalCollection { + public typealias Index = SortedSet.Index + public typealias SubSequence = Self + + /// The position of the first element in a nonempty subsequence. + /// + /// If the collection is empty, `startIndex` is equal to `endIndex`. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var startIndex: Index { Index(_subSequence.startIndex) } + + /// The subsequence'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(_subSequence.endIndex) } + + /// The number of elements in the subsequence. + /// + /// - Complexity: O(1) + @inlinable + @inline(__always) + public var count: Int { _subSequence.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. + /// - Complexity: O(1) + @inlinable + @inline(__always) + public func distance(from start: Index, to end: Index) -> Int { + start._index.ensureValid(forTree: _subSequence.base) + end._index.ensureValid(forTree: _subSequence.base) + return _subSequence.distance(from: start._index, to: end._index) + } + + + /// 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(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func index(after i: Index) -> Index { + i._index.ensureValid(forTree: _subSequence.base) + return Index(_subSequence.index(after: i._index)) + } + + /// Replaces the given index with its successor. + /// + /// - Parameter i: A valid index of the collection. `i` must be less than `endIndex`. + /// - Complexity: O(log(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func formIndex(after i: inout Index) { + i._index.ensureValid(forTree: _subSequence.base) + return _subSequence.formIndex(after: &i._index) + } + + + /// 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(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func index(before i: Index) -> Index { + i._index.ensureValid(forTree: _subSequence.base) + return Index(_subSequence.index(before: i._index)) + } + + /// Replaces the given index with its predecessor. + /// + /// - Parameter i: A valid index of the collection. `i` must be greater + /// than `startIndex`. + /// - Complexity: O(log(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func formIndex(before i: inout Index) { + i._index.ensureValid(forTree: _subSequence.base) + _subSequence.formIndex(before: &i._index) + } + + + /// 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:)`. + /// - Complexity: O(log(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func index(_ i: Index, offsetBy distance: Int) -> Index { + i._index.ensureValid(forTree: _subSequence.base) + return Index(_subSequence.index(i._index, offsetBy: distance)) + } + + /// 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(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + internal func formIndex(_ i: inout Index, offsetBy distance: Int) { + i._index.ensureValid(forTree: _subSequence.base) + _subSequence.formIndex(&i._index, offsetBy: distance) + } + + + /// 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 than `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`. + /// - Complexity: O(log(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + public func index(_ i: Index, offsetBy distance: Int, limitedBy limit: Index) -> Index? { + i._index.ensureValid(forTree: _subSequence.base) + limit._index.ensureValid(forTree: _subSequence.base) + + if let i = _subSequence.index(i._index, offsetBy: distance, limitedBy: limit._index) { + return Index(i) + } else { + return nil + } + } + + /// 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(`self.count`)) in the worst-case. + @inlinable + @inline(__always) + internal func formIndex(_ i: inout Index, offsetBy distance: Int, limitedBy limit: Self.Index) -> Bool { + i._index.ensureValid(forTree: _subSequence.base) + limit._index.ensureValid(forTree: _subSequence.base) + return _subSequence.formIndex(&i._index, offsetBy: distance, limitedBy: limit._index) + } + + @inlinable + @inline(__always) + public subscript(position: Index) -> Element { + position._index.ensureValid(forTree: _subSequence.base) + return _subSequence[position._index].key + } + + @inlinable + @inline(__always) + public func _failEarlyRangeCheck(_ index: Index, bounds: Range) { + _subSequence._failEarlyRangeCheck( + index._index, + bounds: bounds.lowerBound._index.., bounds: Range) { + _subSequence._failEarlyRangeCheck( + range.lowerBound._index.. Element { position._index.ensureValid(forTree: self._root) return self._root[position._index].key } + /// Returns a sequence of elements in the collection bounded by the provided + /// range. + /// + /// This is particularly useful when applied with a bound corresponding to some + /// group of elements. + /// + /// let students: SortedSet = ... + /// students["A"..<"B"] // Sequence of students with names beginning with "A" + /// + /// - Complexity: O(log(`self.count`)) @inlinable - public subscript(range: Range) -> Slice { - let start = self._root.startIndex(forKey: range.lowerBound) - let end = self._root.startIndex(forKey: range.upperBound) - return Slice(base: self, bounds: Index(start)..) -> SubSequence { + let start = _root.startIndex(forKey: range.lowerBound) + let end = _root.startIndex(forKey: range.upperBound) + let range = _Tree.SubSequence(base: _root, bounds: start..(uniqueKeysWithValues: kvs) + let sortedDictionary = SortedDictionary(keysWithValues: kvs) expectEqual(sortedDictionary.count, count) } } @@ -61,7 +61,7 @@ final class SortedDictionaryTests: CollectionTestCase { withEvery("count", in: [0, 1, 2, 3, 4, 8, 16, 64]) { count in for i in 0...count { let kvs = (0..(uniqueKeysWithValues: kvs) + var sortedDictionary = SortedDictionary(keysWithValues: kvs) sortedDictionary[i * 2] = -i var comparison = Array(kvs) @@ -96,7 +96,7 @@ final class SortedDictionaryTests: CollectionTestCase { let kvs = (0..(uniqueKeysWithValues: kvs) + var d = SortedDictionary(keysWithValues: kvs) withEvery("isShared", in: [false, true]) { isShared in withHiddenCopies(if: isShared, of: &d) { d in