From 9150bbf06e4ca6873ed0bb15162fa14db05b3798 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 23 Sep 2022 10:57:15 -0700 Subject: [PATCH] [PersistentCollections] Cache the item hash within collision nodes This will simplify merge operations as we no longer have to spend effort on preventing repeated rehashings of items within collision nodes. Also, review and simplify node allocation and lookup code. --- .../Node/_Node+Debugging.swift | 1 + .../Node/_Node+Initializers.swift | 68 +++--- .../Node/_Node+Invariants.swift | 22 +- .../Node/_Node+Lookups.swift | 103 ++++----- .../Node/_Node+Primitive Removals.swift | 3 +- .../Node/_Node+Storage.swift | 214 ++++++++---------- .../Node/_Node+Subtree Insertions.swift | 109 +++++++-- .../Node/_Node+Subtree Modify.swift | 32 ++- .../Node/_Node+Subtree Removals.swift | 69 +++--- .../Node/_Node+Transform.swift | 21 +- .../Node/_Node+UnsafeHandle.swift | 18 +- .../Node/_Node+isDisjoint.swift | 4 +- .../Node/_Node+isSubset.swift | 1 - .../PersistentCollections/Node/_Node.swift | 5 + .../Node/_RawNode+UnsafeHandle.swift | 6 + .../Node/_StorageHeader.swift | 28 +-- .../PersistentDictionary.swift | 2 +- .../PersistentSet+SetAlgebra basics.swift | 2 +- 18 files changed, 383 insertions(+), 325 deletions(-) diff --git a/Sources/PersistentCollections/Node/_Node+Debugging.swift b/Sources/PersistentCollections/Node/_Node+Debugging.swift index e7821dba..3b0dd1c7 100644 --- a/Sources/PersistentCollections/Node/_Node+Debugging.swift +++ b/Sources/PersistentCollections/Node/_Node+Debugging.swift @@ -67,6 +67,7 @@ extension _Node.UnsafeHandle { print(""" \(firstPrefix)\(isCollisionNode ? "CollisionNode" : "Node")(\ at: \(_addressString(for: _header)), \ + \(isCollisionNode ? "hash: \(collisionHash), " : "")\ \(extra)\ byteCapacity: \(byteCapacity), \ freeBytes: \(bytesFree)) diff --git a/Sources/PersistentCollections/Node/_Node+Initializers.swift b/Sources/PersistentCollections/Node/_Node+Initializers.swift index 0d8d99ea..220d80af 100644 --- a/Sources/PersistentCollections/Node/_Node+Initializers.swift +++ b/Sources/PersistentCollections/Node/_Node+Initializers.swift @@ -12,19 +12,14 @@ extension _Node { @inlinable internal static func _collisionNode( + _ hash: _Hash, _ item1: Element, _ inserter2: (UnsafeMutablePointer) -> Void ) -> _Node { - var node = _Node(storage: Storage.allocate(itemCapacity: 2), count: 2) - node.update { - $0.collisionCount = 2 - let byteCount = 2 * MemoryLayout.stride - assert($0.bytesFree >= byteCount) - $0.bytesFree &-= byteCount - let items = $0.reverseItems + let node = _Node.allocateCollision(count: 2, hash) { items in items.initializeElement(at: 1, to: item1) inserter2(items.baseAddress.unsafelyUnwrapped) - } + }.node node._invariantCheck() return node } @@ -37,36 +32,36 @@ extension _Node { _ bucket2: _Bucket ) -> (node: _Node, slot1: _Slot, slot2: _Slot) { assert(bucket1 != bucket2) - var node = _Node(storage: Storage.allocate(itemCapacity: 2), count: 2) - let (slot1, slot2) = node.update { - $0.itemMap.insert(bucket1) - $0.itemMap.insert(bucket2) - $0.bytesFree &-= 2 * MemoryLayout.stride + let r = _Node.allocate( + itemMap: _Bitmap(bucket1, bucket2), + childMap: .empty, + count: 2 + ) { children, items in + assert(items.count == 2 && children.count == 0) let i1 = bucket1 < bucket2 ? 1 : 0 let i2 = 1 &- i1 - let items = $0.reverseItems items.initializeElement(at: i1, to: item1) inserter2(items.baseAddress.unsafelyUnwrapped + i2) return (_Slot(i2), _Slot(i1)) // Note: swapped } - node._invariantCheck() - return (node, slot1, slot2) + r.node._invariantCheck() + return (r.node, r.result.0, r.result.1) } @inlinable internal static func _regularNode( _ child: _Node, _ bucket: _Bucket ) -> _Node { - var node = _Node( - storage: Storage.allocate(childCapacity: 1), - count: child.count) - node.update { - $0.childMap.insert(bucket) - $0.bytesFree &-= MemoryLayout<_Node>.stride - $0.childPtr(at: .zero).initialize(to: child) + let r = _Node.allocate( + itemMap: .empty, + childMap: _Bitmap(bucket), + count: child.count + ) { children, items in + assert(items.count == 0 && children.count == 1) + children.initializeElement(at: 0, to: child) } - node._invariantCheck() - return node + r.node._invariantCheck() + return r.node } @inlinable @@ -77,18 +72,17 @@ extension _Node { _ childBucket: _Bucket ) -> _Node { assert(itemBucket != childBucket) - var node = _Node( - storage: Storage.allocate(itemCapacity: 1, childCapacity: 1), - count: child.count &+ 1) - node.update { - $0.itemMap.insert(itemBucket) - $0.childMap.insert(childBucket) - $0.bytesFree &-= MemoryLayout.stride + MemoryLayout<_Node>.stride - inserter($0.itemPtr(at: .zero)) - $0.childPtr(at: .zero).initialize(to: child) + let r = _Node.allocate( + itemMap: _Bitmap(itemBucket), + childMap: _Bitmap(childBucket), + count: child.count &+ 1 + ) { children, items in + assert(items.count == 1 && children.count == 1) + inserter(items.baseAddress.unsafelyUnwrapped) + children.initializeElement(at: 0, to: child) } - node._invariantCheck() - return node + r.node._invariantCheck() + return r.node } } @@ -102,7 +96,7 @@ extension _Node { _ hash2: _Hash ) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) { if hash1 == hash2 { - let top = _collisionNode(item1, inserter2) + let top = _collisionNode(hash1, item1, inserter2) return (top, top.unmanaged, _Slot(0), _Slot(1)) } let r = _build( diff --git a/Sources/PersistentCollections/Node/_Node+Invariants.swift b/Sources/PersistentCollections/Node/_Node+Invariants.swift index c9b18e5d..af02f666 100644 --- a/Sources/PersistentCollections/Node/_Node+Invariants.swift +++ b/Sources/PersistentCollections/Node/_Node+Invariants.swift @@ -34,8 +34,19 @@ extension _Node { raw.storage.header._invariantCheck() read { let itemBytes = $0.itemCount * MemoryLayout.stride - let childBytes = $0.childCount * MemoryLayout<_Node>.stride - assert(itemBytes + $0.bytesFree + childBytes == $0.byteCapacity) + + if $0.isCollisionNode { + let hashBytes = MemoryLayout<_Hash>.stride + assert($0.itemCount >= 1) + assert($0.childCount == 0) + assert(itemBytes + $0.bytesFree + hashBytes == $0.byteCapacity) + + assert($0.collisionHash == _Hash($0[item: .zero].key)) + } else { + let childBytes = $0.childCount * MemoryLayout<_Node>.stride + assert(itemBytes + $0.bytesFree + childBytes == $0.byteCapacity) + } + let actualCount = $0.children.reduce($0.itemCount, { $0 + $1.count }) assert(actualCount == self.count) } @@ -55,12 +66,11 @@ extension _Node { if $0.isCollisionNode { precondition(count == $0.itemCount) precondition(count > 0) - let key = $0.collisionHash - let hash = _Hash(key) + let hash = $0.collisionHash precondition( hash.isEqual(to: path, upTo: level), - "Misplaced colliding key '\(key)': \(path) isn't a prefix of \(hash)") - for item in $0.reverseItems.dropFirst() { + "Misplaced collision node: \(path) isn't a prefix of \(hash)") + for item in $0.reverseItems { precondition(_Hash(item.key) == hash) } } diff --git a/Sources/PersistentCollections/Node/_Node+Lookups.swift b/Sources/PersistentCollections/Node/_Node+Lookups.swift index c3c42445..6c626cad 100644 --- a/Sources/PersistentCollections/Node/_Node+Lookups.swift +++ b/Sources/PersistentCollections/Node/_Node+Lookups.swift @@ -46,16 +46,15 @@ extension _Node.UnsafeHandle { @inlinable @inline(never) internal func _findInCollision( _ level: _Level, _ key: Key, _ hash: _Hash - ) -> (code: Int, slot: _Slot, expansionHash: _Hash) { + ) -> (code: Int, slot: _Slot) { assert(isCollisionNode) if !level.isAtBottom { - let h = self.collisionHash - if h != hash { return (2, .zero, h) } + if hash != self.collisionHash { return (2, .zero) } } // Note: this searches the items in reverse insertion order. guard let slot = reverseItems.firstIndex(where: { $0.key == key }) - else { return (1, self.itemsEndSlot, _Hash(_value: 0)) } - return (0, _Slot(itemCount &- 1 &- slot), _Hash(_value: 0)) + else { return (1, self.itemsEndSlot) } + return (0, _Slot(itemCount &- 1 &- slot)) } } @@ -77,15 +76,24 @@ internal enum _FindResult { /// If the current node is a collision node, then the bucket value is /// set to `_Bucket.invalid`. case found(_Bucket, _Slot) + /// The item we're looking for is not currently inside the subtree rooted at /// this node. /// /// If we wanted to insert it, then its correct slot is within this node /// at the specified bucket / item slot. (Which is currently empty.) /// - /// If the current node is a collision node, then the bucket value is - /// set to `_Bucket.invalid`. - case notFound(_Bucket, _Slot) + /// When the node is a collision node, the `insertCollision` case is returned + /// instead of this one. + case insert(_Bucket, _Slot) + + /// The item we're looking for is not currently inside the subtree rooted at + /// this collision node. + /// + /// If we wanted to insert it, then it needs to be appended to the items + /// buffer. + case appendCollision + /// The item we're looking for is not currently inside the subtree rooted at /// this node. /// @@ -95,7 +103,8 @@ internal enum _FindResult { /// it with a new child node. /// /// (This case is never returned if the current node is a collision node.) - case newCollision(_Bucket, _Slot) + case spawnChild(_Bucket, _Slot) + /// The item we're looking for is not in this subtree. /// /// However, the item doesn't belong in this subtree at all. This is an @@ -108,12 +117,9 @@ internal enum _FindResult { /// node further down the tree. (This undoes the compression by expanding /// the collision node's path, hence the name of the enum case.) /// - /// The payload of the expansion case is the shared hash value of all items - /// inside the current (collision) node -- this is needed to sort this node - /// into the proper bucket in any newly created parents. - /// /// (This case is never returned if the current node is a regular node.) - case expansion(_Hash) + case expansion + /// The item we're looking for is not directly stored in this node, but it /// might be somewhere in the subtree rooted at the child at the given /// bucket & slot. @@ -124,17 +130,17 @@ internal enum _FindResult { extension _Node { @inlinable - internal func find( - _ level: _Level, _ key: Key, _ hash: _Hash, forInsert: Bool + internal func findForInsertion( + _ level: _Level, _ key: Key, _ hash: _Hash ) -> _FindResult { - read { $0.find(level, key, hash, forInsert: forInsert) } + read { $0.findForInsertion(level, key, hash) } } } extension _Node.UnsafeHandle { @inlinable - internal func find( - _ level: _Level, _ key: Key, _ hash: _Hash, forInsert: Bool + internal func findForInsertion( + _ level: _Level, _ key: Key, _ hash: _Hash ) -> _FindResult { guard !isCollisionNode else { let r = _findInCollision(level, key, hash) @@ -142,10 +148,10 @@ extension _Node.UnsafeHandle { return .found(.invalid, r.slot) } if r.code == 1 { - return .notFound(.invalid, self.itemsEndSlot) + return .appendCollision } assert(r.code == 2) - return .expansion(r.expansionHash) + return .expansion } let bucket = hash[level] if itemMap.contains(bucket) { @@ -153,15 +159,14 @@ extension _Node.UnsafeHandle { if self[item: slot].key == key { return .found(bucket, slot) } - return .newCollision(bucket, slot) + return .spawnChild(bucket, slot) } if childMap.contains(bucket) { let slot = childMap.slot(of: bucket) return .descend(bucket, slot) } - // Don't calculate the slot unless the caller will need it. - let slot = forInsert ? itemMap.slot(of: bucket) : .zero - return .notFound(bucket, slot) + let slot = itemMap.slot(of: bucket) + return .insert(bucket, slot) } } @@ -171,15 +176,11 @@ extension _Node { @inlinable internal func get(_ level: _Level, _ key: Key, _ hash: _Hash) -> Value? { read { - let r = $0.find(level, key, hash, forInsert: false) - switch r { - case .found(_, let slot): - return $0[item: slot].value - case .notFound, .newCollision, .expansion: - return nil - case .descend(_, let slot): - return $0[child: slot].get(level.descend(), key, hash) + guard let r = $0.find(level, key, hash) else { return nil } + if r.descend { + return $0[child: r.slot].get(level.descend(), key, hash) } + return $0[item: r.slot].value } } } @@ -198,15 +199,9 @@ extension _Node.UnsafeHandle { internal func containsKey( _ level: _Level, _ key: Key, _ hash: _Hash ) -> Bool { - let r = find(level, key, hash, forInsert: false) - switch r { - case .found: - return true - case .notFound, .newCollision, .expansion: - return false - case .descend(_, let slot): - return self[child: slot].containsKey(level.descend(), key, hash) - } + guard let r = find(level, key, hash) else { return false } + guard r.descend else { return true } + return self[child: r.slot].containsKey(level.descend(), key, hash) } } @@ -215,21 +210,15 @@ extension _Node { internal func position( forKey key: Key, _ level: _Level, _ hash: _Hash ) -> Int? { - let r = find(level, key, hash, forInsert: false) - switch r { - case .found(_, let slot): - return slot.value - case .notFound, .newCollision, .expansion: - return nil - case .descend(_, let slot): - return read { h in - let children = h.children - let p = children[slot.value] - .position(forKey: key, level.descend(), hash) - guard let p = p else { return nil } - let c = h.itemCount &+ p - return children[.. _Node.Storage { - assert(itemCapacity >= 0 && childCapacity >= 0) - let itemBytes = itemCapacity * MemoryLayout.stride - let childBytes = childCapacity * MemoryLayout<_Node>.stride - return allocate(byteCapacity: itemBytes &+ childBytes) - } } extension _Node { @@ -105,12 +95,7 @@ extension _Node { } @inlinable @inline(__always) - internal static var spaceForNewChild: Int { - MemoryLayout<_Node>.stride - } - - @inlinable @inline(__always) - internal static var spaceForNewCollision: Int { + internal static var spaceForSpawningChild: Int { Swift.max(0, MemoryLayout<_Node>.stride - MemoryLayout.stride) } @@ -153,130 +138,129 @@ extension _Node { internal static func allocate( itemMap: _Bitmap, childMap: _Bitmap, count: Int, + extraBytes: Int = 0, initializingWith initializer: ( UnsafeMutableBufferPointer<_Node>, UnsafeMutableBufferPointer ) -> R ) -> (node: _Node, result: R) { - let (itemCount, childCount) = _StorageHeader.counts( - itemMap: itemMap, childMap: childMap) + assert(extraBytes >= 0) + assert(itemMap.isDisjoint(with: childMap)) // No collisions + let itemCount = itemMap.count + let childCount = childMap.count + + let itemStride = MemoryLayout.stride + let childStride = MemoryLayout<_Node>.stride + + let itemBytes = itemCount * itemStride + let childBytes = childCount * childStride + let occupiedBytes = itemBytes &+ childBytes let storage = Storage.allocate( - itemCapacity: itemCount, childCapacity: childCount) + byteCapacity: occupiedBytes &+ extraBytes) var node = _Node(storage: storage, count: count) let result = node.update { - let (children, items) = $0._prepare( - itemMap: itemMap, - itemCount: itemCount, - childMap: childMap, - childCount: childCount - ) - return initializer(children, items) + $0.itemMap = itemMap + $0.childMap = childMap + + assert(occupiedBytes <= $0.bytesFree) + $0.bytesFree &-= occupiedBytes + + let childStart = $0._memory + .bindMemory(to: _Node.self, capacity: childCount) + let itemStart = ($0._memory + ($0.byteCapacity - itemBytes)) + .bindMemory(to: Element.self, capacity: itemCount) + + return initializer( + UnsafeMutableBufferPointer(start: childStart, count: childCount), + UnsafeMutableBufferPointer(start: itemStart, count: itemCount)) } return (node, result) } + @inlinable + internal static func allocateCollision( + count: Int, + _ hash: _Hash, + extraBytes: Int = 0, + initializingWith initializer: (UnsafeMutableBufferPointer) -> R + ) -> (node: _Node, result: R) { + assert(count >= 2) + assert(extraBytes >= 0) + let itemBytes = count * MemoryLayout.stride + let hashBytes = MemoryLayout<_Hash>.stride + let bytes = itemBytes &+ hashBytes + assert(MemoryLayout<_Hash>.alignment <= MemoryLayout<_RawNode>.alignment) + let storage = Storage.allocate(byteCapacity: bytes &+ extraBytes) + var node = _Node(storage: storage, count: count) + let result = node.update { + $0.itemMap = _Bitmap(bitPattern: count) + $0.childMap = $0.itemMap + assert(bytes <= $0.bytesFree) + $0.bytesFree &-= bytes + + $0._memory.storeBytes(of: hash, as: _Hash.self) + + let itemStart = ($0._memory + ($0.byteCapacity &- itemBytes)) + .bindMemory(to: Element.self, capacity: count) + + let items = UnsafeMutableBufferPointer(start: itemStart, count: count) + return initializer(items) + } + return (node, result) + } + + @inlinable @inline(never) internal func copy(withFreeSpace space: Int = 0) -> _Node { assert(space >= 0) - let capacity = read { $0.byteCapacity &- $0.bytesFree &+ space } - var new = Self( - storage: Storage.allocate(byteCapacity: capacity), - count: count) - read { src in - new.update { dst in - let (dstChildren, dstItems) = dst._prepare( - itemMap: src.itemMap, childMap: src.childMap) - dstChildren.initializeAll(fromContentsOf: src.children) - dstItems.initializeAll(fromContentsOf: src.reverseItems) + if isCollisionNode { + return read { src in + Self.allocateCollision( + count: self.count, self.collisionHash + ) { dstItems in + dstItems.initializeAll(fromContentsOf: src.reverseItems) + }.node } } - new._invariantCheck() - return new + return read { src in + Self.allocate( + itemMap: src.itemMap, + childMap: src.childMap, + count: self.count, + extraBytes: space + ) { dstChildren, dstItems in + dstChildren.initializeAll(fromContentsOf: src.children) + dstItems.initializeAll(fromContentsOf: src.reverseItems) + }.node + } } @inlinable @inline(never) internal mutating func move(withFreeSpace space: Int = 0) { assert(space >= 0) - let capacity = read { $0.byteCapacity &- $0.bytesFree &+ space } - var new = Self( - storage: Storage.allocate(byteCapacity: capacity), - count: self.count) - self.update { src in - new.update { dst in - let (dstChildren, dstItems) = dst._prepare( - itemMap: src.itemMap, childMap: src.childMap) - + let c = self.count + if isCollisionNode { + self = update { src in + Self.allocateCollision( + count: c, src.collisionHash + ) { dstItems in + dstItems.moveInitializeAll(fromContentsOf: src.reverseItems) + src.clear() + }.node + } + return + } + self = update { src in + Self.allocate( + itemMap: src.itemMap, + childMap: src.childMap, + count: c, + extraBytes: space + ) { dstChildren, dstItems in dstChildren.moveInitializeAll(fromContentsOf: src.children) dstItems.moveInitializeAll(fromContentsOf: src.reverseItems) - src.clear() - assert(dst.bytesFree >= space) - } + }.node } - self.count = 0 - self._invariantCheck() - new._invariantCheck() - self = new } } - -extension _Node.UnsafeHandle { - @inlinable - internal func _prepare( - itemMap: _Bitmap, childMap: _Bitmap - ) -> ( - children: UnsafeMutableBufferPointer<_Node>, - items: UnsafeMutableBufferPointer - ) { - let (itemCount, childCount) = _StorageHeader.counts( - itemMap: itemMap, childMap: childMap) - return self._prepare( - itemMap: itemMap, - itemCount: itemCount, - childMap: childMap, - childCount: childCount) - } - - @inlinable - internal func _prepare( - itemMap: _Bitmap, - itemCount: Int, - childMap: _Bitmap, - childCount: Int - ) -> ( - children: UnsafeMutableBufferPointer<_Node>, - items: UnsafeMutableBufferPointer - ) { - assert(self.itemMap.isEmpty && self.childMap.isEmpty) - assert(self.byteCapacity == self.bytesFree) - - assert( - itemMap == childMap - || (itemMap.count == itemCount && childMap.count == childCount)) - - assert( - itemMap != childMap - || (itemCount == itemMap._value && childCount == 0)) - - self.itemMap = itemMap - self.childMap = childMap - - let itemStride = MemoryLayout.stride - let childStride = MemoryLayout<_Node>.stride - - let itemBytes = itemCount &* itemStride - let childBytes = childCount &* childStride - let occupiedBytes = itemBytes &+ childBytes - assert(occupiedBytes <= byteCapacity) - bytesFree = byteCapacity &- occupiedBytes - - let childStart = self._memory - .bindMemory(to: _Node.self, capacity: childCount) - let itemStart = (self._memory + (byteCapacity - itemBytes)) - .bindMemory(to: Element.self, capacity: itemCount) - return ( - .init(start: childStart, count: childCount), - .init(start: itemStart, count: itemCount)) - } -} - diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift index 0d9b9c05..e590fb33 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift @@ -35,16 +35,19 @@ extension _Node { ) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) { defer { _invariantCheck() } let isUnique = self.isUnique() - let r = find(level, key, hash, forInsert: true) + let r = findForInsertion(level, key, hash) switch r { case .found(_, let slot): ensureUnique(isUnique: isUnique) return (false, unmanaged, slot) - case .notFound(let bucket, let slot): + case .insert(let bucket, let slot): ensureUniqueAndInsertItem(isUnique: isUnique, slot, bucket) { _ in } return (true, unmanaged, slot) - case .newCollision(let bucket, let slot): - let r = ensureUniqueAndMakeNewCollision( + case .appendCollision: + ensureUniqueAndAppendCollision(isUnique: isUnique, hash) { _ in } + return (true, unmanaged, _Slot(self.count &- 1)) + case .spawnChild(let bucket, let slot): + let r = ensureUniqueAndSpawnChild( isUnique: isUnique, level: level, replacing: slot, bucket, @@ -52,12 +55,11 @@ extension _Node { inserter: { _ in } ) return (true, r.leaf, r.slot) - case .expansion(let collisionHash): + case .expansion: let r = _Node.build( level: level, item1: { _ in }, hash, - child2: self, collisionHash - ) + child2: self, self.collisionHash) self = r.top return (true, r.leaf, r.slot1) case .descend(_, let slot): @@ -79,6 +81,8 @@ extension _Node { _ bucket: _Bucket, inserter: (UnsafeMutablePointer) -> Void ) { + assert(!isCollisionNode) + if !isUnique { self = copyNodeAndInsertItem(at: slot, bucket, inserter: inserter) return @@ -101,7 +105,7 @@ extension _Node { _ bucket: _Bucket, inserter: (UnsafeMutablePointer) -> Void ) -> _Node { - // Copy items into new storage. + assert(!isCollisionNode) let (itemMap, childMap) = ( self.raw.storage.header.bitmapsForInsertingItem(at: slot, bucket)) let c = self.count @@ -130,7 +134,7 @@ extension _Node { _ bucket: _Bucket, inserter: (UnsafeMutablePointer) -> Void ) { - // Copy items into new storage. + assert(!isCollisionNode) let (itemMap, childMap) = ( self.raw.storage.header.bitmapsForInsertingItem(at: slot, bucket)) let c = self.count @@ -158,7 +162,72 @@ extension _Node { extension _Node { @inlinable - internal mutating func ensureUniqueAndMakeNewCollision( + internal mutating func ensureUniqueAndAppendCollision( + isUnique: Bool, + _ hash: _Hash, + inserter: (UnsafeMutablePointer) -> Void + ) { + assert(isCollisionNode) + if !isUnique { + self = copyNodeAndAppendCollision(hash, inserter: inserter) + return + } + if !hasFreeSpace(Self.spaceForNewItem) { + moveNodeAndAppendCollision(hash, inserter: inserter) + return + } + // In-place insert. + update { + let p = $0._makeRoomForNewItem(at: $0.itemsEndSlot, .invalid) + inserter(p) + } + self.count &+= 1 + } + + @inlinable @inline(never) + internal func copyNodeAndAppendCollision( + _ hash: _Hash, + inserter: (UnsafeMutablePointer) -> Void + ) -> _Node { + assert(isCollisionNode) + assert(hash == collisionHash) + assert(self.count == read { $0.collisionCount }) + let c = self.count + return read { src in + Self.allocateCollision(count: c &+ 1, hash) { dstItems in + let srcItems = src.reverseItems + assert(dstItems.count == srcItems.count + 1) + dstItems.dropFirst().initializeAll(fromContentsOf: srcItems) + inserter(dstItems.baseAddress!) + }.node + } + } + + @inlinable @inline(never) + internal mutating func moveNodeAndAppendCollision( + _ hash: _Hash, + inserter: (UnsafeMutablePointer) -> Void + ) { + assert(isCollisionNode) + assert(hash == collisionHash) + assert(self.count == read { $0.collisionCount }) + let c = self.count + self = update { src in + Self.allocateCollision(count: c &+ 1, hash) { dstItems in + let srcItems = src.reverseItems + assert(dstItems.count == srcItems.count + 1) + dstItems.dropFirst().moveInitializeAll(fromContentsOf: srcItems) + inserter(dstItems.baseAddress!) + + src.clear() + }.node + } + } +} + +extension _Node { + @inlinable + internal mutating func ensureUniqueAndSpawnChild( isUnique: Bool, level: _Level, replacing slot: _Slot, @@ -169,18 +238,12 @@ extension _Node { let existingHash = read { _Hash($0[item: slot].key) } if newHash == existingHash, hasSingletonItem { // Convert current node to a collision node. - ensureUnique(isUnique: isUnique, withFreeSpace: Self.spaceForNewItem) - count &+= 1 - update { - $0.collisionCount = 1 - let p = $0._makeRoomForNewItem(at: _Slot(1), .invalid) - inserter(p) - } + self = _Node._collisionNode(newHash, read { $0[item: .zero] }, inserter) return (unmanaged, _Slot(1)) } if !isUnique { - let r = copyNodeAndMakeNewCollision( + let r = copyNodeAndSpawnChild( level: level, replacing: slot, bucket, existingHash: existingHash, @@ -189,8 +252,8 @@ extension _Node { self = r.node return (r.leaf, r.slot) } - if !hasFreeSpace(Self.spaceForNewCollision) { - return moveNodeAndMakeNewCollision( + if !hasFreeSpace(Self.spaceForSpawningChild) { + return moveNodeAndSpawnChild( level: level, replacing: slot, bucket, existingHash: existingHash, @@ -208,7 +271,7 @@ extension _Node { } @inlinable @inline(never) - internal func copyNodeAndMakeNewCollision( + internal func copyNodeAndSpawnChild( level: _Level, replacing slot: _Slot, _ bucket: _Bucket, @@ -217,7 +280,7 @@ extension _Node { inserter: (UnsafeMutablePointer) -> Void ) -> (node: _Node, leaf: _UnmanagedNode, slot: _Slot) { let (itemMap, childMap) = ( - self.raw.storage.header.bitmapsForNewCollision(at: slot, bucket)) + self.raw.storage.header.bitmapsForSpawningChild(at: slot, bucket)) let c = self.count let childSlot = childMap.slot(of: bucket) let r = read { src in @@ -263,7 +326,7 @@ extension _Node { inserter: (UnsafeMutablePointer) -> Void ) -> (leaf: _UnmanagedNode, slot: _Slot) { let (itemMap, childMap) = ( - self.raw.storage.header.bitmapsForNewCollision(at: slot, bucket)) + self.raw.storage.header.bitmapsForSpawningChild(at: slot, bucket)) let c = self.count let childSlot = childMap.slot(of: bucket) let r = update { src in diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift b/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift index e6248b6c..6a1c4442 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift @@ -79,7 +79,7 @@ extension _Node { // If the key already exists, we ensure uniqueness for its node and extract // its item but otherwise leave the tree as it was. let isUnique = self.isUnique() - let r = find(state.path.level, state.key, state.hash, forInsert: true) + let r = findForInsertion(state.path.level, state.key, state.hash) switch r { case .found(_, let slot): ensureUnique(isUnique: isUnique) @@ -88,13 +88,17 @@ extension _Node { state.found = true (state.key, state.value) = update { $0.itemPtr(at: slot).move() } - case .notFound(_, let slot): + + case .insert(_, let slot): state.path.selectItem(at: slot) - case .newCollision(_, let slot): + case .appendCollision: + state.path.selectItem(at: _Slot(self.count)) + + case .spawnChild(_, let slot): state.path.selectItem(at: slot) - case .expansion(_): + case .expansion: state.path.selectEnd() case .descend(_, let slot): @@ -191,7 +195,7 @@ extension _Node { _ hash: _Hash ) -> DefaultedValueUpdateState { let isUnique = self.isUnique() - let r = find(level, key, hash, forInsert: true) + let r = findForInsertion(level, key, hash) switch r { case .found(_, let slot): ensureUnique(isUnique: isUnique) @@ -201,7 +205,7 @@ extension _Node { at: slot, inserted: false) - case .notFound(let bucket, let slot): + case .insert(let bucket, let slot): ensureUniqueAndInsertItem(isUnique: isUnique, slot, bucket) { _ in } return DefaultedValueUpdateState( (key, defaultValue()), @@ -209,8 +213,16 @@ extension _Node { at: slot, inserted: true) - case .newCollision(let bucket, let slot): - let r = ensureUniqueAndMakeNewCollision( + case .appendCollision: + ensureUniqueAndAppendCollision(isUnique: isUnique, hash) { _ in } + return DefaultedValueUpdateState( + (key, defaultValue()), + in: unmanaged, + at: _Slot(self.count &- 1), + inserted: true) + + case .spawnChild(let bucket, let slot): + let r = ensureUniqueAndSpawnChild( isUnique: isUnique, level: level, replacing: slot, bucket, @@ -221,11 +233,11 @@ extension _Node { at: r.slot, inserted: true) - case .expansion(let collisionHash): + case .expansion: let r = _Node.build( level: level, item1: { _ in }, hash, - child2: self, collisionHash + child2: self, self.collisionHash ) self = r.top return DefaultedValueUpdateState( diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift index 4af6e0ac..c1378085 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift @@ -19,54 +19,49 @@ extension _Node { /// by inlining the remaining item into the parent node. @inlinable internal mutating func remove( - _ key: Key, _ level: _Level, _ hash: _Hash + _ level: _Level, _ key: Key, _ hash: _Hash ) -> Element? { defer { _invariantCheck() } guard self.isUnique() else { - guard let r = removing(key, level, hash) else { return nil } + guard let r = removing(level, key, hash) else { return nil } self = r.replacement return r.old } - let r = find(level, key, hash, forInsert: false) - switch r { - case .found(let bucket, let slot): - return _removeItemFromUniqueLeafNode(level, bucket, slot) { $0.move() } - case .notFound, .newCollision, .expansion: - return nil - case .descend(let bucket, let slot): - let (old, needsInlining) = update { - let child = $0.childPtr(at: slot) - let old = child.pointee.remove(key, level.descend(), hash) - guard old != nil else { return (old, false) } - let needsInlining = child.pointee.hasSingletonItem - return (old, needsInlining) - } - guard old != nil else { return nil } - _fixupUniqueAncestorAfterItemRemoval( - slot, { _ in bucket }, needsInlining: needsInlining) - return old + guard let r = find(level, key, hash) else { return nil } + guard r.descend else { + let bucket = hash[level] + return _removeItemFromUniqueLeafNode(level, bucket, r.slot) { $0.move() } } + + let (old, needsInlining) = update { + let child = $0.childPtr(at: r.slot) + let old = child.pointee.remove(level.descend(), key, hash) + guard old != nil else { return (old, false) } + let needsInlining = child.pointee.hasSingletonItem + return (old, needsInlining) + } + guard old != nil else { return nil } + _fixupUniqueAncestorAfterItemRemoval( + r.slot, { _ in hash[level] }, needsInlining: needsInlining) + return old } } extension _Node { @inlinable internal func removing( - _ key: Key, _ level: _Level, _ hash: _Hash + _ level: _Level, _ key: Key, _ hash: _Hash ) -> (replacement: _Node, old: Element)? { - let r = find(level, key, hash, forInsert: false) - switch r { - case .found(let bucket, let slot): - return _removingItemFromLeaf(level, slot, bucket) - case .notFound, .newCollision, .expansion: - return nil - case .descend(let bucket, let slot): - let r = read { $0[child: slot].removing(key, level.descend(), hash) } - guard let r = r else { return nil } - return ( - _fixedUpAncestorAfterItemRemoval(level, slot, bucket, r.replacement), - r.old) + guard let r = find(level, key, hash) else { return nil } + guard r.descend else { + return _removingItemFromLeaf(level, hash[level], r.slot) } + let r2 = read { $0[child: r.slot].removing(level.descend(), key, hash) } + guard let r2 = r2 else { return nil } + return ( + _fixedUpAncestorAfterItemRemoval( + level, r.slot, hash[level], r2.replacement), + r2.old) } } @@ -107,7 +102,7 @@ extension _Node { if level == path.level { let slot = path.currentItemSlot let bucket = read { $0.itemBucket(at: slot) } - return _removingItemFromLeaf(level, slot, bucket) + return _removingItemFromLeaf(level, bucket, slot) } let slot = path.childSlot(at: level) let (bucket, r) = read { @@ -142,7 +137,7 @@ extension _Node { @inlinable internal func _removingItemFromLeaf( - _ level: _Level, _ slot: _Slot, _ bucket: _Bucket + _ level: _Level, _ bucket: _Bucket, _ slot: _Slot ) -> (replacement: _Node, old: Element) { // Don't copy the node if we'd immediately discard it. let willAtrophy = read { @@ -218,9 +213,9 @@ extension _Node { assert(isCollisionNode && hasSingletonItem) assert(isUnique()) update { - let hash = $0.collisionHash - $0.itemMap = _Bitmap(hash[.top]) + $0.itemMap = _Bitmap($0.collisionHash[.top]) $0.childMap = .empty + $0.bytesFree &+= MemoryLayout<_Hash>.stride } } } diff --git a/Sources/PersistentCollections/Node/_Node+Transform.swift b/Sources/PersistentCollections/Node/_Node+Transform.swift index ac838d7b..a13d5178 100644 --- a/Sources/PersistentCollections/Node/_Node+Transform.swift +++ b/Sources/PersistentCollections/Node/_Node+Transform.swift @@ -18,12 +18,20 @@ extension _Node { ) rethrows -> _Node { let c = self.count return try read { source in - var result = _Node.allocate( - itemMap: source.itemMap, - childMap: source.childMap, - count: c, - initializingWith: { _, _ in } - ).node + var result: _Node + if isCollisionNode { + result = _Node.allocateCollision( + count: c, source.collisionHash, + initializingWith: { _ in } + ).node + } else { + result = _Node.allocate( + itemMap: source.itemMap, + childMap: source.childMap, + count: c, + initializingWith: { _, _ in } + ).node + } try result.update { target in let sourceItems = source.reverseItems let targetItems = target.reverseItems @@ -59,6 +67,7 @@ extension _Node { } success = true } + result._invariantCheck() return result } } diff --git a/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift b/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift index 7491c85e..583abccd 100644 --- a/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift +++ b/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift @@ -153,13 +153,23 @@ extension _Node.UnsafeHandle { @inlinable @inline(__always) internal var collisionCount: Int { get { _header.pointee.collisionCount } - nonmutating set { _header.pointee.collisionCount = newValue } + nonmutating set { + assertMutable() + _header.pointee.collisionCount = newValue + } } - @inlinable + @inlinable @inline(__always) internal var collisionHash: _Hash { - assert(isCollisionNode) - return _Hash(self[item: .zero].key) + get { + assert(isCollisionNode) + return _memory.load(as: _Hash.self) + } + nonmutating set { + assertMutable() + assert(isCollisionNode) + _memory.storeBytes(of: newValue, as: _Hash.self) + } } @inlinable @inline(__always) diff --git a/Sources/PersistentCollections/Node/_Node+isDisjoint.swift b/Sources/PersistentCollections/Node/_Node+isDisjoint.swift index 3e1abb92..911d9c8b 100644 --- a/Sources/PersistentCollections/Node/_Node+isDisjoint.swift +++ b/Sources/PersistentCollections/Node/_Node+isDisjoint.swift @@ -79,9 +79,7 @@ extension _Node { if other.isCollisionNode { return read { l in other.read { r in - let lh = l.collisionHash - let rh = r.collisionHash - guard lh == rh else { return true } + guard l.collisionHash == r.collisionHash else { return true } let litems = l.reverseItems let ritems = r.reverseItems return litems.allSatisfy { li in diff --git a/Sources/PersistentCollections/Node/_Node+isSubset.swift b/Sources/PersistentCollections/Node/_Node+isSubset.swift index 9a1a3eaf..9c1a04d9 100644 --- a/Sources/PersistentCollections/Node/_Node+isSubset.swift +++ b/Sources/PersistentCollections/Node/_Node+isSubset.swift @@ -26,7 +26,6 @@ extension _Node { let items = $0.reverseItems let hash = $0.collisionHash return items.indices.allSatisfy { - // FIXME: This will repeatedly & unnecessarily call `collisionHash` other.containsKey(level, items[$0].key, hash) } } diff --git a/Sources/PersistentCollections/Node/_Node.swift b/Sources/PersistentCollections/Node/_Node.swift index de2159ca..9a0a3c17 100644 --- a/Sources/PersistentCollections/Node/_Node.swift +++ b/Sources/PersistentCollections/Node/_Node.swift @@ -104,6 +104,11 @@ extension _Node { read { $0.isCollisionNode } } + @inlinable + internal var collisionHash: _Hash { + read { $0.collisionHash } + } + @inlinable internal var hasSingletonItem: Bool { read { $0.hasSingletonItem } diff --git a/Sources/PersistentCollections/Node/_RawNode+UnsafeHandle.swift b/Sources/PersistentCollections/Node/_RawNode+UnsafeHandle.swift index 04a6a8ed..f7ea8557 100644 --- a/Sources/PersistentCollections/Node/_RawNode+UnsafeHandle.swift +++ b/Sources/PersistentCollections/Node/_RawNode+UnsafeHandle.swift @@ -62,6 +62,12 @@ extension _RawNode.UnsafeHandle { _header.pointee.isCollisionNode } + @inline(__always) + internal var collisionHash: _Hash { + assert(isCollisionNode) + return _memory.load(as: _Hash.self) + } + @inline(__always) internal var hasChildren: Bool { _header.pointee.hasChildren diff --git a/Sources/PersistentCollections/Node/_StorageHeader.swift b/Sources/PersistentCollections/Node/_StorageHeader.swift index fa56caa9..f32044e9 100644 --- a/Sources/PersistentCollections/Node/_StorageHeader.swift +++ b/Sources/PersistentCollections/Node/_StorageHeader.swift @@ -122,38 +122,22 @@ extension _StorageHeader { } extension _StorageHeader { - @inlinable - internal static func counts( - itemMap: _Bitmap, childMap: _Bitmap - ) -> (itemCount: Int, childCount: Int) { - if itemMap == childMap { - return (Int(truncatingIfNeeded: itemMap._value), 0) - } - return (itemMap.count, childMap.count) - } - @inlinable internal func bitmapsForInsertingItem( at slot: _Slot, _ bucket: _Bucket ) -> (itemMap: _Bitmap, childMap: _Bitmap) { + assert(!isCollisionNode) + assert(!bucket.isInvalid) + assert(!itemMap.contains(bucket) && !childMap.contains(bucket)) var itemMap = self.itemMap - var childMap = self.childMap - if bucket.isInvalid { - assert(isCollisionNode) - itemMap._value += 1 - childMap = itemMap - } else { - assert(!isCollisionNode) - assert(!itemMap.contains(bucket) && !childMap.contains(bucket)) - itemMap.insert(bucket) - assert(itemMap.slot(of: bucket) == slot) - } + itemMap.insert(bucket) + assert(itemMap.slot(of: bucket) == slot) return (itemMap, childMap) } @inlinable - internal func bitmapsForNewCollision( + internal func bitmapsForSpawningChild( at slot: _Slot, _ bucket: _Bucket ) -> (itemMap: _Bitmap, childMap: _Bitmap) { diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift index b6907fdb..f47409cc 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift @@ -383,7 +383,7 @@ extension PersistentDictionary { @discardableResult public mutating func removeValue(forKey key: Key) -> Value? { _invalidateIndices() - return _root.remove(key, .top, _Hash(key))?.value + return _root.remove(.top, key, _Hash(key))?.value } // fluid/immutable API diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift index 341acf5c..c8c815d3 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift @@ -47,7 +47,7 @@ extension PersistentSet: SetAlgebra { public mutating func remove(_ member: Element) -> Element? { let hash = _Hash(member) _invalidateIndices() - return _root.remove(member, .top, hash)?.key + return _root.remove(.top, member, hash)?.key } @discardableResult