From 03c1bd958acac2e36eb996eee4d7d0a249bbb3f5 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sun, 25 Sep 2022 22:19:45 -0700 Subject: [PATCH] [PersistentSet] Implement structural union operation (untested) --- .../PersistentCollections/Node/_Bitmap.swift | 12 + .../Node/_Node+Builder.swift | 7 +- .../Node/_Node+Initializers.swift | 45 ++ .../Node/_Node+Structural subtracting.swift | 11 +- .../Node/_Node+Structural union.swift | 212 ++++++++ .../Node/_Node+Subtree Insertions.swift | 512 +++++++++++++----- .../Node/_Node+Subtree Modify.swift | 18 +- .../Node/_Node+UnsafeHandle.swift | 2 +- .../Node/_StorageHeader.swift | 30 - .../PersistentDictionary+Initializers.swift | 10 +- .../PersistentDictionary.swift | 33 +- .../PersistentSet+SetAlgebra basics.swift | 38 +- .../PersistentSet+SetAlgebra union.swift | 9 +- 13 files changed, 694 insertions(+), 245 deletions(-) create mode 100644 Sources/PersistentCollections/Node/_Node+Structural union.swift diff --git a/Sources/PersistentCollections/Node/_Bitmap.swift b/Sources/PersistentCollections/Node/_Bitmap.swift index 7cfdce1b..199b61b9 100644 --- a/Sources/PersistentCollections/Node/_Bitmap.swift +++ b/Sources/PersistentCollections/Node/_Bitmap.swift @@ -112,12 +112,24 @@ extension _Bitmap { _value |= (1 &<< bucket.value) } + @inlinable @inline(__always) + internal func inserting(_ bucket: _Bucket) -> _Bitmap { + assert(bucket.value < capacity) + return _Bitmap(_value: _value | (1 &<< bucket.value)) + } + @inlinable @inline(__always) internal mutating func remove(_ bucket: _Bucket) { assert(bucket.value < capacity) _value &= ~(1 &<< bucket.value) } + @inlinable @inline(__always) + internal func removing(_ bucket: _Bucket) -> _Bitmap { + assert(bucket.value < capacity) + return _Bitmap(_value: _value & ~(1 &<< bucket.value)) + } + @inlinable @inline(__always) internal func slot(of bucket: _Bucket) -> _Slot { _Slot(_value._rank(ofBit: bucket.value)) diff --git a/Sources/PersistentCollections/Node/_Node+Builder.swift b/Sources/PersistentCollections/Node/_Node+Builder.swift index 7d3d4972..a45b3dc3 100644 --- a/Sources/PersistentCollections/Node/_Node+Builder.swift +++ b/Sources/PersistentCollections/Node/_Node+Builder.swift @@ -56,7 +56,7 @@ extension _Node { assert(node.isCollisionNode) assert(hash == h) assert(hash == node.collisionHash) - node.ensureUniqueAndAppendCollision(isUnique: true, newItem) + _ = node.ensureUniqueAndAppendCollision(isUnique: true, newItem) self = .node(node, h) } } @@ -80,7 +80,7 @@ extension _Node { assert(!node.isCollisionNode) assert(nodeHash.isEqual(to: hashPrefix, upTo: level)) let bucket = hashPrefix[level] - node.ensureUniqueAndInsertItem(isUnique: true, newItem, bucket) + node.ensureUniqueAndInsertItem(isUnique: true, newItem, at: bucket) self = .node(node, nodeHash) } } @@ -120,7 +120,8 @@ extension _Node { } assert(!node.isCollisionNode) assert(nodeHash.isEqual(to: itemHash, upTo: level)) - node.ensureUniqueAndInsertItem(isUnique: true, item, itemHash[level]) + node.ensureUniqueAndInsertItem( + isUnique: true, item, at: itemHash[level]) self = .node(node, nodeHash) case (.node(var node, let nodeHash), .node(let child, let childHash)): if node.isCollisionNode { diff --git a/Sources/PersistentCollections/Node/_Node+Initializers.swift b/Sources/PersistentCollections/Node/_Node+Initializers.swift index fc7cdfd2..0082620a 100644 --- a/Sources/PersistentCollections/Node/_Node+Initializers.swift +++ b/Sources/PersistentCollections/Node/_Node+Initializers.swift @@ -139,6 +139,27 @@ extension _Node { r.node._invariantCheck() return r.node } + + @inlinable + internal static func _regularNode( + _ child1: __owned _Node, + _ child1Bucket: _Bucket, + _ child2: __owned _Node, + _ child2Bucket: _Bucket + ) -> _Node { + assert(child1Bucket != child2Bucket) + let r = _Node.allocate( + itemMap: .empty, + childMap: _Bitmap(child1Bucket, child2Bucket), + count: child1.count &+ child2.count + ) { children, items in + assert(items.count == 0 && children.count == 2) + children.initializeElement(at: 0, to: child1) + children.initializeElement(at: 1, to: child2) + } + r.node._invariantCheck() + return r.node + } } extension _Node { @@ -150,6 +171,7 @@ extension _Node { item2 inserter2: (UnsafeMutablePointer) -> Void, _ hash2: _Hash ) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) { + assert(hash1.isEqual(to: hash2, upTo: level.ascend())) if hash1 == hash2 { let top = _collisionNode(hash1, item1, inserter2) return (top, top.unmanaged, _Slot(0), _Slot(1)) @@ -203,4 +225,27 @@ extension _Node { let node = _regularNode(inserter1, hash1[level], child2, hash2[level]) return (node, node.unmanaged, .zero, .zero) } + + @inlinable + internal static func build( + level: _Level, + child1: __owned _Node, + _ hash1: _Hash, + child2: __owned _Node, + _ hash2: _Hash + ) -> _Node { + assert(child1.isCollisionNode) + assert(child2.isCollisionNode) + assert(hash1 != hash2) + let b1 = hash1[level] + let b2 = hash2[level] + guard b1 == b2 else { + return _regularNode(child1, b1, child2, b2) + } + let node = build( + level: level.descend(), + child1: child1, hash1, + child2: child2, hash2) + return _regularNode(node, b1) + } } diff --git a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift index 2d72b473..b655d737 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift @@ -42,8 +42,7 @@ extension _Node { let lp = l.itemPtr(at: lslot) let h = _Hash(lp.pointee.key) if !r[child: rslot].containsKey(level.descend(), lp.pointee.key, h) { - let hashPrefix = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, lp.pointee, hashPrefix) + result.addNewItem(level, lp.pointee, h) } } @@ -123,12 +122,10 @@ extension _Node { } return Builder(level, node, l.collisionHash) } - if r.childMap.contains(bucket) { + else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - return subtracting( - level.descend(), - hashPrefix.appending(bucket, at: level), - r[child: rslot]) + let h = hashPrefix.appending(bucket, at: level) + return subtracting(level.descend(), h, r[child: rslot]) } return .empty } diff --git a/Sources/PersistentCollections/Node/_Node+Structural union.swift b/Sources/PersistentCollections/Node/_Node+Structural union.swift new file mode 100644 index 00000000..c4d50eff --- /dev/null +++ b/Sources/PersistentCollections/Node/_Node+Structural union.swift @@ -0,0 +1,212 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension _Node { + @inlinable + internal func union( + _ level: _Level, + _ hashPrefix: _Hash, + _ other: _Node + ) -> (copied: Bool, node: _Node) { + if self.raw.storage === other.raw.storage { + return (false, self) + } + + if self.isCollisionNode || other.isCollisionNode { + return _union_slow(level, hashPrefix, other) + } + + return self.read { l in + other.read { r in + var node = self + var copied = false + + for (bucket, lslot) in l.itemMap { + if r.itemMap.contains(bucket) { + let rslot = r.itemMap.slot(of: bucket) + let lp = l.itemPtr(at: lslot) + let rp = r.itemPtr(at: rslot) + if lp.pointee.key != rp.pointee.key { + _ = node.ensureUniqueAndSpawnChild( + isUnique: copied, + level: level, + replacing: bucket, + itemSlot: lslot, + newHash: _Hash(rp.pointee.key), + { $0.initialize(to: rp.pointee) }) + copied = true + } + } + else if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + let lp = l.itemPtr(at: lslot) + let rp = r.childPtr(at: rslot) + let h = _Hash(lp.pointee.key) + if !rp.pointee.containsKey(level.descend(), lp.pointee.key, h) { + node.ensureUniqueAndPushItemIntoNewChild( + isUnique: copied, + level: level, + rp.pointee, + at: bucket, + itemSlot: lslot) + copied = true + } + } + } + + for (bucket, lslot) in l.childMap { + if r.itemMap.contains(bucket) { + let rslot = r.itemMap.slot(of: bucket) + let rp = r.itemPtr(at: rslot) + let h = _Hash(rp.pointee.key) + let r = l[child: lslot].inserting( + level.descend(), rp.pointee.key, h + ) { + $0.initialize(to: rp.pointee) + } + guard r.inserted else { + // Nothing to do + continue + } + node.ensureUnique(isUnique: copied) + node.update { $0[child: lslot] = r.node } + node.count &+= 1 + copied = true + } + else if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + let child = l[child: lslot].union( + level.descend(), + hashPrefix.appending(bucket, at: level), + r[child: rslot]) + guard child.copied else { + // Nothing to do + continue + } + node.ensureUnique(isUnique: copied) + let delta = node.update { + let p = $0.childPtr(at: lslot) + let delta = child.node.count &- p.pointee.count + $0[child: lslot] = child.node + return delta + } + assert(delta > 0) + node.count &+= delta + copied = true + } + } + + return (copied, node) + } + } + } + + @inlinable @inline(never) + internal func _union_slow( + _ level: _Level, + _ hashPrefix: _Hash, + _ other: _Node + ) -> (copied: Bool, node: _Node) { + let lc = self.isCollisionNode + let rc = other.isCollisionNode + if lc && rc { + return read { l in + other.read { r in + guard l.collisionHash == r.collisionHash else { + let node = _Node.build( + level: level, + child1: self, l.collisionHash, + child2: other, r.collisionHash) + return (true, node) + } + var copied = false + var node = self + let litems = l.reverseItems + var p = r.itemPtr(at: .zero) + let end = r.itemPtr(at: r.itemsEndSlot) + while p != end { + if !litems.contains(where: { $0.key == p.pointee.key }) { + _ = node.ensureUniqueAndAppendCollision( + isUnique: copied, p.pointee) + copied = true + } + } + return (copied, node) + } + } + } + + // One of the nodes must be on a compressed path. + assert(!level.isAtBottom) + + if lc { + // `self` is a collision node on a compressed path. The other tree might + // have the same set of collisions, just expanded a bit deeper. + return read { l in + other.read { r in + let bucket = l.collisionHash[level] + if r.itemMap.contains(bucket) { + let rslot = r.itemMap.slot(of: bucket) + let node = other.copyNodeAndPushItemIntoNewChild( + level: level, + self, + at: bucket, + itemSlot: rslot) + return (true, node) + } + else if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + let h = hashPrefix.appending(bucket, at: level) + let res = self.union(level.descend(), h, r[child: rslot]) + var node = other.copy() + node.update { $0[child: rslot] = res.node } + return (true, node) + } + else { + var node = other.copy(withFreeSpace: _Node.spaceForNewChild) + node.insertChild(self, bucket) + return (true, node) + } + } + } + } + + assert(rc) + // `other` is a collision node on a compressed path. + return read { l in + other.read { r in + let bucket = r.collisionHash[level] + if l.itemMap.contains(bucket) { + let lslot = l.itemMap.slot(of: bucket) + let node = self.copyNodeAndPushItemIntoNewChild( + level: level, + other, + at: bucket, + itemSlot: lslot) + return (true, node) + } + else if l.childMap.contains(bucket) { + let lslot = l.childMap.slot(of: bucket) + let h = hashPrefix.appending(bucket, at: level) + let res = l[child: lslot].union(level.descend(), h, other) + var node = self.copy() + node.update { $0[child: lslot] = res.node } + return (true, node) + } + else { + var node = self.copy(withFreeSpace: _Node.spaceForNewChild) + node.insertChild(other, bucket) + return (true, node) + } + } + } + } +} diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift index 0cc49f9d..b78d7d1d 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift @@ -14,24 +14,108 @@ import _CollectionsUtilities extension _Node { @inlinable internal mutating func insert( - _ item: __owned Element, _ level: _Level, - _ hash: _Hash - ) -> Bool { - let r = update(item.key, level, hash) - guard r.inserted else { return false } - UnsafeHandle.update(r.leaf) { - let p = $0.itemPtr(at: r.slot) - p.initialize(to: item) + _ key: Key, + _ hash: _Hash, + _ inserter: (UnsafeMutablePointer) -> Void + ) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) { + defer { _invariantCheck() } + let isUnique = self.isUnique() + if !isUnique { + let r = self.inserting(level, key, hash, inserter) + self = r.node + return (r.inserted, r.leaf, r.slot) + } + let r = findForInsertion(level, key, hash) + switch r { + case .found(_, let slot): + return (false, unmanaged, slot) + case .insert(let bucket, let slot): + ensureUniqueAndInsertItem( + isUnique: true, at: bucket, itemSlot: slot, inserter) + return (true, unmanaged, slot) + case .appendCollision: + let slot = ensureUniqueAndAppendCollision(isUnique: true, inserter) + return (true, unmanaged, slot) + case .spawnChild(let bucket, let slot): + let r = ensureUniqueAndSpawnChild( + isUnique: true, + level: level, + replacing: bucket, + itemSlot: slot, + newHash: hash, + inserter) + return (true, r.leaf, r.slot) + case .expansion: + let r = _Node.build( + level: level, + item1: inserter, hash, + child2: self, self.collisionHash) + self = r.top + return (true, r.leaf, r.slot1) + case .descend(_, let slot): + let r = update { + $0[child: slot].insert(level.descend(), key, hash, inserter) + } + if r.inserted { count &+= 1 } + return r + } + } + + @inlinable + internal func inserting( + _ level: _Level, + _ key: Key, + _ hash: _Hash, + _ inserter: (UnsafeMutablePointer) -> Void + ) -> (inserted: Bool, node: _Node, leaf: _UnmanagedNode, slot: _Slot) { + defer { _invariantCheck() } + let r = findForInsertion(level, key, hash) + switch r { + case .found(_, let slot): + return (false, self, unmanaged, slot) + case .insert(let bucket, let slot): + let node = copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter) + return (true, node, node.unmanaged, slot) + case .appendCollision: + let r = copyNodeAndAppendCollision(inserter) + return (true, r.node, r.node.unmanaged, r.slot) + case .spawnChild(let bucket, let slot): + let existingHash = read { _Hash($0[item: slot].key) } + let r = copyNodeAndSpawnChild( + level: level, + replacing: bucket, + itemSlot: slot, + existingHash: existingHash, + newHash: hash, + inserter) + return (true, r.node, r.leaf, r.slot) + case .expansion: + let r = _Node.build( + level: level, + item1: { _ in }, hash, + child2: self, self.collisionHash) + return (true, r.top, r.leaf, r.slot1) + case .descend(_, let slot): + let r = read { + $0[child: slot].inserting(level.descend(), key, hash, inserter) + } + guard r.inserted else { + return (false, self, r.leaf, r.slot) + } + var copy = self.copy() + copy.update { $0[child: slot] = r.node } + copy.count &+= 1 + return (true, copy, r.leaf, r.slot) } - return true } @inlinable internal mutating func update( - _ key: Key, _ level: _Level, - _ hash: _Hash + _ key: Key, + _ hash: _Hash, + _ inserter: (UnsafeMutablePointer) -> Void ) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) { defer { _invariantCheck() } let isUnique = self.isUnique() @@ -41,31 +125,32 @@ extension _Node { ensureUnique(isUnique: isUnique) return (false, unmanaged, slot) case .insert(let bucket, let slot): - ensureUniqueAndInsertItem(isUnique: isUnique, slot, bucket) { _ in } + ensureUniqueAndInsertItem( + isUnique: isUnique, at: bucket, itemSlot: slot, inserter) return (true, unmanaged, slot) case .appendCollision: - ensureUniqueAndAppendCollision(isUnique: isUnique) { _ in } - return (true, unmanaged, _Slot(self.count &- 1)) + let slot = ensureUniqueAndAppendCollision(isUnique: isUnique, inserter) + return (true, unmanaged, slot) case .spawnChild(let bucket, let slot): let r = ensureUniqueAndSpawnChild( isUnique: isUnique, level: level, - replacing: slot, bucket, + replacing: bucket, + itemSlot: slot, newHash: hash, - inserter: { _ in } - ) + inserter) return (true, r.leaf, r.slot) case .expansion: let r = _Node.build( level: level, - item1: { _ in }, hash, + item1: inserter, hash, child2: self, self.collisionHash) self = r.top return (true, r.leaf, r.slot1) case .descend(_, let slot): ensureUnique(isUnique: isUnique) let r = update { - $0[child: slot].update(key, level.descend(), hash) + $0[child: slot].update(level.descend(), key, hash, inserter) } if r.inserted { count &+= 1 } return r @@ -78,10 +163,14 @@ extension _Node { internal mutating func ensureUniqueAndInsertItem( isUnique: Bool, _ item: Element, - _ bucket: _Bucket + at bucket: _Bucket ) { let slot = self.read { $0.itemMap.slot(of: bucket) } - ensureUniqueAndInsertItem(isUnique: isUnique, slot, bucket) { + ensureUniqueAndInsertItem( + isUnique: isUnique, + at: bucket, + itemSlot: slot + ) { $0.initialize(to: item) } } @@ -89,18 +178,19 @@ extension _Node { @inlinable internal mutating func ensureUniqueAndInsertItem( isUnique: Bool, - _ slot: _Slot, - _ bucket: _Bucket, - inserter: (UnsafeMutablePointer) -> Void + at bucket: _Bucket, + itemSlot slot: _Slot, + _ inserter: (UnsafeMutablePointer) -> Void ) { assert(!isCollisionNode) if !isUnique { - self = copyNodeAndInsertItem(at: slot, bucket, inserter: inserter) + self = copyNodeAndInsertItem( + at: bucket, itemSlot: slot, inserter) return } if !hasFreeSpace(Self.spaceForNewItem) { - moveNodeAndInsertItem(at: slot, bucket, inserter: inserter) + resizeNodeAndInsertItem(at: bucket, itemSlot: slot, inserter) return } // In-place insert. @@ -113,17 +203,19 @@ extension _Node { @inlinable @inline(never) internal func copyNodeAndInsertItem( - at slot: _Slot, - _ bucket: _Bucket, - inserter: (UnsafeMutablePointer) -> Void + at bucket: _Bucket, + itemSlot slot: _Slot, + _ inserter: (UnsafeMutablePointer) -> Void ) -> _Node { assert(!isCollisionNode) - let (itemMap, childMap) = ( - self.raw.storage.header.bitmapsForInsertingItem(at: slot, bucket)) let c = self.count return read { src in - Self.allocate( - itemMap: itemMap, childMap: childMap, count: c &+ 1 + assert(!src.itemMap.contains(bucket)) + assert(!src.childMap.contains(bucket)) + return Self.allocate( + itemMap: src.itemMap.inserting(bucket), + childMap: src.childMap, + count: c &+ 1 ) { dstChildren, dstItems in dstChildren.initializeAll(fromContentsOf: src.children) @@ -136,23 +228,25 @@ extension _Node { .initializeAll(fromContentsOf: srcItems.prefix(rest)) inserter(dstItems.baseAddress! + rest) - } - }.node + }.node + } } @inlinable @inline(never) - internal mutating func moveNodeAndInsertItem( - at slot: _Slot, - _ bucket: _Bucket, - inserter: (UnsafeMutablePointer) -> Void + internal mutating func resizeNodeAndInsertItem( + at bucket: _Bucket, + itemSlot slot: _Slot, + _ inserter: (UnsafeMutablePointer) -> Void ) { assert(!isCollisionNode) - let (itemMap, childMap) = ( - self.raw.storage.header.bitmapsForInsertingItem(at: slot, bucket)) let c = self.count self = update { src in - Self.allocate( - itemMap: itemMap, childMap: childMap, count: c &+ 1 + assert(!src.itemMap.contains(bucket)) + assert(!src.childMap.contains(bucket)) + return Self.allocate( + itemMap: src.itemMap.inserting(bucket), + childMap: src.childMap, + count: c &+ 1 ) { dstChildren, dstItems in dstChildren.moveInitializeAll(fromContentsOf: src.children) @@ -167,8 +261,8 @@ extension _Node { inserter(dstItems.baseAddress! + rest) src.clear() - } - }.node + }.node + } } } @@ -177,7 +271,7 @@ extension _Node { internal mutating func ensureUniqueAndAppendCollision( isUnique: Bool, _ item: Element - ) { + ) -> _Slot { ensureUniqueAndAppendCollision(isUnique: isUnique) { $0.initialize(to: item) } @@ -186,16 +280,16 @@ extension _Node { @inlinable internal mutating func ensureUniqueAndAppendCollision( isUnique: Bool, - inserter: (UnsafeMutablePointer) -> Void - ) { + _ inserter: (UnsafeMutablePointer) -> Void + ) -> _Slot { assert(isCollisionNode) if !isUnique { - self = copyNodeAndAppendCollision(inserter: inserter) - return + let r = copyNodeAndAppendCollision(inserter) + self = r.node + return r.slot } if !hasFreeSpace(Self.spaceForNewItem) { - moveNodeAndAppendCollision(inserter: inserter) - return + return resizeNodeAndAppendCollision(inserter) } // In-place insert. update { @@ -203,16 +297,17 @@ extension _Node { inserter(p) } self.count &+= 1 + return _Slot(self.count &- 1) } @inlinable @inline(never) internal func copyNodeAndAppendCollision( - inserter: (UnsafeMutablePointer) -> Void - ) -> _Node { + _ inserter: (UnsafeMutablePointer) -> Void + ) -> (node: _Node, slot: _Slot) { assert(isCollisionNode) assert(self.count == read { $0.collisionCount }) let c = self.count - return read { src in + let node = read { src in Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in let srcItems = src.reverseItems assert(dstItems.count == srcItems.count + 1) @@ -220,12 +315,13 @@ extension _Node { inserter(dstItems.baseAddress!) }.node } + return (node, _Slot(c)) } @inlinable @inline(never) - internal mutating func moveNodeAndAppendCollision( - inserter: (UnsafeMutablePointer) -> Void - ) { + internal mutating func resizeNodeAndAppendCollision( + _ inserter: (UnsafeMutablePointer) -> Void + ) -> _Slot { assert(isCollisionNode) assert(self.count == read { $0.collisionCount }) let c = self.count @@ -239,6 +335,174 @@ extension _Node { src.clear() }.node } + return _Slot(c) + } +} + +extension _Node { + @inlinable + internal func _copyNodeAndReplaceItemWithNewChild( + level: _Level, + _ newChild: __owned _Node, + at bucket: _Bucket, + itemSlot: _Slot + ) -> _Node { + let c = self.count + return read { src in + assert(!src.isCollisionNode) + assert(src.itemMap.contains(bucket)) + assert(!src.childMap.contains(bucket)) + assert(src.itemMap.slot(of: bucket) == itemSlot) + + let childSlot = src.childMap.slot(of: bucket) + return Self.allocate( + itemMap: src.itemMap.removing(bucket), + childMap: src.childMap.inserting(bucket), + count: c &+ newChild.count &- 1 + ) { dstChildren, dstItems in + let srcChildren = src.children + let srcItems = src.reverseItems + + // Initialize children. + dstChildren.prefix(childSlot.value) + .initializeAll(fromContentsOf: srcChildren.prefix(childSlot.value)) + let rest = srcChildren.count &- childSlot.value + dstChildren.suffix(rest) + .initializeAll(fromContentsOf: srcChildren.suffix(rest)) + + dstChildren.initializeElement(at: childSlot.value, to: newChild) + + // Initialize items. + dstItems.suffix(itemSlot.value) + .initializeAll(fromContentsOf: srcItems.suffix(itemSlot.value)) + let rest2 = dstItems.count &- itemSlot.value + dstItems.prefix(rest2) + .initializeAll(fromContentsOf: srcItems.prefix(rest2)) + }.node + } + } + + /// The item at `itemSlot` must have already been deinitialized by the time + /// this function is called. + @inlinable + internal mutating func _resizeNodeAndReplaceItemWithNewChild( + level: _Level, + _ newChild: __owned _Node, + at bucket: _Bucket, + itemSlot: _Slot + ) { + let c = self.count + let node = update { src in + assert(!src.isCollisionNode) + assert(src.itemMap.contains(bucket)) + assert(!src.childMap.contains(bucket)) + assert(src.itemMap.slot(of: bucket) == itemSlot) + + let childSlot = src.childMap.slot(of: bucket) + return Self.allocate( + itemMap: src.itemMap.removing(bucket), + childMap: src.childMap.inserting(bucket), + count: c &+ newChild.count &- 1 + ) { dstChildren, dstItems in + let srcChildren = src.children + let srcItems = src.reverseItems + + // Initialize children. + dstChildren.prefix(childSlot.value) + .moveInitializeAll(fromContentsOf: srcChildren.prefix(childSlot.value)) + let rest = srcChildren.count &- childSlot.value + dstChildren.suffix(rest) + .moveInitializeAll(fromContentsOf: srcChildren.suffix(rest)) + + dstChildren.initializeElement(at: childSlot.value, to: newChild) + + // Initialize items. + dstItems.suffix(itemSlot.value) + .moveInitializeAll(fromContentsOf: srcItems.suffix(itemSlot.value)) + let rest2 = dstItems.count &- itemSlot.value + dstItems.prefix(rest2) + .moveInitializeAll(fromContentsOf: srcItems.prefix(rest2)) + + src.clear() + }.node + } + self = node + } +} + +extension _Node { + @inlinable + internal mutating func ensureUniqueAndPushItemIntoNewChild( + isUnique: Bool, + level: _Level, + _ newChild: _Node, + at bucket: _Bucket, + itemSlot: _Slot + ) { + if !isUnique { + self = copyNodeAndPushItemIntoNewChild( + level: level, + newChild, + at: bucket, + itemSlot: itemSlot) + return + } + if !hasFreeSpace(Self.spaceForSpawningChild) { + resizeNodeAndPushItemIntoNewChild( + level: level, + newChild, + at: bucket, + itemSlot: itemSlot) + return + } + + assert(!isCollisionNode) + let item = removeItem(at: itemSlot, bucket, by: { $0.move() }) + let hash = _Hash(item.key) + let r = newChild.inserting(level.descend(), item.key, hash) { + $0.initialize(to: item) + } + assert(r.inserted) + insertChild(newChild, bucket) + } + + @inlinable @inline(never) + internal func copyNodeAndPushItemIntoNewChild( + level: _Level, + _ newChild: __owned _Node, + at bucket: _Bucket, + itemSlot: _Slot + ) -> _Node { + assert(!isCollisionNode) + let item = read { $0[item: itemSlot] } + let hash = _Hash(item.key) + var newChild = newChild + _ = newChild.update(level, item.key, hash) { $0.initialize(to: item) } + return _copyNodeAndReplaceItemWithNewChild( + level: level, + newChild, + at: bucket, + itemSlot: itemSlot) + } + + @inlinable @inline(never) + internal mutating func resizeNodeAndPushItemIntoNewChild( + level: _Level, + _ newChild: __owned _Node, + at bucket: _Bucket, + itemSlot: _Slot + ) { + assert(!isCollisionNode) + let item = update { $0.itemPtr(at: itemSlot).move() } + let hash = _Hash(item.key) + var newChild = newChild + let r = newChild.update(level, item.key, hash) { $0.initialize(to: item) } + assert(r.inserted) + _resizeNodeAndReplaceItemWithNewChild( + level: level, + newChild, + at: bucket, + itemSlot: itemSlot) } } @@ -247,12 +511,13 @@ extension _Node { internal mutating func ensureUniqueAndSpawnChild( isUnique: Bool, level: _Level, - replacing slot: _Slot, - _ bucket: _Bucket, + replacing bucket: _Bucket, + itemSlot: _Slot, newHash: _Hash, - inserter: (UnsafeMutablePointer) -> Void + _ inserter: (UnsafeMutablePointer) -> Void ) -> (leaf: _UnmanagedNode, slot: _Slot) { - let existingHash = read { _Hash($0[item: slot].key) } + let existingHash = read { _Hash($0[item: itemSlot].key) } + assert(existingHash.isEqual(to: newHash, upTo: level)) if newHash == existingHash, hasSingletonItem { // Convert current node to a collision node. self = _Node._collisionNode(newHash, read { $0[item: .zero] }, inserter) @@ -262,23 +527,25 @@ extension _Node { if !isUnique { let r = copyNodeAndSpawnChild( level: level, - replacing: slot, bucket, + replacing: bucket, + itemSlot: itemSlot, existingHash: existingHash, newHash: newHash, - inserter: inserter) + inserter) self = r.node return (r.leaf, r.slot) } if !hasFreeSpace(Self.spaceForSpawningChild) { - return moveNodeAndSpawnChild( + return resizeNodeAndSpawnChild( level: level, - replacing: slot, bucket, + replacing: bucket, + itemSlot: itemSlot, existingHash: existingHash, newHash: newHash, - inserter: inserter) + inserter) } - let existing = removeItem(at: slot, bucket) { $0.move() } + let existing = removeItem(at: itemSlot, bucket) { $0.move() } let r = _Node.build( level: level.descend(), item1: existing, existingHash, @@ -290,96 +557,49 @@ extension _Node { @inlinable @inline(never) internal func copyNodeAndSpawnChild( level: _Level, - replacing slot: _Slot, - _ bucket: _Bucket, + replacing bucket: _Bucket, + itemSlot: _Slot, existingHash: _Hash, newHash: _Hash, - inserter: (UnsafeMutablePointer) -> Void + _ inserter: (UnsafeMutablePointer) -> Void ) -> (node: _Node, leaf: _UnmanagedNode, slot: _Slot) { - let (itemMap, childMap) = ( - self.raw.storage.header.bitmapsForSpawningChild(at: slot, bucket)) - let c = self.count - let childSlot = childMap.slot(of: bucket) - let r = read { src in - Self.allocate( - itemMap: itemMap, childMap: childMap, count: c &+ 1 - ) { dstChildren, dstItems in - let srcChildren = src.children - let srcItems = src.reverseItems - let i = srcItems.count &- 1 &- slot.value - - // Initialize children. - dstChildren.prefix(childSlot.value) - .initializeAll(fromContentsOf: srcChildren.prefix(childSlot.value)) - let rest = srcChildren.count &- childSlot.value - dstChildren.suffix(rest) - .initializeAll(fromContentsOf: srcChildren.suffix(rest)) - - let r = _Node.build( - level: level.descend(), - item1: srcItems[i], existingHash, - item2: inserter, newHash) - dstChildren.initializeElement(at: childSlot.value, to: r.top) - - // Initialize items. - dstItems.prefix(i).initializeAll(fromContentsOf: srcItems.prefix(i)) - let rest2 = dstItems.count &- i - dstItems.suffix(rest2) - .initializeAll(fromContentsOf: srcItems.suffix(rest2)) - - return (leaf: r.leaf, slot: r.slot2) - } + let r = read { + _Node.build( + level: level.descend(), + item1: $0[item: itemSlot], existingHash, + item2: inserter, newHash) } - return (r.node, r.result.leaf, r.result.slot) + let node = _copyNodeAndReplaceItemWithNewChild( + level: level, + r.top, + at: bucket, + itemSlot: itemSlot) + node._invariantCheck() + return (node, r.leaf, r.slot2) } @inlinable @inline(never) - internal mutating func moveNodeAndSpawnChild( + internal mutating func resizeNodeAndSpawnChild( level: _Level, - replacing slot: _Slot, - _ bucket: _Bucket, + replacing bucket: _Bucket, + itemSlot: _Slot, existingHash: _Hash, newHash: _Hash, - inserter: (UnsafeMutablePointer) -> Void + _ inserter: (UnsafeMutablePointer) -> Void ) -> (leaf: _UnmanagedNode, slot: _Slot) { - let (itemMap, childMap) = ( - self.raw.storage.header.bitmapsForSpawningChild(at: slot, bucket)) - let c = self.count - let childSlot = childMap.slot(of: bucket) - let r = update { src in - Self.allocate( - itemMap: itemMap, childMap: childMap, count: c &+ 1 - ) { dstChildren, dstItems in - let srcChildren = src.children - let srcItems = src.reverseItems - let i = srcItems.count &- 1 &- slot.value - - // Initialize children. - dstChildren.prefix(childSlot.value) - .moveInitializeAll(fromContentsOf: srcChildren.prefix(childSlot.value)) - let rest = srcChildren.count &- childSlot.value - dstChildren.suffix(rest) - .moveInitializeAll(fromContentsOf: srcChildren.suffix(rest)) - - let r = _Node.build( - level: level.descend(), - item1: srcItems.moveElement(from: i), existingHash, - item2: inserter, newHash) - dstChildren.initializeElement(at: childSlot.value, to: r.top) - - // Initialize items. - dstItems.prefix(i).moveInitializeAll(fromContentsOf: srcItems.prefix(i)) - let rest2 = dstItems.count &- i - dstItems.suffix(rest2) - .moveInitializeAll(fromContentsOf: srcItems.suffix(rest2)) - - src.clear() - return (leaf: r.leaf, slot: r.slot2) - } + let r = update { + _Node.build( + level: level.descend(), + item1: $0.itemPtr(at: itemSlot).move(), existingHash, + item2: inserter, newHash) } - r.node._invariantCheck() - self = r.node - return (r.result.leaf, r.result.slot) + _resizeNodeAndReplaceItemWithNewChild( + level: level, + r.top, + at: bucket, + itemSlot: itemSlot) + _invariantCheck() + return (r.leaf, r.slot2) } } diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift b/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift index a747d675..a46207c6 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift @@ -127,9 +127,10 @@ extension _Node { _finalizeRemoval(.top, state.hash, at: state.path) case (false, true): // Insertion - let inserted = insert( - (state.key, state.value.unsafelyUnwrapped), .top, state.hash) - assert(inserted) + let r = update(.top, state.key, state.hash) { + $0.initialize(to: (state.key, state.value.unsafelyUnwrapped)) + } + assert(r.inserted) case (false, false): // Noop break @@ -206,7 +207,9 @@ extension _Node { inserted: false) case .insert(let bucket, let slot): - ensureUniqueAndInsertItem(isUnique: isUnique, slot, bucket) { _ in } + ensureUniqueAndInsertItem( + isUnique: isUnique, at: bucket, itemSlot: slot + ) { _ in } return DefaultedValueUpdateState( (key, defaultValue()), in: unmanaged, @@ -214,18 +217,19 @@ extension _Node { inserted: true) case .appendCollision: - ensureUniqueAndAppendCollision(isUnique: isUnique) { _ in } + let slot = ensureUniqueAndAppendCollision(isUnique: isUnique) { _ in } return DefaultedValueUpdateState( (key, defaultValue()), in: unmanaged, - at: _Slot(self.count &- 1), + at: slot, inserted: true) case .spawnChild(let bucket, let slot): let r = ensureUniqueAndSpawnChild( isUnique: isUnique, level: level, - replacing: slot, bucket, + replacing: bucket, + itemSlot: slot, newHash: hash) { _ in } return DefaultedValueUpdateState( (key, defaultValue()), diff --git a/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift b/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift index 583abccd..f10d4e5e 100644 --- a/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift +++ b/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift @@ -255,7 +255,7 @@ extension _Node.UnsafeHandle { @inlinable internal func itemPtr(at slot: _Slot) -> UnsafeMutablePointer { - assert(slot.value < itemCount) + assert(slot.value <= itemCount) return _itemsEnd.advanced(by: -1 &- slot.value) } diff --git a/Sources/PersistentCollections/Node/_StorageHeader.swift b/Sources/PersistentCollections/Node/_StorageHeader.swift index da75a59c..e5b6225f 100644 --- a/Sources/PersistentCollections/Node/_StorageHeader.swift +++ b/Sources/PersistentCollections/Node/_StorageHeader.swift @@ -120,33 +120,3 @@ extension _StorageHeader { bytesFree = byteCapacity } } - -extension _StorageHeader { - @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 - itemMap.insert(bucket) - assert(itemMap.slot(of: bucket) == slot) - return (itemMap, childMap) - } - - @inlinable - internal func bitmapsForSpawningChild( - at slot: _Slot, - _ bucket: _Bucket - ) -> (itemMap: _Bitmap, childMap: _Bitmap) { - assert(!isCollisionNode) - assert(itemMap.contains(bucket)) - var itemMap = self.itemMap - var childMap = self.childMap - itemMap.remove(bucket) - childMap.insert(bucket) - return (itemMap, childMap) - } -} diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift index b89db727..24121f41 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift @@ -35,10 +35,12 @@ extension PersistentDictionary { uniqueKeysWithValues keysAndValues: S ) where S.Element == (Key, Value) { self.init() - for (key, value) in keysAndValues { - let hash = _Hash(key) - let inserted = _root.insert((key, value), .top, hash) - precondition(inserted, "Duplicate key: '\(key)'") + for item in keysAndValues { + let hash = _Hash(item.0) + let r = _root.insert(.top, item.0, hash) { + $0.initialize(to: item) + } + precondition(r.inserted, "Duplicate key: '\(item.0)'") } _invariantCheck() } diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift index f47409cc..053a0a3f 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift @@ -279,14 +279,11 @@ extension PersistentDictionary { _ value: __owned Value, forKey key: Key ) -> Value? { let hash = _Hash(key) - let r = _root.update(key, .top, hash) + let r = _root.update(.top, key, hash) { $0.initialize(to: (key, value)) } _invalidateIndices() + if r.inserted { return nil } return _Node.UnsafeHandle.update(r.leaf) { let p = $0.itemPtr(at: r.slot) - if r.inserted { - p.initialize(to: (key, value)) - return nil - } let old = p.pointee.value p.pointee.value = value return old @@ -294,19 +291,17 @@ extension PersistentDictionary { } @inlinable + @discardableResult internal mutating func _updateValue( _ value: __owned Value, forKey key: Key - ) { + ) -> Bool { let hash = _Hash(key) - let r = _root.update(key, .top, hash) - return _Node.UnsafeHandle.update(r.leaf) { - let p = $0.itemPtr(at: r.slot) - if r.inserted { - p.initialize(to: (key, value)) - } else { - p.pointee.value = value - } + let r = _root.update(.top, key, hash) { $0.initialize(to: (key, value)) } + if r.inserted { return true } + _Node.UnsafeHandle.update(r.leaf) { + $0[item: r.slot].value = value } + return false } // fluid/immutable API @@ -333,13 +328,11 @@ extension PersistentDictionary { with body: (inout Value) throws -> R ) rethrows -> R { let hash = _Hash(key) - let r = _root.update(key, .top, hash) + let r = _root.update(.top, key, hash) { + $0.initialize(to: (key, defaultValue())) + } return try _Node.UnsafeHandle.update(r.leaf) { - let p = $0.itemPtr(at: r.slot) - if r.inserted { - p.initialize(to: (key, defaultValue())) - } - return try body(&p.pointee.value) + try body(&$0[item: r.slot].value) } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift index 840dacc6..11e6da28 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift @@ -26,14 +26,14 @@ extension PersistentSet: SetAlgebra { ) -> (inserted: Bool, memberAfterInsert: Element) { let hash = _Hash(newMember) _invalidateIndices() - let r = _root.update(newMember, .top, hash) - return _Node.UnsafeHandle.update(r.leaf) { - let p = $0.itemPtr(at: r.slot) - if r.inserted { - p.initialize(to: (newMember, ())) - return (true, newMember) - } - return (false, p.pointee.key) + let r = _root.update(.top, newMember, hash) { + $0.initialize(to: (newMember, ())) + } + if r.inserted { + return (true, newMember) + } + return _Node.UnsafeHandle.read(r.leaf) { + (false, $0[item: r.slot].key) } } @@ -41,13 +41,10 @@ extension PersistentSet: SetAlgebra { @inlinable internal mutating func _insert(_ newMember: __owned Element) -> Bool { let hash = _Hash(newMember) - let r = _root.update(newMember, .top, hash) - guard r.inserted else { return false } - _Node.UnsafeHandle.update(r.leaf) { - let p = $0.itemPtr(at: r.slot) - p.initialize(to: (newMember, ())) + let r = _root.update(.top, newMember, hash) { + $0.initialize(to: (newMember, ())) } - return true + return r.inserted } @@ -63,15 +60,14 @@ extension PersistentSet: SetAlgebra { @inlinable public mutating func update(with newMember: __owned Element) -> Element? { let hash = _Hash(newMember) - let r = _root.update(newMember, .top, hash) + let r = _root.update(.top, newMember, hash) { + $0.initialize(to: (newMember, ())) + } + if r.inserted { return nil } return _Node.UnsafeHandle.update(r.leaf) { let p = $0.itemPtr(at: r.slot) - if r.inserted { - p.initialize(to: (newMember, ())) - return nil - } - let old = p.pointee.key - p.pointee = (newMember, ()) + let old = p.move().key + p.initialize(to: (newMember, ())) return old } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift index 3dd367d9..3f4ea30d 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift @@ -12,11 +12,8 @@ extension PersistentSet { @inlinable public func union(_ other: __owned Self) -> Self { - // FIXME: Do this with a structural merge. - var copy = self - for item in other { - copy.insert(item) - } - return copy + let r = _root.union(.top, .emptyPrefix, other._root) + guard r.copied else { return self } + return PersistentSet(_new: r.node) } }