From 7d6fe857dac3d0ac2c973d00fba19e8e8806063a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sun, 25 Sep 2022 01:48:18 -0700 Subject: [PATCH 01/18] [Benchmark] Add Xcode scheme for memory benchmark target --- .../xcschemes/memory-benchmark.xcscheme | 82 +++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/memory-benchmark.xcscheme diff --git a/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/memory-benchmark.xcscheme b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/memory-benchmark.xcscheme new file mode 100644 index 00000000..13ae8a1d --- /dev/null +++ b/Utils/swift-collections.xcworkspace/xcshareddata/xcschemes/memory-benchmark.xcscheme @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 03c1bd958acac2e36eb996eee4d7d0a249bbb3f5 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sun, 25 Sep 2022 22:19:45 -0700 Subject: [PATCH 02/18] [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) } } From 83601d9d3e6997ceac23cf46afcdb0dcc13ee43a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sun, 25 Sep 2022 22:21:38 -0700 Subject: [PATCH 03/18] [PersistentSet] Add fluent set operations (untested) --- ...rsistentSet+SetAlgebra fluent basics.swift | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift new file mode 100644 index 00000000..f9caec67 --- /dev/null +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift @@ -0,0 +1,36 @@ +//===----------------------------------------------------------------------===// +// +// 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 PersistentSet { + @inlinable + public func inserting(_ newMember: __owned Element) -> Self { + let hash = _Hash(newMember) + let r = _root.inserting(.top, newMember, hash) { + $0.initialize(to: (newMember, ())) + } + return PersistentSet(_new: r.node) + } + + @inlinable + public func removing(_ member: Element) -> Self { + let hash = _Hash(member) + let r = _root.removing(.top, member, hash) + guard let r = r else { return self } + return PersistentSet(_new: r.replacement) + } + + @inlinable + public func updating(with newMember: __owned Element) -> Self { + var copy = self + copy.update(with: newMember) + return copy + } +} From 6437aea75a7c71d0a901b94ba852d93167850594 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Sun, 25 Sep 2022 22:44:02 -0700 Subject: [PATCH 04/18] [PersistentCollections] Improve test coverage & fixtures --- .../OrderedDictionary Tests.swift | 2 +- Tests/PersistentCollectionsTests/Hash.swift | 6 + .../PersistentCollections Fixtures.swift | 153 +++-- .../PersistentDictionary Smoke Tests.swift | 2 +- .../PersistentDictionary Tests.swift | 631 +++++++++--------- .../PersistentSet Tests.swift | 33 + 6 files changed, 451 insertions(+), 376 deletions(-) create mode 100644 Tests/PersistentCollectionsTests/PersistentSet Tests.swift diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index 8e519ba8..bca06458 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -875,7 +875,7 @@ class OrderedDictionaryTests: CollectionTestCase { "OrderedDictionary([0: 1, 2: 3, 4: 5])") } - func test_customReflectable() { + func test_CustomReflectable() { do { let d: OrderedDictionary = [1: 2, 3: 4, 5: 6] let mirror = Mirror(reflecting: d) diff --git a/Tests/PersistentCollectionsTests/Hash.swift b/Tests/PersistentCollectionsTests/Hash.swift index 708f4e7e..f8c2182b 100644 --- a/Tests/PersistentCollectionsTests/Hash.swift +++ b/Tests/PersistentCollectionsTests/Hash.swift @@ -35,6 +35,12 @@ extension Hash: Equatable { } } +extension Hash: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(value) + } +} + extension Hash: CustomStringConvertible { var description: String { // Print hash values in radix 32 & reversed, so that the path in the hash diff --git a/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift b/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift index 8ae57a67..713ab2af 100644 --- a/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift +++ b/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift @@ -189,13 +189,14 @@ let _fixtures: KeyValuePairs = [ ], ] -let fixtures: [RawFixture] = _fixtures.map { - RawFixture(title: $0, contents: $1) +let fixtures: [Fixture] = _fixtures.map { + Fixture(title: $0, contents: $1) } -struct RawFixture { +struct Fixture { let title: String - let hashes: [Hash] + let itemsInIterationOrder: [RawCollider] + let itemsInInsertionOrder: [RawCollider] init(title: String, contents: [String]) { self.title = title @@ -208,21 +209,24 @@ struct RawFixture { return path.uppercased() + String(repeating: "0", count: c) } - var paths: [String] = [] + var items: [(path: String, item: RawCollider)] = [] var seen: Set = [] - for item in contents { - let path: String - if let i = item.unicodeScalars.firstIndex(of: "*") { + for var path in contents { + if let i = path.unicodeScalars.firstIndex(of: "*") { // We need to extend the path of collisions with zeroes to // make sure they sort correctly. - let p = String(item.unicodeScalars.prefix(upTo: i)) - guard let count = Int(item.suffix(from: i).dropFirst(), radix: 10) - else { fatalError("Invalid item: '\(item)'") } + let p = String(path.unicodeScalars.prefix(upTo: i)) + guard let count = Int(path.suffix(from: i).dropFirst(), radix: 10) + else { fatalError("Invalid item: '\(path)'") } path = normalized(p) - paths.append(contentsOf: repeatElement(path, count: count)) + let hash = Hash(path)! + for _ in 0 ..< count { + items.append((path, RawCollider(items.count, hash))) + } } else { - path = normalized(item) - paths.append(path) + path = normalized(path) + let hash = Hash(path)! + items.append((path, RawCollider(items.count, hash))) } if !seen.insert(path).inserted { @@ -232,93 +236,116 @@ struct RawFixture { var seenPrefixes: Set = [] var collidingPrefixes: Set = [] - for p in paths { - assert(p.count == maxDepth) - for i in p.indices { - let prefix = p[.. b[j] { return false } - a.formIndex(after: &i) - b.formIndex(after: &j) + if a.path[i] < b.path[j] { return true } + if a.path[j] > b.path[j] { return false } + a.path.formIndex(after: &i) + b.path.formIndex(after: &j) } - precondition(i == a.endIndex && j == b.endIndex) + precondition(i == a.path.endIndex && j == b.path.endIndex) return false } - self.hashes = paths.map { Hash($0)! } + self.itemsInIterationOrder = items.map { $0.item } } -} -struct Fixture { - typealias Element = (key: Key, value: Value) - - let title: String - let items: [Element] - - init( - _ raw: RawFixture, - key keyGenerator: (Int, Hash) -> Key, - value valueGenerator: (Int) -> Value - ) { - self.title = raw.title - self.items = raw.hashes.enumerated().map { i, hash in - (key: keyGenerator(i, hash), value: valueGenerator(i)) - } - } + var count: Int { itemsInInsertionOrder.count } } func withEachFixture( - body: (Fixture) -> Void + body: (Fixture) -> Void ) { - for raw in fixtures { - let entry = TestContext.current.push("fixture: \(raw.title)") + for fixture in fixtures { + let entry = TestContext.current.push("fixture: \(fixture.title)") defer { TestContext.current.pop(entry) } - let fixture = Fixture( - raw, - key: { RawCollider($0, $1) }, - value: { 100 + $0 }) - body(fixture) } } - extension LifetimeTracker { + func persistentSet( + for fixture: Fixture, + with transform: (RawCollider) -> Element + ) -> ( + map: PersistentSet>, + ref: [LifetimeTracked] + ) { + let ref = fixture.itemsInIterationOrder.map { key in + self.instance(for: transform(key)) + } + let ref2 = fixture.itemsInInsertionOrder.map { key in + self.instance(for: transform(key)) + } + return (PersistentSet(ref2), ref) + } + + func persistentSet( + for fixture: Fixture + ) -> ( + map: PersistentSet>, + ref: [LifetimeTracked] + ) { + persistentSet(for: fixture) { key in key } + } + func persistentDictionary( - for fixture: Fixture + for fixture: Fixture, + keyTransform: (RawCollider) -> Key, + valueTransform: (RawCollider) -> Value ) -> ( map: PersistentDictionary, LifetimeTracked>, ref: [(key: LifetimeTracked, value: LifetimeTracked)] ) { - let ref = fixture.items.map { (key, value) in - (key: self.instance(for: key), value: self.instance(for: value)) + let ref = fixture.itemsInIterationOrder.map { item in + let key = keyTransform(item) + let value = valueTransform(item) + return (key: self.instance(for: key), value: self.instance(for: value)) } - let ref2 = fixture.items.map { (key, value) in - (key: self.instance(for: key), value: self.instance(for: value)) + let ref2 = fixture.itemsInInsertionOrder.map { item in + let key = keyTransform(item) + let value = valueTransform(item) + return (key: self.instance(for: key), value: self.instance(for: value)) } return (PersistentDictionary(uniqueKeysWithValues: ref2), ref) } + + func persistentDictionary( + for fixture: Fixture + ) -> ( + map: PersistentDictionary, LifetimeTracked>, + ref: [(key: LifetimeTracked, value: LifetimeTracked)] + ) { + persistentDictionary( + for: fixture, + keyTransform: { $0 }, + valueTransform: { $0.identity + 1000 }) + } } diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift index ce2981b5..686046d8 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary Smoke Tests.swift @@ -544,7 +544,7 @@ final class PersistentDictionarySmokeTests: CollectionTestCase { } func testIteratorEnumeratesAllIfNoCollision() { - let upperBound = 1_000_000 + let upperBound = 1_000 var map1: PersistentDictionary = [:] for index in 0..(codingKey: T) { + guard let value = codingKey.intValue else { return nil} + self.init(value) + } + } + + struct BoringDictionaryKey: Hashable, Codable { + var value: Int + + init(_ value: Int) { + self.value = value + } + } + + func test_Encodable() throws { + let d1: PersistentDictionary = [ + "one": 1, "two": 2, "three": 3] + let v1: MinimalEncoder.Value = .dictionary([ + "one": .int(1), "two": .int(2), "three": .int(3)]) + expectEqual(try MinimalEncoder.encode(d1), v1) + + let d2: PersistentDictionary = [ + 1: "one", 2: "two", 3: "three"] + let v2: MinimalEncoder.Value = .dictionary([ + "1": .string("one"), + "2": .string("two"), + "3": .string("three"), + ]) + expectEqual(try MinimalEncoder.encode(d2), v2) + + if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) { + let d3: PersistentDictionary = [ + FancyDictionaryKey(1): 10, FancyDictionaryKey(2): 20 + ] + let v3: MinimalEncoder.Value = .dictionary([ + "1": .int16(10), "2": .int16(20) + ]) + expectEqual(try MinimalEncoder.encode(d3), v3) + } + + let d4: PersistentDictionary = [ + // Note: we only have a single element to prevent ordering + // problems. + BoringDictionaryKey(42): 23 + ] + let v4: MinimalEncoder.Value = .array([ + .dictionary(["value": .int(42)]), + .uint8(23), + ]) + expectEqual(try MinimalEncoder.encode(d4), v4) + } + + func test_Decodable() throws { + typealias PD = PersistentDictionary + + let d1: PersistentDictionary = [ + "one": 1, "two": 2, "three": 3] + let v1: MinimalEncoder.Value = .dictionary([ + "one": .int(1), "two": .int(2), "three": .int(3)]) + expectEqual( + try MinimalDecoder.decode(v1, as: PD.self), + d1) + + let d2: PersistentDictionary = [ + 1: "one", 2: "two", 3: "three"] + let v2: MinimalEncoder.Value = .dictionary([ + "1": .string("one"), + "2": .string("two"), + "3": .string("three"), + ]) + expectEqual( + try MinimalDecoder.decode(v2, as: PD.self), + d2) + + if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) { + let d3: PersistentDictionary = [ + FancyDictionaryKey(1): 10, FancyDictionaryKey(2): 20 + ] + let v3: MinimalEncoder.Value = .dictionary([ + "1": .int16(10), "2": .int16(20) + ]) + expectEqual( + try MinimalDecoder.decode(v3, as: PD.self), + d3) + } + + let d4: PersistentDictionary = [ + // Note: we only have a single element to prevent ordering + // problems. + BoringDictionaryKey(42): 23 + ] + let v4: MinimalEncoder.Value = .array([ + .dictionary(["value": .int(42)]), + .uint8(23), + ]) + expectEqual( + try MinimalDecoder.decode(v4, as: PD.self), + d4) + + let v5: MinimalEncoder.Value = .dictionary([ + "This is not a number": .string("bus"), + "42": .string("train")]) + expectThrows(try MinimalDecoder.decode(v5, as: PD.self)) { + expectTrue($0 is DecodingError) + } + + if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) { + let v6: MinimalEncoder.Value = .dictionary([ + "This is not a number": .string("bus"), + "42": .string("train")]) + expectThrows( + try MinimalDecoder.decode( + v6, as: PD.self) + ) { + expectTrue($0 is DecodingError) + } + + let v7: MinimalEncoder.Value = .dictionary([ + "23": .string("bus"), + "42": .string("train")]) + let d7: PD = [ + FancyDictionaryKey(23): "bus", + FancyDictionaryKey(42): "train", + ] + expectEqual( + try MinimalDecoder.decode(v7, as: PD.self), + d7) + } + + let v8: MinimalEncoder.Value = .array([ + .int32(1), .string("bike"), .int32(2), + ]) + expectThrows(try MinimalDecoder.decode(v8, as: PD.self)) + } + + func test_CustomReflectable() { + do { + let d: PersistentDictionary = [1: 2, 3: 4, 5: 6] + let mirror = Mirror(reflecting: d) + expectEqual(mirror.displayStyle, .dictionary) + expectNil(mirror.superclassMirror) + expectTrue(mirror.children.compactMap { $0.label }.isEmpty) // No label + expectEqualElements( + mirror.children.compactMap { $0.value as? (key: Int, value: Int) }, + d.map { $0 }) + } + } + + func test_Equatable_Hashable() { + let samples: [[PersistentDictionary]] = [ + [[:], [:]], + [[1: 100], [1: 100]], + [[2: 200], [2: 200]], + [[3: 300], [3: 300]], + [[100: 1], [100: 1]], + [[1: 1], [1: 1]], + [[100: 100], [100: 100]], + [[1: 100, 2: 200], [2: 200, 1: 100]], + [[1: 100, 2: 200, 3: 300], + [1: 100, 3: 300, 2: 200], + [2: 200, 1: 100, 3: 300], + [2: 200, 3: 300, 1: 100], + [3: 300, 1: 100, 2: 200], + [3: 300, 2: 200, 1: 100]] + ] + checkHashable(equivalenceClasses: samples) + } + + func test_CustomStringConvertible() { + let a: PersistentDictionary = [:] + expectEqual(a.description, "[:]") + + let b: PersistentDictionary = [ + RawCollider(0): 1 + ] + expectEqual(b.description, "[0: 1]") + + let c: PersistentDictionary = [ + RawCollider(0): 1, + RawCollider(2): 3, + RawCollider(4): 5, + ] + expectEqual(c.description, "[0: 1, 2: 3, 4: 5]") + } + + func test_CustomDebugStringConvertible() { + let a: PersistentDictionary = [:] + expectEqual( + a.debugDescription, + "PersistentDictionary([:])") + + let b: PersistentDictionary = [0: 1] + expectEqual( + b.debugDescription, + "PersistentDictionary([0: 1])") + + let c: PersistentDictionary = [0: 1, 2: 3, 4: 5] + let cd = c.map { "\($0.key): \($0.value)"}.joined(separator: ", ") + expectEqual( + c.debugDescription, + "PersistentDictionary([\(cd)])") + } + + func test_updateValueForKey_fixtures() { withEachFixture { fixture in withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var d: PersistentDictionary, LifetimeTracked> = [:] var ref: Dictionary, LifetimeTracked> = [:] - withEvery("i", in: 0 ..< fixture.items.count) { i in + withEvery("i", in: 0 ..< fixture.count) { i in withHiddenCopies(if: isShared, of: &d) { d in - let item = fixture.items[i] - let key = tracker.instance(for: item.key) - let value = tracker.instance(for: item.value) + let item = fixture.itemsInInsertionOrder[i] + let key = tracker.instance(for: item) + let value = tracker.instance(for: 1000 + item.identity) d[key] = value ref[key] = value expectEqualDictionaries(d, ref) @@ -293,10 +531,10 @@ class PersistentDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in var d: PersistentDictionary, Empty> = [:] var ref: Dictionary, Empty> = [:] - withEvery("i", in: 0 ..< fixture.items.count) { i in + withEvery("i", in: 0 ..< fixture.count) { i in withHiddenCopies(if: isShared, of: &d) { d in - let item = fixture.items[i] - let key = tracker.instance(for: item.key) + let item = fixture.itemsInInsertionOrder[i] + let key = tracker.instance(for: item) d[key] = Empty() ref[key] = Empty() expectEqualDictionaries(d, ref) @@ -307,9 +545,9 @@ class PersistentDictionaryTests: CollectionTestCase { } } - func test_removeValueForKey_fixtures() { + func test_removeValueForKey_fixtures_justOne() { withEachFixture { fixture in - withEvery("offset", in: 0 ..< fixture.items.count) { offset in + withEvery("offset", in: 0 ..< fixture.count) { offset in withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, ref) = tracker.persistentDictionary(for: fixture) @@ -326,6 +564,27 @@ class PersistentDictionaryTests: CollectionTestCase { } } + func test_removeValueForKey_fixtures_all() { + withEachFixture { fixture in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var (d, ref) = tracker.persistentDictionary(for: fixture) + var rng = RepeatableRandomNumberGenerator(seed: 0) + withEvery("i", in: 0 ..< fixture.count) { _ in + withHiddenCopies(if: isShared, of: &d) { d in + let offset = ref.indices.randomElement(using: &rng)! + let old = d.removeValue(forKey: ref[offset].key) + d._invariantCheck() + expectEqual(old, ref[offset].value) + ref.remove(at: offset) + expectEqualDictionaries(d, ref) + } + } + } + } + } + } + func test_subscript_getter_data() { func check(count: Int, generator: G) { context.withTrace("count: \(count), generator: \(generator)") { @@ -384,7 +643,7 @@ class PersistentDictionaryTests: CollectionTestCase { func test_subscript_setter_update_fixtures() { withEachFixture { fixture in - withEvery("offset", in: 0 ..< fixture.items.count) { offset in + withEvery("offset", in: 0 ..< fixture.count) { offset in withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, ref) = tracker.persistentDictionary(for: fixture) @@ -426,7 +685,7 @@ class PersistentDictionaryTests: CollectionTestCase { func test_subscript_setter_remove_fixtures() { withEachFixture { fixture in - withEvery("offset", in: 0 ..< fixture.items.count) { offset in + withEvery("offset", in: 0 ..< fixture.count) { offset in withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, ref) = tracker.persistentDictionary(for: fixture) @@ -491,11 +750,11 @@ class PersistentDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in var d: PersistentDictionary, LifetimeTracked> = [:] var ref: Dictionary, LifetimeTracked> = [:] - withEvery("i", in: 0 ..< fixture.items.count) { i in + withEvery("i", in: 0 ..< fixture.count) { i in withHiddenCopies(if: isShared, of: &d) { d in - let item = fixture.items[i] - let key = tracker.instance(for: item.key) - let value = tracker.instance(for: item.value) + let item = fixture.itemsInInsertionOrder[i] + let key = tracker.instance(for: item) + let value = tracker.instance(for: 1000 + item.identity) d[key] = value ref[key] = value expectEqualDictionaries(d, ref) @@ -607,7 +866,7 @@ class PersistentDictionaryTests: CollectionTestCase { func test_subscript_modify_update_fixtures() { withEachFixture { fixture in - withEvery("offset", in: 0 ..< fixture.items.count) { offset in + withEvery("offset", in: 0 ..< fixture.count) { offset in withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, ref) = tracker.persistentDictionary(for: fixture) @@ -629,7 +888,7 @@ class PersistentDictionaryTests: CollectionTestCase { func test_subscript_modify_in_place() { withEachFixture { fixture in - withEvery("offset", in: 0 ..< fixture.items.count) { offset in + withEvery("offset", in: 0 ..< fixture.count) { offset in withLifetimeTracking { tracker in var (d, ref) = tracker.persistentDictionary(for: fixture) let key = ref[offset].key @@ -646,7 +905,7 @@ class PersistentDictionaryTests: CollectionTestCase { func test_subscript_modify_remove_fixtures() { withEachFixture { fixture in - withEvery("offset", in: 0 ..< fixture.items.count) { offset in + withEvery("offset", in: 0 ..< fixture.count) { offset in withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, ref) = tracker.persistentDictionary(for: fixture) @@ -721,11 +980,11 @@ class PersistentDictionaryTests: CollectionTestCase { withLifetimeTracking { tracker in var d: PersistentDictionary, LifetimeTracked> = [:] var ref: Dictionary, LifetimeTracked> = [:] - withEvery("i", in: 0 ..< fixture.items.count) { i in + withEvery("i", in: 0 ..< fixture.count) { i in withHiddenCopies(if: isShared, of: &d) { d in - let item = fixture.items[i] - let key = tracker.instance(for: item.key) - let value = tracker.instance(for: item.value) + let item = fixture.itemsInInsertionOrder[i] + let key = tracker.instance(for: item) + let value = tracker.instance(for: 1000 + item.identity) mutate(&d[key]) { v in expectNil(v) v = value @@ -825,7 +1084,7 @@ class PersistentDictionaryTests: CollectionTestCase { func test_defaulted_subscript_setter_update_fixtures() { withEachFixture { fixture in - withEvery("offset", in: 0 ..< fixture.items.count) { offset in + withEvery("offset", in: 0 ..< fixture.count) { offset in withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, ref) = tracker.persistentDictionary(for: fixture) @@ -879,11 +1138,11 @@ class PersistentDictionaryTests: CollectionTestCase { var d: PersistentDictionary, LifetimeTracked> = [:] var ref: Dictionary, LifetimeTracked> = [:] let def = tracker.instance(for: -1000) - withEvery("i", in: 0 ..< fixture.items.count) { i in + withEvery("i", in: 0 ..< fixture.count) { i in withHiddenCopies(if: isShared, of: &d) { d in - let item = fixture.items[i] - let key = tracker.instance(for: item.key) - let value = tracker.instance(for: item.value) + let item = fixture.itemsInInsertionOrder[i] + let key = tracker.instance(for: item) + let value = tracker.instance(for: 1000 + item.identity) d[key, default: def] = value ref[key] = value expectEqualDictionaries(d, ref) @@ -926,7 +1185,7 @@ class PersistentDictionaryTests: CollectionTestCase { func test_defaulted_subscript_modify_update_fixtures() { withEachFixture { fixture in - withEvery("offset", in: 0 ..< fixture.items.count) { offset in + withEvery("offset", in: 0 ..< fixture.count) { offset in withEvery("isShared", in: [false, true]) { isShared in withLifetimeTracking { tracker in var (d, ref) = tracker.persistentDictionary(for: fixture) @@ -949,7 +1208,7 @@ class PersistentDictionaryTests: CollectionTestCase { func test_defaulted_subscript_modify_in_place() { withEachFixture { fixture in - withEvery("offset", in: 0 ..< fixture.items.count) { offset in + withEvery("offset", in: 0 ..< fixture.count) { offset in withLifetimeTracking { tracker in var (d, ref) = tracker.persistentDictionary(for: fixture) let key = ref[offset].key @@ -972,7 +1231,6 @@ class PersistentDictionaryTests: CollectionTestCase { let values = tracker.instances( for: (0 ..< count).map { generator.value(for: $0) }) let def = tracker.instance(for: generator.value(for: -1000)) - print(def) var d: PersistentDictionary, LifetimeTracked> = [:] var ref: Dictionary, LifetimeTracked> = [:] withEvery("offset", in: 0 ..< count) { offset in @@ -981,6 +1239,7 @@ class PersistentDictionaryTests: CollectionTestCase { expectEqual(value, def) value = values[offset] } + d._invariantCheck() ref[keys[offset]] = values[offset] expectEqualDictionaries(d, ref) } @@ -1002,11 +1261,11 @@ class PersistentDictionaryTests: CollectionTestCase { var d: PersistentDictionary, LifetimeTracked> = [:] var ref: Dictionary, LifetimeTracked> = [:] let def = tracker.instance(for: -1) - withEvery("i", in: 0 ..< fixture.items.count) { i in + withEvery("i", in: 0 ..< fixture.count) { i in withHiddenCopies(if: isShared, of: &d) { d in - let item = fixture.items[i] - let key = tracker.instance(for: item.key) - let value = tracker.instance(for: item.value) + let item = fixture.itemsInInsertionOrder[i] + let key = tracker.instance(for: item) + let value = tracker.instance(for: 1000 + item.identity) mutate(&d[key, default: def]) { v in expectEqual(v, def) v = value @@ -1141,7 +1400,6 @@ class PersistentDictionaryTests: CollectionTestCase { typealias Value2 = LifetimeTracked withEachFixture { fixture in - print(fixture.title, fixture.items) withLifetimeTracking { tracker in func transform(_ value: Value) -> Value2? { guard value.payload.isMultiple(of: 2) else { return nil } @@ -1182,18 +1440,17 @@ class PersistentDictionaryTests: CollectionTestCase { }) } - func test_filter_fixtures() { + func test_filter_fixtures_evens() { typealias Key = LifetimeTracked typealias Value = LifetimeTracked withEachFixture { fixture in - print(fixture.title, fixture.items) withLifetimeTracking { tracker in withEvery("isShared", in: [false, true]) { isShared in var (d, ref) = tracker.persistentDictionary(for: fixture) withHiddenCopies(if: isShared, of: &d) { d in func predicate(_ item: (key: Key, value: Value)) -> Bool { - expectEqual(item.value.payload, 100 + item.key.payload.identity) + expectEqual(item.value.payload, 1000 + item.key.payload.identity) return item.value.payload.isMultiple(of: 2) } let d2 = d.filter(predicate) @@ -1206,6 +1463,31 @@ class PersistentDictionaryTests: CollectionTestCase { } } + func test_filter_fixtures_filter_one() { + typealias Key = LifetimeTracked + typealias Value = LifetimeTracked + + withEachFixture { fixture in + withLifetimeTracking { tracker in + withEvery("isShared", in: [false, true]) { isShared in + withEvery("i", in: 0 ..< fixture.count) { i in + var (d, ref) = tracker.persistentDictionary(for: fixture) + withHiddenCopies(if: isShared, of: &d) { d in + func predicate(_ item: (key: Key, value: Value)) -> Bool { + expectEqual(item.value.payload, 1000 + item.key.payload.identity) + return item.key.payload.identity == i + } + let d2 = d.filter(predicate) + let ref2 = Dictionary( + uniqueKeysWithValues: ref.filter(predicate)) + expectEqualDictionaries(d2, ref2) + } + } + } + } + } + } + // MARK: - @@ -2088,279 +2370,6 @@ class PersistentDictionaryTests: CollectionTestCase { // }) // } - func test_CustomStringConvertible() { - let a: PersistentDictionary = [:] - expectEqual(a.description, "[:]") - - let b: PersistentDictionary = [ - RawCollider(0): 1 - ] - expectEqual(b.description, "[0: 1]") - - let c: PersistentDictionary = [ - RawCollider(0): 1, - RawCollider(2): 3, - RawCollider(4): 5, - ] - expectEqual(c.description, "[0: 1, 2: 3, 4: 5]") - } - - // func test_CustomDebugStringConvertible() { - // let a: PersistentDictionary = [:] - // expectEqual(a.debugDescription, - // "PersistentDictionary([:])") - // - // let b: PersistentDictionary = [0: 1] - // expectEqual(b.debugDescription, - // "PersistentDictionary([0: 1])") - // - // let c: PersistentDictionary = [0: 1, 2: 3, 4: 5] - // expectEqual(c.debugDescription, - // "PersistentDictionary([0: 1, 2: 3, 4: 5])") - // } - - // func test_customReflectable() { - // do { - // let d: PersistentDictionary = [1: 2, 3: 4, 5: 6] - // let mirror = Mirror(reflecting: d) - // expectEqual(mirror.displayStyle, .dictionary) - // expectNil(mirror.superclassMirror) - // expectTrue(mirror.children.compactMap { $0.label }.isEmpty) // No label - // expectEqualElements( - // mirror.children.compactMap { $0.value as? (key: Int, value: Int) }, - // d.map { $0 }) - // } - // } - - func test_Equatable_Hashable() { - let samples: [[PersistentDictionary]] = [ - [[:], [:]], - [[1: 100], [1: 100]], - [[2: 200], [2: 200]], - [[3: 300], [3: 300]], - [[100: 1], [100: 1]], - [[1: 1], [1: 1]], - [[100: 100], [100: 100]], - [[1: 100, 2: 200], [2: 200, 1: 100]], - [[1: 100, 2: 200, 3: 300], - [1: 100, 3: 300, 2: 200], - [2: 200, 1: 100, 3: 300], - [2: 200, 3: 300, 1: 100], - [3: 300, 1: 100, 2: 200], - [3: 300, 2: 200, 1: 100]] - ] - checkHashable(equivalenceClasses: samples) - } - - // func test_Encodable() throws { - // let d1: PersistentDictionary = [:] - // let v1: MinimalEncoder.Value = .array([]) - // expectEqual(try MinimalEncoder.encode(d1), v1) - // - // let d2: PersistentDictionary = [0: 1] - // let v2: MinimalEncoder.Value = .array([.int(0), .int(1)]) - // expectEqual(try MinimalEncoder.encode(d2), v2) - // - // let d3: PersistentDictionary = [0: 1, 2: 3] - // let v3: MinimalEncoder.Value = - // .array([.int(0), .int(1), .int(2), .int(3)]) - // expectEqual(try MinimalEncoder.encode(d3), v3) - // - // let d4 = PersistentDictionary( - // uniqueKeys: 0 ..< 100, - // values: (0 ..< 100).map { 100 * $0 }) - // let v4: MinimalEncoder.Value = - // .array((0 ..< 100).flatMap { [.int($0), .int(100 * $0)] }) - // expectEqual(try MinimalEncoder.encode(d4), v4) - // } - - // func test_Decodable() throws { - // typealias OD = PersistentDictionary - // let d1: OD = [:] - // let v1: MinimalEncoder.Value = .array([]) - // expectEqual(try MinimalDecoder.decode(v1, as: OD.self), d1) - // - // let d2: OD = [0: 1] - // let v2: MinimalEncoder.Value = .array([.int(0), .int(1)]) - // expectEqual(try MinimalDecoder.decode(v2, as: OD.self), d2) - // - // let d3: OD = [0: 1, 2: 3] - // let v3: MinimalEncoder.Value = - // .array([.int(0), .int(1), .int(2), .int(3)]) - // expectEqual(try MinimalDecoder.decode(v3, as: OD.self), d3) - // - // let d4 = PersistentDictionary( - // uniqueKeys: 0 ..< 100, - // values: (0 ..< 100).map { 100 * $0 }) - // let v4: MinimalEncoder.Value = - // .array((0 ..< 100).flatMap { [.int($0), .int(100 * $0)] }) - // expectEqual(try MinimalDecoder.decode(v4, as: OD.self), d4) - // - // let v5: MinimalEncoder.Value = .array([.int(0), .int(1), .int(2)]) - // expectThrows(try MinimalDecoder.decode(v5, as: OD.self)) { error in - // guard case DecodingError.dataCorrupted(let context) = error else { - // expectFailure("Unexpected error \(error)") - // return - // } - // expectEqual(context.debugDescription, - // "Unkeyed container reached end before value in key-value pair") - // - // } - // - // let v6: MinimalEncoder.Value = .array([.int(0), .int(1), .int(0), .int(2)]) - // expectThrows(try MinimalDecoder.decode(v6, as: OD.self)) { error in - // guard case DecodingError.dataCorrupted(let context) = error else { - // expectFailure("Unexpected error \(error)") - // return - // } - // expectEqual(context.debugDescription, "Duplicate key at offset 2") - // } - // } - - // func test_swapAt() { - // withEvery("count", in: 0 ..< 20) { count in - // withEvery("i", in: 0 ..< count) { i in - // withEvery("j", in: 0 ..< count) { j in - // withEvery("isShared", in: [false, true]) { isShared in - // withLifetimeTracking { tracker in - // var (d, keys, values) = tracker.persistentDictionary(keys: 0 ..< count) - // keys.swapAt(i, j) - // values.swapAt(i, j) - // withHiddenCopies(if: isShared, of: &d) { d in - // d.swapAt(i, j) - // expectEqualElements(d.values, values) - // expectEqual(d[keys[i]], values[i]) - // expectEqual(d[keys[j]], values[j]) - // } - // } - // } - // } - // } - // } - // } - - // func test_partition() { - // withEvery("seed", in: 0 ..< 10) { seed in - // withEvery("count", in: 0 ..< 30) { count in - // withEvery("isShared", in: [false, true]) { isShared in - // withLifetimeTracking { tracker in - // var rng = RepeatableRandomNumberGenerator(seed: seed) - // var (d, keys, values) = tracker.persistentDictionary( - // keys: (0 ..< count).shuffled(using: &rng)) - // var items = Array(zip(keys, values)) - // let expectedPivot = items.partition { $0.0.payload < count / 2 } - // withHiddenCopies(if: isShared, of: &d) { d in - // let actualPivot = d.partition { $0.key.payload < count / 2 } - // expectEqual(actualPivot, expectedPivot) - // expectEqualElements(d, items) - // } - // } - // } - // } - // } - // } - - // func test_sort() { - // withEvery("seed", in: 0 ..< 10) { seed in - // withEvery("count", in: 0 ..< 30) { count in - // withEvery("isShared", in: [false, true]) { isShared in - // withLifetimeTracking { tracker in - // var rng = RepeatableRandomNumberGenerator(seed: seed) - // var (d, keys, values) = tracker.persistentDictionary( - // keys: (0 ..< count).shuffled(using: &rng)) - // var items = Array(zip(keys, values)) - // items.sort(by: { $0.0 < $1.0 }) - // withHiddenCopies(if: isShared, of: &d) { d in - // d.sort() - // expectEqualElements(d, items) - // } - // } - // } - // } - // } - // } - - // func test_sort_by() { - // withEvery("seed", in: 0 ..< 10) { seed in - // withEvery("count", in: 0 ..< 30) { count in - // withEvery("isShared", in: [false, true]) { isShared in - // withLifetimeTracking { tracker in - // var rng = RepeatableRandomNumberGenerator(seed: seed) - // var (d, keys, values) = tracker.persistentDictionary( - // keys: (0 ..< count).shuffled(using: &rng)) - // var items = Array(zip(keys, values)) - // items.sort(by: { $0.0 > $1.0 }) - // withHiddenCopies(if: isShared, of: &d) { d in - // d.sort(by: { $0.key > $1.key }) - // expectEqualElements(d, items) - // } - // } - // } - // } - // } - // } - - // func test_shuffle() { - // withEvery("count", in: 0 ..< 30) { count in - // withEvery("isShared", in: [false, true]) { isShared in - // withEvery("seed", in: 0 ..< 10) { seed in - // var d = PersistentDictionary( - // uniqueKeys: 0 ..< count, - // values: 100 ..< 100 + count) - // var items = (0 ..< count).map { (key: $0, value: 100 + $0) } - // withHiddenCopies(if: isShared, of: &d) { d in - // expectEqualElements(d, items) - // - // var rng1 = RepeatableRandomNumberGenerator(seed: seed) - // items.shuffle(using: &rng1) - // - // var rng2 = RepeatableRandomNumberGenerator(seed: seed) - // d.shuffle(using: &rng2) - // - // items.sort(by: { $0.key < $1.key }) - // d.sort() - // expectEqualElements(d, items) - // } - // } - // } - // if count >= 2 { - // // Check that shuffling with the system RNG does permute the elements. - // var d = PersistentDictionary( - // uniqueKeys: 0 ..< count, - // values: 100 ..< 100 + count) - // let original = d - // var success = false - // for _ in 0 ..< 1000 { - // d.shuffle() - // if !d.elementsEqual( - // original, - // by: { $0.key == $1.key && $0.value == $1.value} - // ) { - // success = true - // break - // } - // } - // expectTrue(success) - // } - // } - // } - - // func test_reverse() { - // withEvery("count", in: 0 ..< 30) { count in - // withEvery("isShared", in: [false, true]) { isShared in - // withLifetimeTracking { tracker in - // var (d, keys, values) = tracker.persistentDictionary(keys: 0 ..< count) - // var items = Array(zip(keys, values)) - // withHiddenCopies(if: isShared, of: &d) { d in - // items.reverse() - // d.reverse() - // expectEqualElements(d, items) - // } - // } - // } - // } - // } - // func test_removeAll() { // withEvery("count", in: 0 ..< 30) { count in // withEvery("isShared", in: [false, true]) { isShared in diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift new file mode 100644 index 00000000..a78c4f99 --- /dev/null +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -0,0 +1,33 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +import _CollectionsTestSupport +import PersistentCollections + +class PersistentSetTests: CollectionTestCase { + func test_init_empty() { + let set = PersistentSet() + expectEqual(set.count, 0) + expectTrue(set.isEmpty) + expectEqualElements(set, []) + } + + func test_BidirectionalCollection() { + withEachFixture { fixture in + withLifetimeTracking { tracker in + let (set, ref) = tracker.persistentSet(for: fixture) + checkBidirectionalCollection(set, expectedContents: ref, by: ==) + } + } + } + + +} From a887a77ef5c15e970c612364f38ddab0a9322edc Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 26 Sep 2022 16:37:39 -0700 Subject: [PATCH 05/18] [PersistentSet] Add tests for intersection & subtracting; fix issues --- .../Node/_Node+Builder.swift | 255 ++++++++++-------- .../Node/_Node+Structural intersection.swift | 81 +++--- .../Node/_Node+Structural subtracting.swift | 116 ++++---- .../Node/_Node+Subtree Removals.swift | 78 ++++++ ...ersistentSet+SetAlgebra intersection.swift | 6 +- ...PersistentSet+SetAlgebra subtracting.swift | 6 +- .../Colliders.swift | 2 +- Tests/PersistentCollectionsTests/Hash.swift | 2 +- .../PersistentCollections Fixtures.swift | 3 +- .../PersistentDictionary Tests.swift | 11 +- .../PersistentSet Tests.swift | 206 +++++++++++++- .../Utilities.swift | 80 ++++++ 12 files changed, 620 insertions(+), 226 deletions(-) diff --git a/Sources/PersistentCollections/Node/_Node+Builder.swift b/Sources/PersistentCollections/Node/_Node+Builder.swift index a45b3dc3..635374a7 100644 --- a/Sources/PersistentCollections/Node/_Node+Builder.swift +++ b/Sources/PersistentCollections/Node/_Node+Builder.swift @@ -13,127 +13,144 @@ extension _Node { @usableFromInline @frozen internal enum Builder { + @usableFromInline typealias Element = _Node.Element + case empty case item(Element, _Hash) case node(_Node, _Hash) - - @inlinable - internal init(_ level: _Level, _ node: _Node, _ hashPrefix: _Hash) { - if node.count == 0 { - self = .empty - } else if node.hasSingletonItem { - let item = node.read { $0[item: .zero] } - self = .item(item, hashPrefix) - } else { - self = .node(node, hashPrefix) - } - } - - @inlinable - internal func finalize(_ level: _Level) -> _Node { - assert(level.isAtRoot) - switch self { - case .empty: - return _Node(storage: _emptySingleton, count: 0) - case .item(let item, let h): - return _Node._regularNode(item, h[level]) - case .node(let node, _): - return node - } - } - - @inlinable - internal mutating func addNewCollision(_ newItem: Element, _ hash: _Hash) { - switch self { - case .empty: - self = .item(newItem, hash) - case .item(let oldItem, let h): - assert(hash == h) - let node = _Node._collisionNode(hash, oldItem, newItem) - self = .node(node, hash) - case .node(var node, let h): - self = .empty - assert(node.isCollisionNode) - assert(hash == h) - assert(hash == node.collisionHash) - _ = node.ensureUniqueAndAppendCollision(isUnique: true, newItem) - self = .node(node, h) - } - } - - @inlinable - internal mutating func addNewItem( - _ level: _Level, _ newItem: Element, _ hashPrefix: _Hash - ) { - switch self { - case .empty: - self = .item(newItem, hashPrefix) - case .item(let oldItem, let oldHash): - let bucket1 = oldHash[level] - let bucket2 = hashPrefix[level] - assert(bucket1 != bucket2) - assert(oldHash.isEqual(to: hashPrefix, upTo: level)) - let node = _Node._regularNode(oldItem, bucket1, newItem, bucket2) - self = .node(node, hashPrefix) - case .node(var node, let nodeHash): - self = .empty - assert(!node.isCollisionNode) - assert(nodeHash.isEqual(to: hashPrefix, upTo: level)) - let bucket = hashPrefix[level] - node.ensureUniqueAndInsertItem(isUnique: true, newItem, at: bucket) - self = .node(node, nodeHash) - } - } - - @inlinable - internal mutating func addNewChildBranch( - _ level: _Level, _ branch: Builder - ) { - switch (self, branch) { - case (_, .empty): - break - case (.empty, .item): - self = branch - case (.empty, .node(let child, let childHash)): - if child.isCollisionNode { - // Compression - assert(!level.isAtBottom) - self = branch - } else { - let node = _Node._regularNode(child, childHash[level]) - self = .node(node, childHash) - } - case let (.item(li, lh), .item(ri, rh)): - let node = _Node._regularNode(li, lh[level], ri, rh[level]) - self = .node(node, lh) - case let (.item(item, itemHash), .node(child, childHash)): - assert(itemHash.isEqual(to: childHash, upTo: level)) - let node = _Node._regularNode( - item, itemHash[level], - child, childHash[level]) - self = .node(node, childHash) - case (.node(var node, let nodeHash), .item(let item, let itemHash)): - if node.isCollisionNode { - // Expansion - assert(!level.isAtBottom) - node = _Node._regularNode(node, nodeHash[level]) - } - assert(!node.isCollisionNode) - assert(nodeHash.isEqual(to: itemHash, upTo: 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 { - // Expansion - assert(!level.isAtBottom) - node = _Node._regularNode(node, nodeHash[level]) - } - assert(nodeHash.isEqual(to: childHash, upTo: level)) - node.ensureUnique(isUnique: true, withFreeSpace: _Node.spaceForNewChild) - node.insertChild(child, childHash[level]) - self = .node(node, nodeHash) - } - } + } +} + +extension _Node.Builder { + @inlinable + internal init(_ level: _Level, _ node: _Node, _ hashPrefix: _Hash) { + if node.count == 0 { + self = .empty + } else if node.hasSingletonItem { + let item = node.read { $0[item: .zero] } + self = .item(item, hashPrefix) + } else { + self = .node(node, hashPrefix) + } + } + + @inlinable + internal func finalize(_ level: _Level) -> _Node { + assert(level.isAtRoot) + switch self { + case .empty: + return _Node(storage: _emptySingleton, count: 0) + case .item(let item, let h): + return _Node._regularNode(item, h[level]) + case .node(let node, _): + return node + } + } + + @inlinable + internal mutating func addNewCollision(_ newItem: Element, _ hash: _Hash) { + switch self { + case .empty: + self = .item(newItem, hash) + case .item(let oldItem, let h): + assert(hash == h) + let node = _Node._collisionNode(hash, oldItem, newItem) + self = .node(node, hash) + case .node(var node, let h): + self = .empty + assert(node.isCollisionNode) + assert(hash == h) + assert(hash == node.collisionHash) + _ = node.ensureUniqueAndAppendCollision(isUnique: true, newItem) + self = .node(node, h) + } + } + + @inlinable + internal mutating func addNewItem( + _ level: _Level, _ newItem: Element, _ hashPrefix: _Hash + ) { + switch self { + case .empty: + self = .item(newItem, hashPrefix) + case .item(let oldItem, let oldHash): + let bucket1 = oldHash[level] + let bucket2 = hashPrefix[level] + assert(bucket1 != bucket2) + assert(oldHash.isEqual(to: hashPrefix, upTo: level)) + let node = _Node._regularNode(oldItem, bucket1, newItem, bucket2) + self = .node(node, hashPrefix) + case .node(var node, let nodeHash): + self = .empty + if node.isCollisionNode { + // Expansion + assert(!level.isAtBottom) + node = _Node._regularNode(node, nodeHash[level]) + } + assert(nodeHash.isEqual(to: hashPrefix, upTo: level)) + let bucket = hashPrefix[level] + node.ensureUniqueAndInsertItem(isUnique: true, newItem, at: bucket) + self = .node(node, nodeHash) + } + } + + @inlinable + internal mutating func addNewChildBranch( + _ level: _Level, _ branch: Self + ) { + switch (self, branch) { + case (_, .empty): + break + case (.empty, .item): + self = branch + case (.empty, .node(let child, let childHash)): + if child.isCollisionNode { + // Compression + assert(!level.isAtBottom) + self = branch + } else { + let node = _Node._regularNode(child, childHash[level]) + self = .node(node, childHash) + } + case let (.item(li, lh), .item(ri, rh)): + let node = _Node._regularNode(li, lh[level], ri, rh[level]) + self = .node(node, lh) + case let (.item(item, itemHash), .node(child, childHash)): + assert(itemHash.isEqual(to: childHash, upTo: level)) + let node = _Node._regularNode( + item, itemHash[level], + child, childHash[level]) + self = .node(node, childHash) + case (.node(var node, let nodeHash), .item(let item, let itemHash)): + if node.isCollisionNode { + // Expansion + assert(!level.isAtBottom) + node = _Node._regularNode(node, nodeHash[level]) + } + assert(!node.isCollisionNode) + assert(nodeHash.isEqual(to: itemHash, upTo: 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 { + // Expansion + assert(!level.isAtBottom) + node = _Node._regularNode(node, nodeHash[level]) + } + assert(nodeHash.isEqual(to: childHash, upTo: level)) + node.ensureUnique(isUnique: true, withFreeSpace: _Node.spaceForNewChild) + node.insertChild(child, childHash[level]) + self = .node(node, nodeHash) + } + } + + @inlinable + internal static func childBranch( + _ level: _Level, _ branch: Self + ) -> Self { + var result: Self = .empty + result.addNewChildBranch(level, branch) + return result } } diff --git a/Sources/PersistentCollections/Node/_Node+Structural intersection.swift b/Sources/PersistentCollections/Node/_Node+Structural intersection.swift index 6cd331d9..4dd1e4a3 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural intersection.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural intersection.swift @@ -26,49 +26,47 @@ extension _Node { return self.read { l in other.read { r in var result: Builder = .empty - for (bucket, _) in l.itemMap.intersection(r.itemMap) { - let lslot = l.itemMap.slot(of: bucket) - let rslot = r.itemMap.slot(of: bucket) - let lp = l.itemPtr(at: lslot) - if lp.pointee.key == r[item: rslot].key { - let hashPrefix = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, lp.pointee, hashPrefix) + for (bucket, lslot) in l.itemMap { + if r.itemMap.contains(bucket) { + let rslot = r.itemMap.slot(of: bucket) + let lp = l.itemPtr(at: lslot) + if lp.pointee.key == r[item: rslot].key { + let hashPrefix = hashPrefix.appending(bucket, at: level) + result.addNewItem(level, lp.pointee, hashPrefix) + } } - } - - for (bucket, _) in l.itemMap.intersection(r.childMap) { - let lslot = l.itemMap.slot(of: bucket) - let rslot = r.childMap.slot(of: bucket) - 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) - } - } - - for (bucket, _) in l.childMap.intersection(r.itemMap) { - let lslot = l.childMap.slot(of: bucket) - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) - let h = _Hash(rp.pointee.key) - let res = l[child: lslot].lookup(level.descend(), rp.pointee.key, h) - if let res = res { - UnsafeHandle.read(res.node) { - let p = $0.itemPtr(at: res.slot) - result.addNewItem(level, p.pointee, h) + else if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + 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) } } } - for (bucket, _) in l.childMap.intersection(r.childMap) { - let lslot = l.childMap.slot(of: bucket) - let rslot = r.childMap.slot(of: bucket) - let branch = l[child: lslot].intersection( - level.descend(), - hashPrefix.appending(bucket, at: level), - r[child: rslot]) - result.addNewChildBranch(level, branch) + 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 res = l[child: lslot].lookup(level.descend(), rp.pointee.key, h) + if let res = res { + UnsafeHandle.read(res.node) { + let p = $0.itemPtr(at: res.slot) + result.addNewItem(level, p.pointee, h) + } + } + } + else if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + let branch = l[child: lslot].intersection( + level.descend(), + hashPrefix.appending(bucket, at: level), + r[child: rslot]) + result.addNewChildBranch(level, branch) + } } return result } @@ -143,11 +141,12 @@ extension _Node { return .item(litem.pointee, r.collisionHash) } if l.childMap.contains(bucket) { - let lslot = l.itemMap.slot(of: bucket) - return intersection( + let lslot = l.childMap.slot(of: bucket) + let branch = l[child: lslot].intersection( level.descend(), hashPrefix.appending(bucket, at: level), - l[child: lslot]) + other) + return .childBranch(level, branch) } return .empty } diff --git a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift index b655d737..f7c7de01 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift @@ -26,48 +26,53 @@ extension _Node { return self.read { l in other.read { r in var result: Builder = .empty - for (bucket, _) in l.itemMap.intersection(r.itemMap) { - let lslot = l.itemMap.slot(of: bucket) - let rslot = r.itemMap.slot(of: bucket) + for (bucket, lslot) in l.itemMap { let lp = l.itemPtr(at: lslot) - if lp.pointee.key != r[item: rslot].key { - let hashPrefix = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, lp.pointee, hashPrefix) + if r.itemMap.contains(bucket) { + let rslot = r.itemMap.slot(of: bucket) + if lp.pointee.key != r[item: rslot].key { + let hashPrefix = hashPrefix.appending(bucket, at: level) + result.addNewItem(level, lp.pointee, hashPrefix) + } + } + else if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + let h = _Hash(lp.pointee.key) + if !r[child: rslot].containsKey(level.descend(), lp.pointee.key, h) { + result.addNewItem(level, lp.pointee, h) + } + } + else { + let hp = hashPrefix.appending(bucket, at: level) + result.addNewItem(level, lp.pointee, hp) } } - for (bucket, _) in l.itemMap.intersection(r.childMap) { - let lslot = l.itemMap.slot(of: bucket) - let rslot = r.childMap.slot(of: bucket) - let lp = l.itemPtr(at: lslot) - let h = _Hash(lp.pointee.key) - if !r[child: rslot].containsKey(level.descend(), lp.pointee.key, h) { - result.addNewItem(level, lp.pointee, h) + 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 node = ( + l[child: lslot] + .removing(level.descend(), rp.pointee.key, h)?.replacement + ?? l[child: lslot]) + let branch = Builder( + level.descend(), node, hashPrefix.appending(bucket, at: level)) + result.addNewChildBranch(level, branch) + } + else if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + let branch = l[child: lslot].subtracting( + level.descend(), + hashPrefix.appending(bucket, at: level), + r[child: rslot]) + result.addNewChildBranch(level, branch) + } + else { + let hp = hashPrefix.appending(bucket, at: level) + result.addNewChildBranch(level, .node(l[child: lslot], hp)) } - } - - for (bucket, _) in l.childMap.intersection(r.itemMap) { - let lslot = l.childMap.slot(of: bucket) - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) - let h = _Hash(rp.pointee.key) - let node = ( - l[child: lslot] - .removing(level.descend(), rp.pointee.key, h)?.replacement - ?? l[child: lslot]) - let branch = Builder( - level.descend(), node, hashPrefix.appending(bucket, at: level)) - result.addNewChildBranch(level, branch) - } - - for (bucket, _) in l.childMap.intersection(r.childMap) { - let lslot = l.childMap.slot(of: bucket) - let rslot = r.childMap.slot(of: bucket) - let branch = l[child: lslot].subtracting( - level.descend(), - hashPrefix.appending(bucket, at: level), - r[child: rslot]) - result.addNewChildBranch(level, branch) } return result } @@ -85,7 +90,9 @@ extension _Node { if lc && rc { return read { l in other.read { r in - guard l.collisionHash == r.collisionHash else { return .empty } + guard l.collisionHash == r.collisionHash else { + return .node(self, l.collisionHash) + } var result: Builder = .empty let litems = l.reverseItems let ritems = r.reverseItems @@ -111,23 +118,21 @@ extension _Node { if r.itemMap.contains(bucket) { let rslot = r.itemMap.slot(of: bucket) let ritem = r.itemPtr(at: rslot) - let res = l.find(level, ritem.pointee.key, _Hash(ritem.pointee.key)) + let h = _Hash(ritem.pointee.key) + let res = l.find(level, ritem.pointee.key, h) guard let res = res else { return .node(self, l.collisionHash) } - assert(!res.descend) - var node = self.copy() - node.removeItem(at: res.slot, .invalid) { - _ = $0.deinitialize(count: 1) - } - return Builder(level, node, l.collisionHash) + return self._removingItemFromLeaf( + level, hashPrefix, bucket, res.slot + ).replacement } else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) let h = hashPrefix.appending(bucket, at: level) - return subtracting(level.descend(), h, r[child: rslot]) + return self.subtracting(level.descend(), h, r[child: rslot]) } - return .empty + return .node(self, l.collisionHash) } } } @@ -142,17 +147,22 @@ extension _Node { let litem = l.itemPtr(at: lslot) let h = _Hash(litem.pointee.key) let res = r.find(level, litem.pointee.key, h) - if res != nil { return .empty } - return .item(litem.pointee, h) + if res == nil { return .node(self, hashPrefix) } + return self._removingItemFromLeaf( + level, hashPrefix, bucket, lslot + ).replacement } if l.childMap.contains(bucket) { - let lslot = l.itemMap.slot(of: bucket) - return subtracting( + let lslot = l.childMap.slot(of: bucket) + let branch = l[child: lslot].subtracting( level.descend(), hashPrefix.appending(bucket, at: level), - l[child: lslot]) + other) + var result = self._removingChild(level, hashPrefix, bucket, lslot) + result.addNewChildBranch(level, branch) + return result } - return .empty + return .node(self, hashPrefix) } } } diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift index e7e73ac7..b1e91213 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift @@ -64,6 +64,24 @@ extension _Node { level, r.slot, hash[level], r2.replacement), r2.old) } + + @inlinable + internal func removing( + _ level: _Level, + _ hashPrefix: _Hash, + _ key: Key, + _ hash: _Hash + ) -> (replacement: Builder, old: Element)? { + assert(hashPrefix.isEqual(to: hash, upTo: level)) + guard let r = find(level, key, hash) else { return nil } + guard r.descend else { + return _removingItemFromLeaf(level, hashPrefix, hash[level], r.slot) + } + let hp = hashPrefix.appending(hash[level], at: level) + let r2 = read { $0[child: r.slot].removing(level.descend(), hp, key, hash) } + guard let r2 = r2 else { return nil } + return (.childBranch(level, r2.replacement), r2.old) + } } extension _Node { @@ -157,6 +175,66 @@ extension _Node { node._invariantCheck() return (node, old) } + + @inlinable + internal func _removingItemFromLeaf( + _ level: _Level, _ hashPrefix: _Hash, _ bucket: _Bucket, _ slot: _Slot + ) -> (replacement: Builder, old: Element) { + read { + assert($0.isCollisionNode || $0.itemMap.contains(bucket)) + let willAtrophy = ( + $0.itemCount == 1 + && $0.childCount == 1 + && $0[child: .zero].isCollisionNode) + if willAtrophy { + let child = $0[child: .zero] + let old = $0[item: .zero] + return (.node(child, child.collisionHash), old) + } + let willEvaporate = ($0.itemCount == 2 && $0.childCount == 0) + if willEvaporate { + let remainder = $0[item: _Slot(1 &- slot.value)] + let old = $0[item: slot] + return (.item(remainder, hashPrefix), old) + } + var node = self.copy() + let old = node.removeItem(at: slot, bucket) { $0.move() } + node._invariantCheck() + return (.node(node, hashPrefix), old) + } + } +} + +extension _Node { + @inlinable + internal func _removingChild( + _ level: _Level, _ hashPrefix: _Hash, _ bucket: _Bucket, _ slot: _Slot + ) -> Builder { + read { + assert(!$0.isCollisionNode && $0.childMap.contains(bucket)) + let willAtrophy = ( + $0.itemCount == 0 + && $0.childCount == 2 + && $0[child: _Slot(1 &- slot.value)].isCollisionNode + ) + if willAtrophy { + let child = $0[child: _Slot(1 &- slot.value)] + return .node(child, child.collisionHash) + } + let willTurnIntoItem = ($0.itemCount == 1 && $0.childCount == 1) + if willTurnIntoItem { + return .item($0[item: .zero], hashPrefix) + } + let willEvaporate = ($0.itemCount == 0 && $0.childCount == 1) + if willEvaporate { + return .empty + } + var node = self.copy() + _ = node.removeChild(at: slot, bucket) + node._invariantCheck() + return .node(node, hashPrefix) + } + } } extension _Node { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift index fced90a1..6cfbbe44 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift @@ -12,7 +12,9 @@ extension PersistentSet { @inlinable public func intersection(_ other: Self) -> Self { - let result = _root.intersection(.top, .emptyPrefix, other._root) - return Self(_new: result.finalize(.top)) + let builder = _root.intersection(.top, .emptyPrefix, other._root) + let root = builder.finalize(.top) + root._fullInvariantCheck(.top, .emptyPrefix) + return Self(_new: root) } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift index a0caadb7..b42fd5eb 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift @@ -12,7 +12,9 @@ extension PersistentSet { @inlinable public __consuming func subtracting(_ other: Self) -> Self { - let result = _root.subtracting(.top, .emptyPrefix, other._root) - return Self(_new: result.finalize(.top)) + let builder = _root.subtracting(.top, .emptyPrefix, other._root) + let root = builder.finalize(.top) + root._fullInvariantCheck(.top, .emptyPrefix) + return Self(_new: root) } } diff --git a/Tests/PersistentCollectionsTests/Colliders.swift b/Tests/PersistentCollectionsTests/Colliders.swift index ea09792f..fded9dde 100644 --- a/Tests/PersistentCollectionsTests/Colliders.swift +++ b/Tests/PersistentCollectionsTests/Colliders.swift @@ -97,6 +97,6 @@ struct RawCollider: } var debugDescription: String { - "\(identity)-#\(hash)" + "\(identity)#\(hash)" } } diff --git a/Tests/PersistentCollectionsTests/Hash.swift b/Tests/PersistentCollectionsTests/Hash.swift index f8c2182b..cab0e252 100644 --- a/Tests/PersistentCollectionsTests/Hash.swift +++ b/Tests/PersistentCollectionsTests/Hash.swift @@ -54,7 +54,7 @@ extension Hash: CustomStringConvertible { let path = String(repeating: "0", count: Swift.max(0, c - p.count)) + p return String(path.reversed()) #else - return p + return String(p.reversed()) #endif } } diff --git a/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift b/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift index 713ab2af..66ee863e 100644 --- a/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift +++ b/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift @@ -280,10 +280,11 @@ struct Fixture { } func withEachFixture( + _ label: String = "fixture", body: (Fixture) -> Void ) { for fixture in fixtures { - let entry = TestContext.current.push("fixture: \(fixture.title)") + let entry = TestContext.current.push("\(label): \(fixture.title)") defer { TestContext.current.pop(entry) } body(fixture) diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift index eac40e74..8a3279fc 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift @@ -473,14 +473,14 @@ class PersistentDictionaryTests: CollectionTestCase { let b: PersistentDictionary = [ RawCollider(0): 1 ] - expectEqual(b.description, "[0: 1]") + expectEqual(b.description, "[0#0: 1]") let c: PersistentDictionary = [ RawCollider(0): 1, RawCollider(2): 3, RawCollider(4): 5, ] - expectEqual(c.description, "[0: 1, 2: 3, 4: 5]") + expectEqual(c.description, "[0#0: 1, 2#2: 3, 4#4: 5]") } func test_CustomDebugStringConvertible() { @@ -511,10 +511,11 @@ class PersistentDictionaryTests: CollectionTestCase { withEvery("i", in: 0 ..< fixture.count) { i in withHiddenCopies(if: isShared, of: &d) { d in let item = fixture.itemsInInsertionOrder[i] - let key = tracker.instance(for: item) + let key1 = tracker.instance(for: item) + let key2 = tracker.instance(for: item) let value = tracker.instance(for: 1000 + item.identity) - d[key] = value - ref[key] = value + d[key1] = value + ref[key2] = value expectEqualDictionaries(d, ref) } } diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index a78c4f99..4ea2627d 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -20,7 +20,7 @@ class PersistentSetTests: CollectionTestCase { expectEqualElements(set, []) } - func test_BidirectionalCollection() { + func test_BidirectionalCollection_fixtures() { withEachFixture { fixture in withLifetimeTracking { tracker in let (set, ref) = tracker.persistentSet(for: fixture) @@ -29,5 +29,209 @@ class PersistentSetTests: CollectionTestCase { } } + func test_BidirectionalCollection_random100() { + let s = PersistentSet(0 ..< 100) + checkBidirectionalCollection(s, expectedContents: Array(s)) + } + func test_basics() { + var set: PersistentSet> = [] + + let a1 = HashableBox(1) + let a2 = HashableBox(1) + + var r = set.insert(a1) + expectTrue(r.inserted) + expectIdentical(r.memberAfterInsert, a1) + expectIdentical(set.first, a1) + expectTrue(set.contains(a1)) + expectTrue(set.contains(a2)) + + r = set.insert(a2) + expectFalse(r.inserted) + expectIdentical(r.memberAfterInsert, a1) + expectIdentical(set.first, a1) + expectTrue(set.contains(a1)) + expectTrue(set.contains(a2)) + + var old = set.update(with: a2) + expectIdentical(old, a1) + expectIdentical(set.first, a2) + expectTrue(set.contains(a1)) + expectTrue(set.contains(a2)) + + old = set.remove(a1) + expectIdentical(old, a2) + expectNil(set.first) + expectFalse(set.contains(a1)) + expectFalse(set.contains(a2)) + + old = set.update(with: a1) + expectNil(old) + expectIdentical(set.first, a1) + expectTrue(set.contains(a1)) + expectTrue(set.contains(a2)) + } + + func test_insert_fixtures() { + withEachFixture { fixture in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var s: PersistentSet> = [] + var ref: Set> = [] + withEvery("i", in: 0 ..< fixture.count) { i in + withHiddenCopies(if: isShared, of: &s) { s in + let item = fixture.itemsInInsertionOrder[i] + let key1 = tracker.instance(for: item) + let r = s.insert(key1) + expectTrue(r.inserted) + expectEqual(r.memberAfterInsert, key1) + + let key2 = tracker.instance(for: item) + ref.insert(key2) + expectEqualSets(s, ref) + } + } + } + } + } + } + + func test_intersection_Self_basics() { + let a = RawCollider(1, "A") + let b = RawCollider(2, "B") + let c = RawCollider(3, "C") + + let s0: PersistentSet = [] + let s1: PersistentSet = [a, b] + let s2: PersistentSet = [a, c] + + expectEqualSets(s0.intersection(s0), []) + expectEqualSets(s1.intersection(s0), []) + expectEqualSets(s0.intersection(s1), []) + + expectEqualSets(s1.intersection(s1), [a, b]) + expectEqualSets(s1.intersection(s2), [a]) + expectEqualSets(s2.intersection(s1), [a]) + + let ab = RawCollider(4, "AB") + let ac = RawCollider(5, "AC") + let s3: PersistentSet = [ab, ac] + let s4: PersistentSet = [a, ab] + expectEqualSets(s1.intersection(s3), []) + expectEqualSets(s2.intersection(s3), []) + expectEqualSets(s1.intersection(s4), [a]) + expectEqualSets(s2.intersection(s4), [a]) + expectEqualSets(s3.intersection(s1), []) + expectEqualSets(s3.intersection(s2), []) + expectEqualSets(s4.intersection(s1), [a]) + expectEqualSets(s4.intersection(s2), [a]) + + let ad = RawCollider(6, "AD") + let ae = RawCollider(7, "AE") + let s5: PersistentSet = [a, ab, ad, ae] + expectEqualSets(s1.intersection(s5), [a]) + expectEqualSets(s2.intersection(s5), [a]) + expectEqualSets(s3.intersection(s5), [ab]) + expectEqualSets(s4.intersection(s5), [a, ab]) + + expectEqualSets(s5.intersection(s1), [a]) + expectEqualSets(s5.intersection(s2), [a]) + expectEqualSets(s5.intersection(s3), [ab]) + expectEqualSets(s5.intersection(s4), [a, ab]) + + let af1 = RawCollider(8, "AF") + let af2 = RawCollider(9, "AF") + let s6: PersistentSet = [af1, af2] + expectEqualSets(s1.intersection(s6), []) + expectEqualSets(s2.intersection(s6), []) + expectEqualSets(s3.intersection(s6), []) + expectEqualSets(s4.intersection(s6), []) + expectEqualSets(s5.intersection(s6), []) + + expectEqualSets(s6.intersection(s1), []) + expectEqualSets(s6.intersection(s2), []) + expectEqualSets(s6.intersection(s3), []) + expectEqualSets(s6.intersection(s4), []) + expectEqualSets(s6.intersection(s5), []) + + let af3 = RawCollider(10, "AF") + let s7: PersistentSet = [af1, af3] + expectEqualSets(s1.intersection(s7), []) + expectEqualSets(s2.intersection(s7), []) + expectEqualSets(s3.intersection(s7), []) + expectEqualSets(s4.intersection(s7), []) + expectEqualSets(s5.intersection(s7), []) + expectEqualSets(s6.intersection(s7), [af1]) + + expectEqualSets(s7.intersection(s1), []) + expectEqualSets(s7.intersection(s2), []) + expectEqualSets(s7.intersection(s3), []) + expectEqualSets(s7.intersection(s4), []) + expectEqualSets(s7.intersection(s5), []) + expectEqualSets(s7.intersection(s6), [af1]) + + let s8: PersistentSet = [a, af1] + expectEqualSets(s1.intersection(s8), [a]) + expectEqualSets(s2.intersection(s8), [a]) + expectEqualSets(s3.intersection(s8), []) + expectEqualSets(s4.intersection(s8), [a]) + expectEqualSets(s5.intersection(s8), [a]) + expectEqualSets(s6.intersection(s8), [af1]) + expectEqualSets(s7.intersection(s8), [af1]) + + expectEqualSets(s8.intersection(s1), [a]) + expectEqualSets(s8.intersection(s2), [a]) + expectEqualSets(s8.intersection(s3), []) + expectEqualSets(s8.intersection(s4), [a]) + expectEqualSets(s8.intersection(s5), [a]) + expectEqualSets(s8.intersection(s6), [af1]) + expectEqualSets(s8.intersection(s7), [af1]) + + let afa1 = RawCollider(11, "AFA") + let afa2 = RawCollider(12, "AFA") + let s9: PersistentSet = [afa1, afa2] + expectEqualSets(s9.intersection(s6), []) + expectEqualSets(s6.intersection(s9), []) + } + + /// A set of items whose subsets will produce a bunch of interesting test + /// cases. + /// + /// Note: Try to keep this short. Every new item added here will double + /// testing costs. + let testItems = [ + RawCollider(1, "A"), + RawCollider(2, "ACA"), + RawCollider(3, "ACB"), + RawCollider(4, "ACAD"), + RawCollider(5, "ACAD"), + RawCollider(6, "ACADB"), + RawCollider(7, "ACADB"), + RawCollider(8, "ACADB"), + ] + + func test_intersection_Self_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentSet(a) + let u = Set(a) + withEverySubset("b", of: testItems) { b in + let y = PersistentSet(b) + let v = Set(b) + expectEqualSets(x.intersection(y), u.intersection(v)) + } + } + } + + func test_subtracting_Self_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentSet(a) + let u = Set(a) + withEverySubset("b", of: testItems) { b in + let y = PersistentSet(b) + let v = Set(b) + expectEqualSets(x.subtracting(y), u.subtracting(v)) + } + } + } } diff --git a/Tests/PersistentCollectionsTests/Utilities.swift b/Tests/PersistentCollectionsTests/Utilities.swift index 496b3131..676e1d3b 100644 --- a/Tests/PersistentCollectionsTests/Utilities.swift +++ b/Tests/PersistentCollectionsTests/Utilities.swift @@ -129,6 +129,59 @@ func _expectFailure( file: file, line: line) } +func expectEqualSets( + _ set: PersistentSet, + _ ref: [Element], + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #file, + line: UInt = #line +) { + expectEqualSets( + set, Set(ref), + message(), + trapping: trapping, + file: file, line: line) +} + +func expectEqualSets( + _ set: PersistentSet, + _ ref: Set, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #file, + line: UInt = #line +) { + var ref = ref + var seen: Set = [] + var extras: [Element] = [] + var dupes: [Element: Int] = [:] + for item in set { + if !seen.insert(item).inserted { + dupes[item, default: 1] += 1 + } else if ref.remove(item) == nil { + extras.append(item) + } + } + let missing = Array(ref) + var msg = "" + if !extras.isEmpty { + msg += "\nUnexpected items: \(extras)" + } + if !missing.isEmpty { + msg += "\nMissing items: \(missing)" + } + if !dupes.isEmpty { + msg += "\nDuplicate items: \(dupes)" + } + if !msg.isEmpty { + _expectFailure( + "\n\(msg)", + message, trapping: trapping, file: file, line: line) + } +} + + func expectEqualDictionaries( _ map: PersistentDictionary, _ ref: [(key: Key, value: Value)], @@ -188,3 +241,30 @@ func mutate( ) rethrows -> R { try body(&value) } + +func withEverySubset( + _ label: String, + of items: C, + body: ([C.Element]) -> Void +) { + var set: [C.Element] = [] + _withEverySubset(label, of: items, extending: &set, body: body) +} + +func _withEverySubset( + _ label: String, + of items: C, + extending set: inout [C.Element], + body: ([C.Element]) -> Void +) { + guard let item = items.first else { + let entry = TestContext.current.push("\(label): \(set)") + defer { TestContext.current.pop(entry) } + body(set) + return + } + _withEverySubset(label, of: items.dropFirst(), extending: &set, body: body) + set.append(item) + _withEverySubset(label, of: items.dropFirst(), extending: &set, body: body) + set.removeLast() +} From 03a4791766c87b1c7bc879adaedd90e2e861b6cf Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 26 Sep 2022 17:11:45 -0700 Subject: [PATCH 06/18] [PersistentSet] Add tests for set predicates; fix issues --- .../Node/_Node+Structural isDisjoint.swift | 9 +- .../Node/_Node+Structural isEqual.swift | 2 +- .../Node/_Node+Structural isSubset.swift | 14 ++- .../Colliders.swift | 6 +- .../PersistentSet Tests.swift | 88 +++++++++++++++++++ 5 files changed, 107 insertions(+), 12 deletions(-) diff --git a/Sources/PersistentCollections/Node/_Node+Structural isDisjoint.swift b/Sources/PersistentCollections/Node/_Node+Structural isDisjoint.swift index eee101b0..80eb8ecf 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural isDisjoint.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural isDisjoint.swift @@ -17,13 +17,14 @@ extension _Node { _ level: _Level, with other: _Node ) -> Bool { - if self.raw.storage === other.raw.storage { return count == 0 } + if self.count == 0 || other.count == 0 { return true } + if self.raw.storage === other.raw.storage { return false } if self.isCollisionNode { return _isDisjointCollision(level, with: other) } if other.isCollisionNode { - return other._isDisjointCollision(level, with: other) + return other._isDisjointCollision(level, with: self) } return self.read { l in @@ -96,8 +97,8 @@ extension _Node { return isDisjoint(level.descend(), with: r[child: slot]) } if r.itemMap.contains(bucket) { - let slot = r.itemMap.slot(of: bucket) - let p = r.itemPtr(at: slot) + let rslot = r.itemMap.slot(of: bucket) + let p = r.itemPtr(at: rslot) let hash = _Hash(p.pointee.key) return read { l in guard hash == l.collisionHash else { return true } diff --git a/Sources/PersistentCollections/Node/_Node+Structural isEqual.swift b/Sources/PersistentCollections/Node/_Node+Structural isEqual.swift index 8a2e1e3d..c45a8899 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural isEqual.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural isEqual.swift @@ -27,7 +27,7 @@ extension _Node { guard lhs.collisionHash == rhs.collisionHash else { return false } let l = lhs.reverseItems let r = rhs.reverseItems - guard l.count == r.count else { return false } + assert(l.count == r.count) // Already checked above for i in l.indices { let found = r.contains { l[i].key == $0.key && areEquivalent(l[i].value, $0.value) diff --git a/Sources/PersistentCollections/Node/_Node+Structural isSubset.swift b/Sources/PersistentCollections/Node/_Node+Structural isSubset.swift index de3f3d57..261f9cf0 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural isSubset.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural isSubset.swift @@ -17,6 +17,7 @@ extension _Node { _ level: _Level, of other: _Node ) -> Bool { + guard self.count > 0 else { return true } if self.raw.storage === other.raw.storage { return true } guard self.count <= other.count else { return false } @@ -42,8 +43,17 @@ extension _Node { return self.isSubset(level.descend(), of: $0[child: slot]) } } - - guard !other.isCollisionNode else { return false } + if other.isCollisionNode { + return read { l in + guard level.isAtRoot, l.hasSingletonItem else { return false } + // Annoying special case: the root node may contain a single item + // that matches one in the collision node. + return other.read { r in + let hash = _Hash(l[item: .zero].key) + return r.find(level, l[item: .zero].key, hash) != nil + } + } + } return self.read { l in other.read { r in diff --git a/Tests/PersistentCollectionsTests/Colliders.swift b/Tests/PersistentCollectionsTests/Colliders.swift index fded9dde..9b8b5f5d 100644 --- a/Tests/PersistentCollectionsTests/Colliders.swift +++ b/Tests/PersistentCollectionsTests/Colliders.swift @@ -54,7 +54,7 @@ struct Collider: /// A type with precisely controlled hash values. This can be used to set up /// hash tables with fully deterministic contents. struct RawCollider: - Hashable, CustomStringConvertible, CustomDebugStringConvertible + Hashable, CustomStringConvertible { var identity: Int var hash: Hash @@ -93,10 +93,6 @@ struct RawCollider: } var description: String { - return "\(identity)" - } - - var debugDescription: String { "\(identity)#\(hash)" } } diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index 4ea2627d..a09caf6d 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -211,6 +211,84 @@ class PersistentSetTests: CollectionTestCase { RawCollider(8, "ACADB"), ] + func test_isEqual_Self_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentSet(a) + let u = Set(a) + expectTrue(x.isEqual(to: x)) + withEverySubset("b", of: testItems) { b in + let y = PersistentSet(b) + let v = Set(b) + expectEqual(x.isEqual(to: y), u == v) + } + } + } + + func test_isSubset_Self_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentSet(a) + let u = Set(a) + expectTrue(x.isSubset(of: x)) + withEverySubset("b", of: testItems) { b in + let y = PersistentSet(b) + let v = Set(b) + expectEqual(x.isSubset(of: y), u.isSubset(of: v)) + } + } + } + + func test_isSuperset_Self_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentSet(a) + let u = Set(a) + expectTrue(x.isSuperset(of: x)) + withEverySubset("b", of: testItems) { b in + let y = PersistentSet(b) + let v = Set(b) + expectEqual(x.isSuperset(of: y), u.isSuperset(of: v)) + } + } + } + + func test_isStrictsubset_Self_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentSet(a) + let u = Set(a) + expectFalse(x.isStrictSubset(of: x)) + withEverySubset("b", of: testItems) { b in + let y = PersistentSet(b) + let v = Set(b) + expectEqual(x.isStrictSubset(of: y), u.isStrictSubset(of: v)) + } + } + } + + func test_isStrictSuperset_Self_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentSet(a) + let u = Set(a) + expectFalse(x.isStrictSuperset(of: x)) + withEverySubset("b", of: testItems) { b in + let y = PersistentSet(b) + let v = Set(b) + expectEqual(x.isStrictSuperset(of: y), u.isStrictSuperset(of: v)) + } + } + } + + func test_isDisjoint_Self_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentSet(a) + let u = Set(a) + expectEqual(x.isDisjoint(with: x), x.isEmpty) + withEverySubset("b", of: testItems) { b in + let y = PersistentSet(b) + let v = Set(b) + expectEqual(x.isDisjoint(with: y), u.isDisjoint(with: v)) + } + } + } + func test_intersection_Self_exhaustive() { withEverySubset("a", of: testItems) { a in let x = PersistentSet(a) @@ -234,4 +312,14 @@ class PersistentSetTests: CollectionTestCase { } } } + + func test_filter_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentSet(a) + withEverySubset("b", of: a) { b in + let v = Set(b) + expectEqualSets(x.filter { v.contains($0) }, v) + } + } + } } From c7906d924e4f56878eb37825a6f2e2e77f0a292b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 27 Sep 2022 14:15:20 -0700 Subject: [PATCH 07/18] [PersistentSet] intersect, subtracting, filter: Preserve structure when possible --- .../PersistentCollections/Node/_Node+Builder.swift | 14 ++++++++++++++ .../Node/_Node+Structural filter.swift | 14 ++++++++++++-- .../Node/_Node+Structural intersection.swift | 6 +++++- .../Node/_Node+Structural subtracting.swift | 11 ++++++++++- 4 files changed, 41 insertions(+), 4 deletions(-) diff --git a/Sources/PersistentCollections/Node/_Node+Builder.swift b/Sources/PersistentCollections/Node/_Node+Builder.swift index 635374a7..e3449e86 100644 --- a/Sources/PersistentCollections/Node/_Node+Builder.swift +++ b/Sources/PersistentCollections/Node/_Node+Builder.swift @@ -21,6 +21,20 @@ extension _Node { } } +extension _Node.Builder { + @inlinable + internal var count: Int { + switch self { + case .empty: + return 0 + case .item: + return 1 + case .node(let node, _): + return node.count + } + } +} + extension _Node.Builder { @inlinable internal init(_ level: _Level, _ node: _Node, _ hashPrefix: _Hash) { diff --git a/Sources/PersistentCollections/Node/_Node+Structural filter.swift b/Sources/PersistentCollections/Node/_Node+Structural filter.swift index 2b79e098..dd1da281 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural filter.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural filter.swift @@ -16,8 +16,7 @@ extension _Node { _ hashPrefix: _Hash, _ isIncluded: (Element) throws -> Bool ) rethrows -> Builder { - // FIXME: Consider preserving `self` when nothing needs to be removed. - return try self.read { + try self.read { var result: Builder = .empty if isCollisionNode { @@ -27,6 +26,11 @@ extension _Node { result.addNewCollision(items[i], $0.collisionHash) } } + if result.count == self.count { + // FIXME: Delay allocating a result node until we know for sure + // we're going to need it. + return .node(self, $0.collisionHash) + } return result } @@ -43,6 +47,12 @@ extension _Node { let branch = try $0[child: slot].filter(level.descend(), h, isIncluded) result.addNewChildBranch(level, branch) } + + if result.count == self.count { + // FIXME: Delay allocating a result node until we know for sure + // we're going to need it. + return .node(self, hashPrefix) + } return result } } diff --git a/Sources/PersistentCollections/Node/_Node+Structural intersection.swift b/Sources/PersistentCollections/Node/_Node+Structural intersection.swift index 4dd1e4a3..83c6ce89 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural intersection.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural intersection.swift @@ -16,7 +16,6 @@ extension _Node { _ hashPrefix: _Hash, _ other: _Node ) -> Builder { - // FIXME: Consider preserving `self` when nothing needs to be removed. if self.raw.storage === other.raw.storage { return .node(self, hashPrefix) } if self.isCollisionNode || other.isCollisionNode { @@ -68,6 +67,11 @@ extension _Node { result.addNewChildBranch(level, branch) } } + if result.count == self.count { + // FIXME: Delay allocating a result node until we know for sure + // we're going to need it. + return .node(self, hashPrefix) + } return result } } diff --git a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift index f7c7de01..b2350c21 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift @@ -16,7 +16,6 @@ extension _Node { _ hashPrefix: _Hash, _ other: _Node ) -> Builder { - // FIXME: Consider preserving `self` when nothing needs to be removed. if self.raw.storage === other.raw.storage { return .empty } if self.isCollisionNode || other.isCollisionNode { @@ -74,6 +73,11 @@ extension _Node { result.addNewChildBranch(level, .node(l[child: lslot], hp)) } } + if result.count == self.count { + // FIXME: Delay allocating a result node until we know for sure + // we're going to need it. + return .node(self, hashPrefix) + } return result } } @@ -101,6 +105,11 @@ extension _Node { result.addNewCollision(litems[i], l.collisionHash) } } + if result.count == self.count { + // FIXME: Delay allocating a result node until we know for sure + // we're going to need it. + return .node(self, l.collisionHash) + } return result } } From 4a4c4a75fd0b0f222fa70615dc3bee5dbf1730b4 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Tue, 27 Sep 2022 20:46:23 -0700 Subject: [PATCH 08/18] [PersistentSet] Add tests for union; fix issues --- .../Node/_Node+Primitive Insertions.swift | 2 +- .../Node/_Node+Primitive Removals.swift | 15 +++ .../Node/_Node+Primitive Replacement.swift | 37 ++++++ .../Node/_Node+Structural subtracting.swift | 1 - .../Node/_Node+Structural union.swift | 109 +++++++++++------- .../Node/_Node+Subtree Insertions.swift | 38 +++--- .../Node/_Node+Subtree Removals.swift | 8 +- ...rsistentSet+SetAlgebra fluent basics.swift | 4 +- .../PersistentSet+SetAlgebra union.swift | 1 + .../PersistentSet Tests.swift | 19 ++- 10 files changed, 165 insertions(+), 69 deletions(-) create mode 100644 Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift diff --git a/Sources/PersistentCollections/Node/_Node+Primitive Insertions.swift b/Sources/PersistentCollections/Node/_Node+Primitive Insertions.swift index c52b16c3..d1f17675 100644 --- a/Sources/PersistentCollections/Node/_Node+Primitive Insertions.swift +++ b/Sources/PersistentCollections/Node/_Node+Primitive Insertions.swift @@ -80,7 +80,7 @@ extension _Node.UnsafeHandle { extension _Node { @inlinable @inline(__always) internal mutating func insertItem( - _ item: __owned Element, _ bucket: _Bucket + _ item: __owned Element, at bucket: _Bucket ) { let slot = read { $0.itemMap.slot(of: bucket) } self.insertItem(item, at: slot, bucket) diff --git a/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift b/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift index 8cd4c573..94d2fb01 100644 --- a/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift +++ b/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift @@ -62,6 +62,21 @@ extension _Node.UnsafeHandle { } extension _Node { + @inlinable + internal mutating func removeItem( + at bucket: _Bucket + ) -> Element { + let slot = read { $0.itemMap.slot(of: bucket) } + return removeItem(at: slot, bucket, by: { $0.move() }) + } + + @inlinable + internal mutating func removeItem( + at slot: _Slot, _ bucket: _Bucket + ) -> Element { + removeItem(at: slot, bucket, by: { $0.move() }) + } + /// Remove the item at `slot`, increasing the amount of free /// space available in the node. /// diff --git a/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift b/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift new file mode 100644 index 00000000..bec13f35 --- /dev/null +++ b/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift @@ -0,0 +1,37 @@ +//===----------------------------------------------------------------------===// +// +// 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 mutating func replaceChild( + at bucket: _Bucket, with child: _Node + ) -> Int { + let slot = read { $0.childMap.slot(of: bucket) } + return replaceChild(at: bucket, slot, with: child) + } + + @inlinable + internal mutating func replaceChild( + at bucket: _Bucket, _ slot: _Slot, with child: _Node + ) -> Int { + let delta = update { + assert(!$0.isCollisionNode) + assert($0.childMap.contains(bucket)) + assert($0.childMap.slot(of: bucket) == slot) + let p = $0.childPtr(at: slot) + let delta = child.count &- p.pointee.count + p.pointee = child + return delta + } + self.count &+= delta + return delta + } +} diff --git a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift index b2350c21..eb945271 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift @@ -175,5 +175,4 @@ extension _Node { } } } - } diff --git a/Sources/PersistentCollections/Node/_Node+Structural union.swift b/Sources/PersistentCollections/Node/_Node+Structural union.swift index c4d50eff..4500575a 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural union.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural union.swift @@ -16,6 +16,9 @@ extension _Node { _ hashPrefix: _Hash, _ other: _Node ) -> (copied: Bool, node: _Node) { + guard self.count > 0 else { return (true, other) } + guard other.count > 0 else { return (false, self) } + if self.raw.storage === other.raw.storage { return (false, self) } @@ -35,11 +38,15 @@ extension _Node { let lp = l.itemPtr(at: lslot) let rp = r.itemPtr(at: rslot) if lp.pointee.key != rp.pointee.key { + let slot = ( + copied + ? node.read { $0.itemMap.slot(of: bucket) } + : lslot) _ = node.ensureUniqueAndSpawnChild( isUnique: copied, level: level, replacing: bucket, - itemSlot: lslot, + itemSlot: slot, newHash: _Hash(rp.pointee.key), { $0.initialize(to: rp.pointee) }) copied = true @@ -47,18 +54,14 @@ extension _Node { } 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 - } + + node.ensureUnique( + isUnique: copied, withFreeSpace: _Node.spaceForSpawningChild) + let item = node.removeItem(at: bucket) + let r = rp.pointee.inserting(level.descend(), item, _Hash(item.key)) + node.insertChild(r.node, bucket) + copied = true } } @@ -67,18 +70,14 @@ extension _Node { 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) - } + let r = l[child: lslot].inserting(level.descend(), rp.pointee, h) guard r.inserted else { // Nothing to do continue } node.ensureUnique(isUnique: copied) - node.update { $0[child: lslot] = r.node } - node.count &+= 1 + let delta = node.replaceChild(at: bucket, with: r.node) + assert(delta == 1) copied = true } else if r.childMap.contains(bucket) { @@ -92,18 +91,28 @@ extension _Node { 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 + let delta = node.replaceChild(at: bucket, with: child.node) + assert(delta > 0) // If we didn't add an item, why did we copy? copied = true } } + /// Add buckets in `other` that we haven't processed above. + let seen = l.itemMap.union(l.childMap) + for (bucket, _) in r.itemMap.subtracting(seen) { + let rslot = r.itemMap.slot(of: bucket) + node.ensureUniqueAndInsertItem( + isUnique: copied, r[item: rslot], at: bucket) + copied = true + } + for (bucket, _) in r.childMap.subtracting(seen) { + let rslot = r.childMap.slot(of: bucket) + node.ensureUnique( + isUnique: copied, withFreeSpace: _Node.spaceForNewChild) + copied = true + node.insertChild(r[child: rslot], bucket) + } + return (copied, node) } } @@ -138,6 +147,7 @@ extension _Node { isUnique: copied, p.pointee) copied = true } + p -= 1 } return (copied, node) } @@ -155,6 +165,13 @@ extension _Node { let bucket = l.collisionHash[level] if r.itemMap.contains(bucket) { let rslot = r.itemMap.slot(of: bucket) + let rp = r.itemPtr(at: rslot) + if + r.hasSingletonItem + && l.reverseItems.contains(where: { $0.key == rp.pointee.key }) + { + return (false, self) + } let node = other.copyNodeAndPushItemIntoNewChild( level: level, self, @@ -162,19 +179,20 @@ extension _Node { itemSlot: rslot) return (true, node) } - else if r.childMap.contains(bucket) { + + 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) + let delta = node.replaceChild(at: bucket, rslot, with: res.node) + assert(delta >= 0) return (true, node) } + + var node = other.copy(withFreeSpace: _Node.spaceForNewChild) + node.insertChild(self, bucket) + return (true, node) } } } @@ -186,6 +204,12 @@ extension _Node { let bucket = r.collisionHash[level] if l.itemMap.contains(bucket) { let lslot = l.itemMap.slot(of: bucket) + let lp = l.itemPtr(at: lslot) + if l.hasSingletonItem { + let hash = _Hash(lp.pointee.key) + let replacement = other.inserting(level, lp.pointee, hash) + return (true, replacement.node) + } let node = self.copyNodeAndPushItemIntoNewChild( level: level, other, @@ -193,19 +217,20 @@ extension _Node { itemSlot: lslot) return (true, node) } - else if l.childMap.contains(bucket) { + 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) + let child = l[child: lslot].union(level.descend(), h, other) + guard child.copied else { return (false, self) } 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) + let delta = node.replaceChild(at: bucket, lslot, with: child.node) + assert(delta > 0) // If we didn't add an item, why did we copy? return (true, node) } + + 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 b78d7d1d..b80312be 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift @@ -62,6 +62,15 @@ extension _Node { } } + @inlinable + internal func inserting( + _ level: _Level, + _ item: __owned Element, + _ hash: _Hash + ) -> (inserted: Bool, node: _Node, leaf: _UnmanagedNode, slot: _Slot) { + inserting(level, item.key, hash, { $0.initialize(to: item) }) + } + @inlinable internal func inserting( _ level: _Level, @@ -93,7 +102,7 @@ extension _Node { case .expansion: let r = _Node.build( level: level, - item1: { _ in }, hash, + item1: inserter, hash, child2: self, self.collisionHash) return (true, r.top, r.leaf, r.slot1) case .descend(_, let slot): @@ -354,6 +363,11 @@ extension _Node { assert(!src.childMap.contains(bucket)) assert(src.itemMap.slot(of: bucket) == itemSlot) + if src.hasSingletonItem && newChild.isCollisionNode { + // Compression + return newChild + } + let childSlot = src.childMap.slot(of: bucket) return Self.allocate( itemMap: src.itemMap.removing(bucket), @@ -457,13 +471,10 @@ extension _Node { } assert(!isCollisionNode) - let item = removeItem(at: itemSlot, bucket, by: { $0.move() }) + let item = removeItem(at: itemSlot, bucket) let hash = _Hash(item.key) - let r = newChild.inserting(level.descend(), item.key, hash) { - $0.initialize(to: item) - } - assert(r.inserted) - insertChild(newChild, bucket) + let r = newChild.inserting(level.descend(), item, hash) + insertChild(r.node, bucket) } @inlinable @inline(never) @@ -476,11 +487,10 @@ extension _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) } + let r = newChild.inserting(level, item, hash) return _copyNodeAndReplaceItemWithNewChild( level: level, - newChild, + r.node, at: bucket, itemSlot: itemSlot) } @@ -495,12 +505,10 @@ extension _Node { 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) + let r = newChild.inserting(level, item, hash) _resizeNodeAndReplaceItemWithNewChild( level: level, - newChild, + r.node, at: bucket, itemSlot: itemSlot) } @@ -545,7 +553,7 @@ extension _Node { inserter) } - let existing = removeItem(at: itemSlot, bucket) { $0.move() } + let existing = removeItem(at: itemSlot, bucket) let r = _Node.build( level: level.descend(), item1: existing, existingHash, diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift index b1e91213..7dca801e 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift @@ -168,7 +168,7 @@ extension _Node { return read { (replacement: $0[child: .zero], old: $0[item: .zero]) } } var node = self.copy() - let old = node.removeItem(at: slot, bucket) { $0.move() } + let old = node.removeItem(at: slot, bucket) if level.isAtRoot, node.isCollisionNode, node.hasSingletonItem { node._convertToRegularNode() } @@ -198,7 +198,7 @@ extension _Node { return (.item(remainder, hashPrefix), old) } var node = self.copy() - let old = node.removeItem(at: slot, bucket) { $0.move() } + let old = node.removeItem(at: slot, bucket) node._invariantCheck() return (.node(node, hashPrefix), old) } @@ -251,7 +251,7 @@ extension _Node { let bucket = bucket(&self) var child = self.removeChild(at: slot, bucket) let item = child.removeSingletonItem() - insertItem(item, bucket) + insertItem(item, at: bucket) } if isAtrophied { self = removeSingletonChild() @@ -270,7 +270,7 @@ extension _Node { var node = copy(withFreeSpace: Self.spaceForInlinedChild) _ = node.removeChild(at: slot, bucket) let item = newChild.removeSingletonItem() - node.insertItem(item, bucket) + node.insertItem(item, at: bucket) node._invariantCheck() return node } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift index f9caec67..1e89ed28 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra fluent basics.swift @@ -13,9 +13,7 @@ extension PersistentSet { @inlinable public func inserting(_ newMember: __owned Element) -> Self { let hash = _Hash(newMember) - let r = _root.inserting(.top, newMember, hash) { - $0.initialize(to: (newMember, ())) - } + let r = _root.inserting(.top, (newMember, ()), hash) return PersistentSet(_new: r.node) } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift index 3f4ea30d..c6c87469 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift @@ -14,6 +14,7 @@ extension PersistentSet { public func union(_ other: __owned Self) -> Self { let r = _root.union(.top, .emptyPrefix, other._root) guard r.copied else { return self } + r.node._fullInvariantCheck(.top, .emptyPrefix) return PersistentSet(_new: r.node) } } diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index a09caf6d..9458291a 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -206,9 +206,9 @@ class PersistentSetTests: CollectionTestCase { RawCollider(3, "ACB"), RawCollider(4, "ACAD"), RawCollider(5, "ACAD"), - RawCollider(6, "ACADB"), - RawCollider(7, "ACADB"), - RawCollider(8, "ACADB"), + RawCollider(6, "ACAEB"), + RawCollider(7, "ACAEB"), + RawCollider(8, "ACAEB"), ] func test_isEqual_Self_exhaustive() { @@ -322,4 +322,17 @@ class PersistentSetTests: CollectionTestCase { } } } + + func test_union_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentSet(a) + let u = Set(a) + expectEqualSets(x.union(x), u) + withEverySubset("b", of: testItems) { b in + let y = PersistentSet(b) + let v = Set(b) + expectEqualSets(x.union(y), u.union(v)) + } + } + } } From 562b21e70ff35e5312cdc49fe683137b7c637946 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 28 Sep 2022 14:45:44 -0700 Subject: [PATCH 09/18] =?UTF-8?q?[PersistentCollections]=20filter,=20inter?= =?UTF-8?q?section,=20subtracting:=20Don=E2=80=99t=20build=20a=20result=20?= =?UTF-8?q?node=20until=20we=20know=20for=20sure=20we=20won=E2=80=99t=20ju?= =?UTF-8?q?st=20clone=20self?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Node/_Node+Builder.swift | 57 +++++++++ .../Node/_Node+Primitive Replacement.swift | 41 ++++++ .../Node/_Node+Structural filter.swift | 73 +++++++---- .../Node/_Node+Structural intersection.swift | 85 +++++++++---- .../Node/_Node+Structural subtracting.swift | 118 +++++++++++------- .../Node/_Node+Subtree Removals.swift | 28 ++--- .../PersistentDictionary+Filter.swift | 1 + .../PersistentSet/PersistentSet+Filter.swift | 1 + ...ersistentSet+SetAlgebra intersection.swift | 1 + ...PersistentSet+SetAlgebra subtracting.swift | 1 + .../PersistentSet Tests.swift | 4 +- 11 files changed, 302 insertions(+), 108 deletions(-) diff --git a/Sources/PersistentCollections/Node/_Node+Builder.swift b/Sources/PersistentCollections/Node/_Node+Builder.swift index e3449e86..98d3d2e4 100644 --- a/Sources/PersistentCollections/Node/_Node+Builder.swift +++ b/Sources/PersistentCollections/Node/_Node+Builder.swift @@ -33,6 +33,12 @@ extension _Node.Builder { return node.count } } + + @inlinable + internal var isEmpty: Bool { + guard case .empty = self else { return false } + return true + } } extension _Node.Builder { @@ -168,3 +174,54 @@ extension _Node.Builder { return result } } + +extension _Node.Builder { + @inlinable + internal mutating func copyCollisions( + from source: _Node.UnsafeHandle, + upTo end: _Slot + ) { + assert(isEmpty) + assert(source.isCollisionNode) + assert(end < source.itemsEndSlot) + let h = source.collisionHash + for slot: _Slot in stride(from: .zero, to: end, by: 1) { + self.addNewCollision(source[item: slot], h) + } + } + + @inlinable + internal mutating func copyItems( + _ level: _Level, + _ hashPrefix: _Hash, + from source: _Node.UnsafeHandle, + upTo end: _Bucket + ) { + assert(isEmpty) + assert(!source.isCollisionNode) + for (b, s) in source.itemMap.intersection(_Bitmap(upTo: end)) { + let h = hashPrefix.appending(b, at: level) + self.addNewItem(level, source[item: s], h) + } + } + + @inlinable + internal mutating func copyItemsAndChildren( + _ level: _Level, + _ hashPrefix: _Hash, + from source: _Node.UnsafeHandle, + upTo end: _Bucket + ) { + assert(isEmpty) + assert(!source.isCollisionNode) + for (b, s) in source.itemMap { + let h = hashPrefix.appending(b, at: level) + self.addNewItem(level, source[item: s], h) + } + for (b, s) in source.childMap.intersection(_Bitmap(upTo: end)) { + let h = hashPrefix.appending(b, at: level) + self.addNewChildBranch(level, .node(source[child: s], h)) + } + } + +} diff --git a/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift b/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift index bec13f35..5aa40f9e 100644 --- a/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift +++ b/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift @@ -34,4 +34,45 @@ extension _Node { self.count &+= delta return delta } + + @inlinable + internal func replacingChild( + _ level: _Level, + _ hashPrefix: _Hash, + _ slot: _Slot, + with child: __owned Builder + ) -> Builder { + let bucket = hashPrefix[level] + read { + assert(!$0.isCollisionNode) + assert($0.childMap.contains(bucket)) + assert(slot == $0.childMap.slot(of: bucket)) + } + switch child { + case .empty: + return _removingChild(level, hashPrefix, bucket, slot) + case let .item(item, hash): + assert(hash.isEqual(to: hashPrefix, upTo: level)) + assert(hash[level] == bucket) + if hasSingletonChild { + return child + } + var node = self.copy(withFreeSpace: _Node.spaceForInlinedChild) + _ = node.removeChild(at: slot, bucket) + node.insertItem(item, at: bucket) + node._invariantCheck() + return .node(node, hashPrefix) + case let .node(node, hash): + assert(hash.isEqual(to: hashPrefix, upTo: level)) + assert(hash[level] == bucket) + if node.isCollisionNode, self.hasSingletonChild { + // Compression + assert(!level.isAtBottom) + return child + } + var copy = self.copy() + _ = copy.replaceChild(at: bucket, slot, with: node) + return .node(copy, hashPrefix) + } + } } diff --git a/Sources/PersistentCollections/Node/_Node+Structural filter.swift b/Sources/PersistentCollections/Node/_Node+Structural filter.swift index dd1da281..2931d9df 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural filter.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural filter.swift @@ -15,44 +15,71 @@ extension _Node { _ level: _Level, _ hashPrefix: _Hash, _ isIncluded: (Element) throws -> Bool - ) rethrows -> Builder { - try self.read { + ) rethrows -> Builder? { + guard !isCollisionNode else { + return try _filter_slow(isIncluded) + } + return try self.read { var result: Builder = .empty - - if isCollisionNode { - let items = $0.reverseItems - for i in items.indices { - if try isIncluded(items[i]) { - result.addNewCollision(items[i], $0.collisionHash) - } - } - if result.count == self.count { - // FIXME: Delay allocating a result node until we know for sure - // we're going to need it. - return .node(self, $0.collisionHash) - } - return result - } + var removing = false // true if we need to remove something for (bucket, slot) in $0.itemMap { let p = $0.itemPtr(at: slot) - if try isIncluded(p.pointee) { + let include = try isIncluded(p.pointee) + switch (include, removing) { + case (true, true): let h = hashPrefix.appending(bucket, at: level) result.addNewItem(level, p.pointee, h) + case (false, false): + removing = true + result.copyItems(level, hashPrefix, from: $0, upTo: bucket) + default: + break } } for (bucket, slot) in $0.childMap { let h = hashPrefix.appending(bucket, at: level) let branch = try $0[child: slot].filter(level.descend(), h, isIncluded) - result.addNewChildBranch(level, branch) + if let branch = branch { + assert(branch.count < self.count) + if !removing { + removing = true + result.copyItemsAndChildren( + level, hashPrefix, from: $0, upTo: bucket) + } + result.addNewChildBranch(level, branch) + } else if removing { + result.addNewChildBranch(level, .node($0[child: slot], h)) + } } - if result.count == self.count { - // FIXME: Delay allocating a result node until we know for sure - // we're going to need it. - return .node(self, hashPrefix) + guard removing else { return nil } + return result + } + } + + @inlinable @inline(never) + internal func _filter_slow( + _ isIncluded: (Element) throws -> Bool + ) rethrows -> Builder? { + try self.read { + var result: Builder = .empty + var removing = false + + for slot: _Slot in stride(from: .zero, to: $0.itemsEndSlot, by: 1) { + let p = $0.itemPtr(at: slot) + let include = try isIncluded(p.pointee) + if include, removing { + result.addNewCollision(p.pointee, $0.collisionHash) + } + else if !include, !removing { + removing = true + result.copyCollisions(from: $0, upTo: slot) + } } + guard removing else { return nil } + assert(result.count < self.count) return result } } diff --git a/Sources/PersistentCollections/Node/_Node+Structural intersection.swift b/Sources/PersistentCollections/Node/_Node+Structural intersection.swift index 83c6ce89..405415a9 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural intersection.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural intersection.swift @@ -15,8 +15,8 @@ extension _Node { _ level: _Level, _ hashPrefix: _Hash, _ other: _Node - ) -> Builder { - if self.raw.storage === other.raw.storage { return .node(self, hashPrefix) } + ) -> Builder? { + if self.raw.storage === other.raw.storage { return nil } if self.isCollisionNode || other.isCollisionNode { return _intersection_slow(level, hashPrefix, other) @@ -25,28 +25,40 @@ extension _Node { return self.read { l in other.read { r in var result: Builder = .empty + var removing = false + for (bucket, lslot) in l.itemMap { + let lp = l.itemPtr(at: lslot) + let include: Bool if r.itemMap.contains(bucket) { let rslot = r.itemMap.slot(of: bucket) - let lp = l.itemPtr(at: lslot) - if lp.pointee.key == r[item: rslot].key { - let hashPrefix = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, lp.pointee, hashPrefix) - } + include = (lp.pointee.key == r[item: rslot].key) } else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - 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) - } + include = r[child: rslot] + .containsKey(level.descend(), lp.pointee.key, h) + } + else { include = false} + + if include, removing { + let hashPrefix = hashPrefix.appending(bucket, at: level) + result.addNewItem(level, lp.pointee, hashPrefix) + } + else if !include, !removing { + removing = true + result.copyItems(level, hashPrefix, from: l, upTo: bucket) } } for (bucket, lslot) in l.childMap { if r.itemMap.contains(bucket) { + if !removing { + removing = true + result.copyItemsAndChildren( + level, hashPrefix, from: l, upTo: bucket) + } let rslot = r.itemMap.slot(of: bucket) let rp = r.itemPtr(at: rslot) let h = _Hash(rp.pointee.key) @@ -64,14 +76,26 @@ extension _Node { level.descend(), hashPrefix.appending(bucket, at: level), r[child: rslot]) - result.addNewChildBranch(level, branch) + if let branch = branch { + assert(branch.count < self.count) + if !removing { + removing = true + result.copyItemsAndChildren( + level, hashPrefix, from: l, upTo: bucket) + } + result.addNewChildBranch(level, branch) + } else if removing { + let h = hashPrefix.appending(bucket, at: level) + result.addNewChildBranch(level, .node(l[child: lslot], h)) + } + } + else if !removing { + removing = true + result.copyItemsAndChildren( + level, hashPrefix, from: l, upTo: bucket) } } - if result.count == self.count { - // FIXME: Delay allocating a result node until we know for sure - // we're going to need it. - return .node(self, hashPrefix) - } + guard removing else { return nil } return result } } @@ -82,7 +106,7 @@ extension _Node { _ level: _Level, _ hashPrefix: _Hash, _ other: _Node - ) -> Builder { + ) -> Builder? { let lc = self.isCollisionNode let rc = other.isCollisionNode if lc && rc { @@ -90,13 +114,22 @@ extension _Node { other.read { r in guard l.collisionHash == r.collisionHash else { return .empty } var result: Builder = .empty - let litems = l.reverseItems + var removing = false + let ritems = r.reverseItems - for i in litems.indices { - if ritems.contains(where: { $0.key == litems[i].key }) { - result.addNewCollision(litems[i], l.collisionHash) + for lslot: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { + let lp = l.itemPtr(at: lslot) + let include = ritems.contains { $0.key == lp.pointee.key } + if include, removing { + result.addNewCollision(lp.pointee, l.collisionHash) + } + else if !include, !removing { + removing = true + result.copyCollisions(from: l, upTo: lslot) } } + guard removing else { return nil } + assert(result.count < self.count) return result } } @@ -150,6 +183,12 @@ extension _Node { level.descend(), hashPrefix.appending(bucket, at: level), other) + guard let branch = branch else { + assert(l[child: lslot].isCollisionNode) + assert(l[child: lslot].collisionHash == r.collisionHash) + // Compression + return .node(l[child: lslot], r.collisionHash) + } return .childBranch(level, branch) } return .empty diff --git a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift index eb945271..d3c9eb86 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural subtracting.swift @@ -15,7 +15,7 @@ extension _Node { _ level: _Level, _ hashPrefix: _Hash, _ other: _Node - ) -> Builder { + ) -> Builder? { if self.raw.storage === other.raw.storage { return .empty } if self.isCollisionNode || other.isCollisionNode { @@ -25,25 +25,32 @@ extension _Node { return self.read { l in other.read { r in var result: Builder = .empty + var removing = false + for (bucket, lslot) in l.itemMap { let lp = l.itemPtr(at: lslot) + let include: Bool if r.itemMap.contains(bucket) { let rslot = r.itemMap.slot(of: bucket) - if lp.pointee.key != r[item: rslot].key { - let hashPrefix = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, lp.pointee, hashPrefix) - } + include = (lp.pointee.key != r[item: rslot].key) } else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) let h = _Hash(lp.pointee.key) - if !r[child: rslot].containsKey(level.descend(), lp.pointee.key, h) { - result.addNewItem(level, lp.pointee, h) - } + include = !r[child: rslot] + .containsKey(level.descend(), lp.pointee.key, h) } else { - let hp = hashPrefix.appending(bucket, at: level) - result.addNewItem(level, lp.pointee, hp) + include = true + } + + if include, removing { + let h = hashPrefix.appending(bucket, at: level) + result.addNewItem(level, lp.pointee, h) + } + else if !include, !removing { + removing = true + result.copyItems(level, hashPrefix, from: l, upTo: bucket) } } @@ -52,32 +59,48 @@ extension _Node { let rslot = r.itemMap.slot(of: bucket) let rp = r.itemPtr(at: rslot) let h = _Hash(rp.pointee.key) - let node = ( - l[child: lslot] - .removing(level.descend(), rp.pointee.key, h)?.replacement - ?? l[child: lslot]) - let branch = Builder( - level.descend(), node, hashPrefix.appending(bucket, at: level)) - result.addNewChildBranch(level, branch) + let child = l[child: lslot] + .removing2(level.descend(), rp.pointee.key, h)?.replacement + if let child = child { + assert(child.count < self.count) + if !removing { + removing = true + result.copyItemsAndChildren( + level, hashPrefix, from: l, upTo: bucket) + } + result.addNewChildBranch(level, child) + } + else if removing { + let h = hashPrefix.appending(bucket, at: level) + result.addNewChildBranch(level, .node(l[child: lslot], h)) + } } else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - let branch = l[child: lslot].subtracting( + let child = l[child: lslot].subtracting( level.descend(), hashPrefix.appending(bucket, at: level), r[child: rslot]) - result.addNewChildBranch(level, branch) + if let child = child { + assert(child.count < self.count) + if !removing { + removing = true + result.copyItemsAndChildren( + level, hashPrefix, from: l, upTo: bucket) + } + result.addNewChildBranch(level, child) + } + else if removing { + let h = hashPrefix.appending(bucket, at: level) + result.addNewChildBranch(level, .node(l[child: lslot], h)) + } } - else { - let hp = hashPrefix.appending(bucket, at: level) - result.addNewChildBranch(level, .node(l[child: lslot], hp)) + else if removing { + let h = hashPrefix.appending(bucket, at: level) + result.addNewChildBranch(level, .node(l[child: lslot], h)) } } - if result.count == self.count { - // FIXME: Delay allocating a result node until we know for sure - // we're going to need it. - return .node(self, hashPrefix) - } + guard removing else { return nil } return result } } @@ -88,28 +111,32 @@ extension _Node { _ level: _Level, _ hashPrefix: _Hash, _ other: _Node - ) -> Builder { + ) -> Builder? { 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 { - return .node(self, l.collisionHash) + return nil } var result: Builder = .empty - let litems = l.reverseItems + var removing = false + let ritems = r.reverseItems - for i in litems.indices { - if !ritems.contains(where: { $0.key == litems[i].key }) { - result.addNewCollision(litems[i], l.collisionHash) + for lslot: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { + let lp = l.itemPtr(at: lslot) + let include = !ritems.contains { $0.key == lp.pointee.key } + if include, removing { + result.addNewCollision(lp.pointee, l.collisionHash) + } + else if !include, !removing { + removing = true + result.copyCollisions(from: l, upTo: lslot) } } - if result.count == self.count { - // FIXME: Delay allocating a result node until we know for sure - // we're going to need it. - return .node(self, l.collisionHash) - } + guard removing else { return nil } + assert(result.count < self.count) return result } } @@ -129,11 +156,9 @@ extension _Node { let ritem = r.itemPtr(at: rslot) let h = _Hash(ritem.pointee.key) let res = l.find(level, ritem.pointee.key, h) - guard let res = res else { - return .node(self, l.collisionHash) - } + guard let res = res else { return nil } return self._removingItemFromLeaf( - level, hashPrefix, bucket, res.slot + level, hashPrefix.appending(bucket, at: level), res.slot ).replacement } else if r.childMap.contains(bucket) { @@ -141,7 +166,7 @@ extension _Node { let h = hashPrefix.appending(bucket, at: level) return self.subtracting(level.descend(), h, r[child: rslot]) } - return .node(self, l.collisionHash) + return nil } } } @@ -156,9 +181,9 @@ extension _Node { let litem = l.itemPtr(at: lslot) let h = _Hash(litem.pointee.key) let res = r.find(level, litem.pointee.key, h) - if res == nil { return .node(self, hashPrefix) } + if res == nil { return nil } return self._removingItemFromLeaf( - level, hashPrefix, bucket, lslot + level, hashPrefix.appending(bucket, at: level), lslot ).replacement } if l.childMap.contains(bucket) { @@ -167,11 +192,12 @@ extension _Node { level.descend(), hashPrefix.appending(bucket, at: level), other) + guard let branch = branch else { return nil } var result = self._removingChild(level, hashPrefix, bucket, lslot) result.addNewChildBranch(level, branch) return result } - return .node(self, hashPrefix) + return nil } } } diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift index 7dca801e..61463c9e 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift @@ -66,21 +66,17 @@ extension _Node { } @inlinable - internal func removing( - _ level: _Level, - _ hashPrefix: _Hash, - _ key: Key, - _ hash: _Hash + internal func removing2( + _ level: _Level, _ key: Key, _ hash: _Hash ) -> (replacement: Builder, old: Element)? { - assert(hashPrefix.isEqual(to: hash, upTo: level)) guard let r = find(level, key, hash) else { return nil } guard r.descend else { - return _removingItemFromLeaf(level, hashPrefix, hash[level], r.slot) + return _removingItemFromLeaf(level, hash, r.slot) } - let hp = hashPrefix.appending(hash[level], at: level) - let r2 = read { $0[child: r.slot].removing(level.descend(), hp, key, hash) } + let r2 = read { $0[child: r.slot].removing2(level.descend(), key, hash) } guard let r2 = r2 else { return nil } - return (.childBranch(level, r2.replacement), r2.old) + let result = self.replacingChild(level, hash, r.slot, with: r2.replacement) + return (result, r2.old) } } @@ -178,10 +174,12 @@ extension _Node { @inlinable internal func _removingItemFromLeaf( - _ level: _Level, _ hashPrefix: _Hash, _ bucket: _Bucket, _ slot: _Slot + _ level: _Level, _ hash: _Hash, _ slot: _Slot ) -> (replacement: Builder, old: Element) { read { - assert($0.isCollisionNode || $0.itemMap.contains(bucket)) + assert($0.isCollisionNode || $0.itemMap.contains(hash[level])) + assert(!$0.isCollisionNode || slot.value < $0.collisionCount ) + assert($0.isCollisionNode || slot == $0.itemMap.slot(of: hash[level])) let willAtrophy = ( $0.itemCount == 1 && $0.childCount == 1 @@ -195,12 +193,12 @@ extension _Node { if willEvaporate { let remainder = $0[item: _Slot(1 &- slot.value)] let old = $0[item: slot] - return (.item(remainder, hashPrefix), old) + return (.item(remainder, hash), old) } var node = self.copy() - let old = node.removeItem(at: slot, bucket) + let old = node.removeItem(at: slot, hash[level]) node._invariantCheck() - return (.node(node, hashPrefix), old) + return (.node(node, hash), old) } } } diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift index ce3cec2d..de07b163 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Filter.swift @@ -15,6 +15,7 @@ extension PersistentDictionary { _ isIncluded: (Element) throws -> Bool ) rethrows -> Self { let result = try _root.filter(.top, .emptyPrefix, isIncluded) + guard let result = result else { return self } return PersistentDictionary(_new: result.finalize(.top)) } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift index 031fb952..3c57db5c 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+Filter.swift @@ -17,6 +17,7 @@ extension PersistentSet { let result = try _root.filter(.top, .emptyPrefix) { try isIncluded($0.key) } + guard let result = result else { return self } return PersistentSet(_new: result.finalize(.top)) } } diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift index 6cfbbe44..c4365941 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift @@ -13,6 +13,7 @@ extension PersistentSet { @inlinable public func intersection(_ other: Self) -> Self { let builder = _root.intersection(.top, .emptyPrefix, other._root) + guard let builder = builder else { return self } let root = builder.finalize(.top) root._fullInvariantCheck(.top, .emptyPrefix) return Self(_new: root) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift index b42fd5eb..f2d1602a 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift @@ -13,6 +13,7 @@ extension PersistentSet { @inlinable public __consuming func subtracting(_ other: Self) -> Self { let builder = _root.subtracting(.top, .emptyPrefix, other._root) + guard let builder = builder else { return self } let root = builder.finalize(.top) root._fullInvariantCheck(.top, .emptyPrefix) return Self(_new: root) diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index 9458291a..1d90a922 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -198,7 +198,7 @@ class PersistentSetTests: CollectionTestCase { /// A set of items whose subsets will produce a bunch of interesting test /// cases. /// - /// Note: Try to keep this short. Every new item added here will double + /// Note: Try to keep this short. Every new item added here will quadruple /// testing costs. let testItems = [ RawCollider(1, "A"), @@ -293,6 +293,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("a", of: testItems) { a in let x = PersistentSet(a) let u = Set(a) + expectEqualSets(x.intersection(x), u) withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) @@ -305,6 +306,7 @@ class PersistentSetTests: CollectionTestCase { withEverySubset("a", of: testItems) { a in let x = PersistentSet(a) let u = Set(a) + expectEqualSets(x.subtracting(x), []) withEverySubset("b", of: testItems) { b in let y = PersistentSet(b) let v = Set(b) From d6b1e6c76768646f353105d7f26584c4ba9a5c2e Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 28 Sep 2022 18:37:49 -0700 Subject: [PATCH 10/18] [PersistentSet] Add some documentation --- ...stentSet+SetAlgebra formIntersection.swift | 17 ++++ ...t+SetAlgebra formSymmetricDifference.swift | 14 +++ .../PersistentSet+SetAlgebra formUnion.swift | 18 ++++ ...ersistentSet+SetAlgebra intersection.swift | 18 ++++ .../PersistentSet+SetAlgebra isDisjoint.swift | 47 +++++++++- ...sistentSet+SetAlgebra isStrictSubset.swift | 81 +++++++++++++++++ ...stentSet+SetAlgebra isStrictSuperset.swift | 81 +++++++++++++++++ .../PersistentSet+SetAlgebra isSubset.swift | 86 +++++++++++++++++++ .../PersistentSet+SetAlgebra isSuperset.swift | 53 ++++++++++++ .../PersistentSet+SetAlgebra subtract.swift | 13 +++ ...PersistentSet+SetAlgebra subtracting.swift | 14 +++ ...ntSet+SetAlgebra symmetricDifference.swift | 14 +++ .../PersistentSet+SetAlgebra union.swift | 17 ++++ .../_FastMembershipCheckable.swift | 2 +- 14 files changed, 472 insertions(+), 3 deletions(-) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formIntersection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formIntersection.swift index 7ddf7774..bd66d374 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formIntersection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formIntersection.swift @@ -10,6 +10,23 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Removes the elements of this set that aren't also in the given one. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [0, 2, 4, 6] + /// a.formIntersection(b) + /// // `a` is now some permutation of `[2, 4]` + /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// + /// - Parameter other: An arbitrary set of elements. + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public mutating func formIntersection(_ other: Self) { self = intersection(other) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formSymmetricDifference.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formSymmetricDifference.swift index afe0a3eb..ee85c49b 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formSymmetricDifference.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formSymmetricDifference.swift @@ -10,6 +10,20 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Replace this set with the elements contained in this set or the given + /// set, but not both. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [0, 2, 4, 6] + /// a.formSymmetricDifference(b) + /// // `a` is now some permutation of `[0, 1, 3, 6]` + /// + /// - Parameter other: An arbitrary set of elements. + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public mutating func formSymmetricDifference(_ other: __owned Self) { self = symmetricDifference(other) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formUnion.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formUnion.swift index dab9c748..9b94003e 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formUnion.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra formUnion.swift @@ -10,6 +10,24 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Adds the elements of the given set to this set. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [0, 2, 4, 6] + /// a.formUnion(b) + /// // `a` is now some permutation of `[0, 1, 2, 3, 4, 6]` + /// + /// For values that are members of both sets, this operation preserves the + /// instances that were originally in `self`. (This matters if equal members + /// can be distinguished by comparing their identities, or by some other + /// means.) + /// + /// - Parameter other: The set of elements to insert. + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public mutating func formUnion(_ other: __owned Self) { self = union(other) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift index c4365941..f4522873 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra intersection.swift @@ -10,6 +10,24 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Returns a new set with the elements that are common to both this set and + /// the provided other one. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [0, 2, 4, 6] + /// let c = a.intersection(b) + /// // `c` is some permutation of `[2, 4]` + /// + /// The result will only contain instances that were originally in `self`. + /// (This matters if equal members can be distinguished by comparing their + /// identities, or by some other means.) + /// + /// - Parameter other: An arbitrary set of elements. + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public func intersection(_ other: Self) -> Self { let builder = _root.intersection(.top, .emptyPrefix, other._root) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift index 937e3a03..bd6ab909 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isDisjoint.swift @@ -10,19 +10,62 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on + /// average, if `Element` implements high-quality hashing. @inlinable public func isDisjoint(with other: Self) -> Bool { self._root.isDisjoint(.top, with: other._root) } - @inlinable + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on + /// average, if `Element` implements high-quality hashing. + @inlinable public func isDisjoint( with other: PersistentDictionary.Keys ) -> Bool { self._root.isDisjoint(.top, with: other._base._root) } - @inlinable + /// Returns a Boolean value that indicates whether the set has no members in + /// common with the given set. + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [5, 6] + /// a.isDisjoint(with: b) // true + /// + /// - Parameter other: A sequence of elements, some of whose elements may + /// appear more than once. + /// + /// - Returns: `true` if `self` has no elements in common with `other`; + /// otherwise, `false`. + /// + /// - Complexity: In the worst case, this makes O(*n*) calls to + /// `self.contains`, where *n* is the length of the sequence. + @inlinable public func isDisjoint(with other: S) -> Bool where S.Element == Element { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift index f4505653..09919f73 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift @@ -12,12 +12,52 @@ import _CollectionsUtilities extension PersistentSet { + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// b.isStrictSubset(of: a) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. The implementation is careful to make + /// the best use of hash tree structure to minimize work when possible, + /// e.g. by skipping over parts of the input trees. @inlinable public func isStrictSubset(of other: Self) -> Bool { guard self.count < other.count else { return false } return isSubset(of: other) } + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// b.isStrictSubset(of: a) // true + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. The implementation is careful to make + /// the best use of hash tree structure to minimize work when possible, + /// e.g. by skipping over parts of the input trees. @inlinable public func isStrictSubset( of other: PersistentDictionary.Keys @@ -26,6 +66,26 @@ extension PersistentSet { return isSubset(of: other) } + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// b.isStrictSubset(of: a) // true + /// + /// - Parameter other: A sequence with a fast `contains` implementation, + /// some of whose elements may appear more than once. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: In the worst case, this makes `self.count` + /// calls to `other.contains`, followed by *n* calls to `self.contains` + /// where *n* is the length of the sequence. @inlinable public func isStrictSubset( of other: S @@ -36,6 +96,27 @@ extension PersistentSet { } + /// Returns a Boolean value that indicates whether the set is a strict subset + /// of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// b.isStrictSubset(of: a) // true + /// + /// - Parameter other: A sequence of elements, some of whose elements may + /// appear more than once. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: In the worst case, this makes O(*n*) calls to + /// `self.contains` (where *n* is the number of elements in `other`), + /// and it constructs a temporary persistent set containing every + /// element of the sequence. @inlinable public func isStrictSubset(of other: S) -> Bool where S.Element == Element diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift index 94b54d03..53f63e6e 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift @@ -12,12 +12,52 @@ import _CollectionsUtilities extension PersistentSet { + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given set. + /// + /// Set *A* is a strict superset of another set *B* if every member of *B* is + /// also a member of *A* and *A* contains at least one element that is *not* + /// a member of *B*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// a.isStrictSuperset(of: b.unordered) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if `self` is a strict superset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. The implementation is careful to make + /// the best use of hash tree structure to minimize work when possible, + /// e.g. by skipping over parts of the input trees. @inlinable public func isStrictSuperset(of other: Self) -> Bool { guard self.count > other.count else { return false } return other._root.isSubset(.top, of: self._root) } + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// a.isStrictSuperset(of: b.unordered) // true + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. The implementation is careful to make + /// the best use of hash tree structure to minimize work when possible, + /// e.g. by skipping over parts of the input trees. @inlinable public func isStrictSuperset( of other: PersistentDictionary.Keys @@ -26,6 +66,26 @@ extension PersistentSet { return other._base._root.isSubset(.top, of: self._root) } + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// a.isStrictSuperset(of: b.unordered) // true + /// + /// - Parameter other: A sequence with a fast `contains` implementation, + /// some of whose elements may appear more than once. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: In the worst case, this makes `other.count` + /// calls to `self.contains`, followed by *n* calls to `other.contains` + /// where *n* is the length of the sequence. @inlinable public func isStrictSuperset( of other: S @@ -37,6 +97,27 @@ extension PersistentSet { return !self.allSatisfy { other.contains($0) } } + /// Returns a Boolean value that indicates whether the set is a strict + /// superset of the given set. + /// + /// Set *A* is a strict subset of another set *B* if every member of *A* is + /// also a member of *B* and *B* contains at least one element that is not a + /// member of *A*. (Ignoring the order the elements appear in the sets.) + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// a.isStrictSuperset(of: b.unordered) // true + /// + /// - Parameter other: A sequence of elements, some of whose elements may + /// appear more than once. + /// + /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, + /// `false`. + /// + /// - Complexity: In the worst case, this makes O(*n*) calls to + /// `self.contains` (where *n* is the number of elements in `other`), + /// and it constructs a temporary persistent set containing every + /// element of the sequence. @inlinable public func isStrictSuperset(of other: S) -> Bool where S.Element == Element diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift index 608564d7..5231a7be 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift @@ -12,11 +12,47 @@ import _CollectionsUtilities extension PersistentSet { + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given set. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// b.isSubset(of: a) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. The implementation is careful to make + /// the best use of hash tree structure to minimize work when possible, + /// e.g. by skipping over parts of the input trees. @inlinable public func isSubset(of other: Self) -> Bool { self._root.isSubset(.top, of: other._root) } + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given set. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// b.isSubset(of: a) // true + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`self.count`) on average, if `Element` + /// implements high-quality hashing. The implementation is careful to make + /// the best use of hash tree structure to minimize work when possible, + /// e.g. by skipping over parts of the input trees. @inlinable public func isSubset( of other: PersistentDictionary.Keys @@ -24,6 +60,21 @@ extension PersistentSet { self._root.isSubset(.top, of: other._base._root) } + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given set. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// b.isSubset(of: a) // true + /// + /// - Parameter other: A container with a fast `contains` implementation. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: O(`self.count`) calls to `other.contains`. @inlinable public func isSubset( of other: S @@ -32,6 +83,22 @@ extension PersistentSet { self.allSatisfy { other.contains($0) } } + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given sequence. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// b.isSubset(of: a) // true + /// + /// - Parameter other: A sequence with a fast `contains` implementation, + /// some of whose elements may appear more than once. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: O(`self.count`) calls to `other.contains`. @inlinable public func isSubset( of other: S @@ -40,6 +107,25 @@ extension PersistentSet { self.allSatisfy { other.contains($0) } } + /// Returns a Boolean value that indicates whether this set is a subset of + /// the given sequence. + /// + /// Set *A* is a subset of another set *B* if every member of *A* is also a + /// member of *B*, ignoring the order they appear in the two sets. + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// b.isSubset(of: a) // true + /// + /// - Parameter other: A sequence of elements, some of whose elements may + /// appear more than once. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: In the worst case, this makes O(*n*) calls to + /// `self.contains` (where *n* is the number of elements in `other`), + /// and it constructs a temporary persistent set containing every + /// element of the sequence. @inlinable public func isSubset(of other: S) -> Bool where S.Element == Element diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift index 3641eed6..5d74547c 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift @@ -10,11 +10,47 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given set. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: Another set. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. The implementation is careful to make + /// the best use of hash tree structure to minimize work when possible, + /// e.g. by skipping over parts of the input trees. @inlinable public func isSuperset(of other: Self) -> Bool { other._root.isSubset(.top, of: self._root) } + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given set. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: The keys view of a persistent dictionary. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: Expected to be O(`other.count`) on average, if `Element` + /// implements high-quality hashing. The implementation is careful to make + /// the best use of hash tree structure to minimize work when possible, + /// e.g. by skipping over parts of the input trees. @inlinable public func isSuperset( of other: PersistentDictionary @@ -22,6 +58,23 @@ extension PersistentSet { other._root.isSubset(.top, of: self._root) } + /// Returns a Boolean value that indicates whether this set is a superset of + /// the given set. + /// + /// Set *A* is a superset of another set *B* if every member of *B* is also a + /// member of *A*, ignoring the order they appear in the two sets. + /// + /// let a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [4, 2, 1] + /// a.isSuperset(of: b) // true + /// + /// - Parameter other: A sequence of elements, some of whose elements may + /// appear more than once. + /// + /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. + /// + /// - Complexity: O(*n*) calls to `self.contains`, where *n* is the number + /// of elements in `other`. @inlinable public func isSuperset(of other: S) -> Bool where S.Element == Element diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtract.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtract.swift index 83eb1376..0535853b 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtract.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtract.swift @@ -10,6 +10,19 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Removes the elements of the given set from this set. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [0, 2, 4, 6] + /// a.subtract(b) + /// // `a` is now some permutation of `[1, 3]` + /// + /// - Parameter other: An arbitrary set of elements. + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public mutating func subtract(_ other: Self) { self = subtracting(other) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift index f2d1602a..c79cceb8 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra subtracting.swift @@ -10,6 +10,20 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Returns a new set containing the elements of this set that do not occur + /// in the given other set. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [0, 2, 4, 6] + /// let c = a.subtracting(b) + /// // `c` is some permutation of `[1, 3]` + /// + /// - Parameter other: An arbitrary set of elements. + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public __consuming func subtracting(_ other: Self) -> Self { let builder = _root.subtracting(.top, .emptyPrefix, other._root) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift index 317dda3b..8641627a 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift @@ -10,6 +10,20 @@ //===----------------------------------------------------------------------===// extension PersistentSet { + /// Returns a new set with the elements that are either in this set or in + /// `other`, but not in both. + /// + /// var a: PersistentSet = [1, 2, 3, 4] + /// let b: PersistentSet = [0, 2, 4, 6] + /// let c = a.symmetricDifference(b) + /// // `c` is some permutation of `[0, 1, 3, 6]` + /// + /// - Parameter other: An arbitrary set of elements. + /// - Complexity: Expected complexity is O(`self.count` + `other.count`) in + /// the worst case, if `Element` properly implements hashing. + /// However, the implementation is careful to make the best use of + /// hash tree structure to minimize work when possible, e.g. by linking + /// parts of the input trees directly into the result. @inlinable public func symmetricDifference(_ other: __owned Self) -> Self { // FIXME: Do this with a structural merge. diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift index c6c87469..2767d8cc 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra union.swift @@ -9,6 +9,23 @@ // //===----------------------------------------------------------------------===// +/// Returns a new set with the elements of both this and the given set. +/// +/// var a: PersistentSet = [1, 2, 3, 4] +/// let b: PersistentSet = [0, 2, 4, 6] +/// let c = a.union(b) +/// // `c` is some permutation of `[0, 1, 2, 3, 4, 6]` +/// +/// For values that are members of both sets, the result set contains the +/// instances that were originally in `self`. (This matters if equal members +/// can be distinguished by comparing their identities, or by some other means.) +/// +/// - Parameter other: The set of elements to insert. +/// - Complexity: Expected complexity is O(`self.count` + `other.count`) in +/// the worst case, if `Element` properly implements hashing. +/// However, the implementation is careful to make the best use of +/// hash tree structure to minimize work when possible, e.g. by linking +/// parts of the input trees directly into the result. extension PersistentSet { @inlinable public func union(_ other: __owned Self) -> Self { diff --git a/Sources/_CollectionsUtilities/_FastMembershipCheckable.swift b/Sources/_CollectionsUtilities/_FastMembershipCheckable.swift index 4b9fa608..d652fade 100644 --- a/Sources/_CollectionsUtilities/_FastMembershipCheckable.swift +++ b/Sources/_CollectionsUtilities/_FastMembershipCheckable.swift @@ -11,7 +11,7 @@ /// A utility protocol for marking container types (not necessarily /// conforming to `Sequence` or `Collection`) that provide a -/// fast `contains` operation. +/// fast and non-destructive `contains` operation. public protocol _FastMembershipCheckable { // FIXME: Add as primary associated type on >=5.7 associatedtype Element: Equatable From 876177dbb5cd53ee0f2cb3884dab69286f934bc3 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 28 Sep 2022 18:38:14 -0700 Subject: [PATCH 11/18] [PersistentSet] Test & fix symmetricDifference --- ...rsistentSet+SetAlgebra symmetricDifference.swift | 4 +++- .../PersistentSet Tests.swift | 13 +++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift index 8641627a..56e9966f 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift @@ -27,6 +27,8 @@ extension PersistentSet { @inlinable public func symmetricDifference(_ other: __owned Self) -> Self { // FIXME: Do this with a structural merge. - self.subtracting(self.intersection(other)) + let a = self.subtracting(other) + let b = other.subtracting(self) + return a.union(b) } } diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index 1d90a922..bbc131ff 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -337,4 +337,17 @@ class PersistentSetTests: CollectionTestCase { } } } + + func test_symmetricDifference_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentSet(a) + let u = Set(a) + expectEqualSets(x.symmetricDifference(x), []) + withEverySubset("b", of: testItems) { b in + let y = PersistentSet(b) + let v = Set(b) + expectEqualSets(x.symmetricDifference(y), u.symmetricDifference(v)) + } + } + } } From 54b265ea5dc1f24c8a675e36a84c56f90ee2e0e3 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 28 Sep 2022 18:40:17 -0700 Subject: [PATCH 12/18] =?UTF-8?q?[PersistentSet]=20Don=E2=80=99t=20check?= =?UTF-8?q?=20underestimatedCount=20in=20is[Strict][Sub,Super]set=20implem?= =?UTF-8?q?entations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The input sequence may include duplicate items, which may break these shortcuts. --- .../PersistentSet+SetAlgebra isStrictSubset.swift | 3 --- .../PersistentSet+SetAlgebra isStrictSuperset.swift | 4 ---- .../PersistentSet/PersistentSet+SetAlgebra isSuperset.swift | 5 +---- 3 files changed, 1 insertion(+), 11 deletions(-) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift index 09919f73..0e2b7161 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift @@ -121,9 +121,6 @@ extension PersistentSet { public func isStrictSubset(of other: S) -> Bool where S.Element == Element { - if other.underestimatedCount > self.count { - return isSubset(of: other) - } // FIXME: Would making this a BitSet of seen positions be better? var seen: PersistentSet? = [] var isStrict = false diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift index 53f63e6e..d73d142d 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift @@ -92,7 +92,6 @@ extension PersistentSet { ) -> Bool where S.Element == Element { - if self.count < other.underestimatedCount { return false } if !other.allSatisfy({ self.contains($0) }) { return false } return !self.allSatisfy { other.contains($0) } } @@ -122,9 +121,6 @@ extension PersistentSet { public func isStrictSuperset(of other: S) -> Bool where S.Element == Element { - guard self.count >= other.underestimatedCount else { - return false - } // FIXME: Would making this a BitSet of seen positions be better? var seen: PersistentSet = [] for item in other { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift index 5d74547c..b0f5a4f1 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSuperset.swift @@ -79,9 +79,6 @@ extension PersistentSet { public func isSuperset(of other: S) -> Bool where S.Element == Element { - guard self.count >= other.underestimatedCount else { - return false - } - return other.allSatisfy { self.contains($0) } + other.allSatisfy { self.contains($0) } } } From 81acdb7f8d58ce7c01b6fca2220d806db629dd36 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 29 Sep 2022 15:55:02 -0700 Subject: [PATCH 13/18] [PersistentSet] Implement structural symmetricDifference I think this may be the last missing non-trivial algorithm for this module. --- .../Node/_Node+Primitive Replacement.swift | 12 + ..._Node+Structural symmetricDifference.swift | 232 ++++++++++++++++++ .../Node/_Node+Structural union.swift | 6 +- .../Node/_Node+Subtree Insertions.swift | 11 + ...ntSet+SetAlgebra symmetricDifference.swift | 8 +- .../PersistentSet Tests.swift | 9 +- 6 files changed, 267 insertions(+), 11 deletions(-) create mode 100644 Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift diff --git a/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift b/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift index 5aa40f9e..4acf88cb 100644 --- a/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift +++ b/Sources/PersistentCollections/Node/_Node+Primitive Replacement.swift @@ -10,6 +10,18 @@ //===----------------------------------------------------------------------===// extension _Node { + @inlinable + internal mutating func replaceItem( + at bucket: _Bucket, _ slot: _Slot, with item: Element + ) { + update { + assert($0.isCollisionNode || $0.itemMap.contains(bucket)) + assert($0.isCollisionNode || slot == $0.itemMap.slot(of: bucket)) + assert(!$0.isCollisionNode || slot.value < $0.collisionCount) + $0[item: slot] = item + } + } + @inlinable internal mutating func replaceChild( at bucket: _Bucket, with child: _Node diff --git a/Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift b/Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift new file mode 100644 index 00000000..89c8ad89 --- /dev/null +++ b/Sources/PersistentCollections/Node/_Node+Structural symmetricDifference.swift @@ -0,0 +1,232 @@ +//===----------------------------------------------------------------------===// +// +// 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 symmetricDifference( + _ level: _Level, + _ hashPrefix: _Hash, + _ other: _Node + ) -> Builder? { + guard self.count > 0 else { return .node(other, hashPrefix) } + guard other.count > 0 else { return nil } + return _symmetricDifference(level, hashPrefix, other) + } + + @inlinable + internal func _symmetricDifference( + _ level: _Level, + _ hashPrefix: _Hash, + _ other: _Node + ) -> Builder { + assert(self.count > 0 && other.count > 0) + + if self.raw.storage === other.raw.storage { + return .empty + } + if self.isCollisionNode || other.isCollisionNode { + return _symmetricDifference_slow(level, hashPrefix, other) + } + + return self.read { l in + other.read { r in + var result: Builder = .empty + + for (bucket, lslot) in l.itemMap { + let lp = l.itemPtr(at: lslot) + if r.itemMap.contains(bucket) { + let rslot = r.itemMap.slot(of: bucket) + let rp = r.itemPtr(at: rslot) + if lp.pointee.key != rp.pointee.key { + let h1 = _Hash(lp.pointee.key) + let h2 = _Hash(rp.pointee.key) + let child = _Node.build( + level: level.descend(), + item1: lp.pointee, h1, + item2: { $0.initialize(to: rp.pointee) }, h2) + result.addNewChildBranch(level, .node(child.top, h1)) + } + } + else if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + let rp = r.childPtr(at: rslot) + let h = _Hash(lp.pointee.key) + let child = rp.pointee + .removing2(level.descend(), lp.pointee.key, h)?.replacement + if let child = child { + result.addNewChildBranch(level, child) + } + else { + let child2 = rp.pointee.inserting(level.descend(), lp.pointee, h) + assert(child2.inserted) + result.addNewChildBranch(level, .node(child2.node, h)) + } + } + else { + let h = hashPrefix.appending(bucket, at: level) + result.addNewItem(level, lp.pointee, h) + } + } + + for (bucket, lslot) in l.childMap { + let lp = l.childPtr(at: lslot) + 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 child = lp.pointee + .removing2(level.descend(), rp.pointee.key, h)?.replacement + if let child = child { + result.addNewChildBranch(level, child) + } + else { + let child2 = lp.pointee.inserting(level.descend(), rp.pointee, h) + assert(child2.inserted) + result.addNewChildBranch(level, .node(child2.node, h)) + } + } + else if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + let hp = hashPrefix.appending(bucket, at: level) + let b = l[child: lslot]._symmetricDifference( + level.descend(), hp, r[child: rslot]) + result.addNewChildBranch(level, b) + } + else { + let h = hashPrefix.appending(bucket, at: level) + result.addNewChildBranch(level, .node(lp.pointee, h)) + } + } + + let seen = l.itemMap.union(l.childMap) + for (bucket, rslot) in r.itemMap { + guard !seen.contains(bucket) else { continue } + let h = hashPrefix.appending(bucket, at: level) + result.addNewItem(level, r[item: rslot], h) + } + for (bucket, rslot) in r.childMap { + guard !seen.contains(bucket) else { continue } + let h = hashPrefix.appending(bucket, at: level) + result.addNewChildBranch(level, .node(r[child: rslot], h)) + } + return result + } + } + } + + @inlinable @inline(never) + internal func _symmetricDifference_slow( + _ level: _Level, + _ hashPrefix: _Hash, + _ other: _Node + ) -> Builder { + switch (self.isCollisionNode, other.isCollisionNode) { + case (true, true): + return self._symmetricDifference_slow_both(level, hashPrefix, other) + case (true, false): + return self._symmetricDifference_slow_left(level, hashPrefix, other) + case (false, _): + return other._symmetricDifference_slow_left(level, hashPrefix, self) + } + } + + @inlinable + internal func _symmetricDifference_slow_both( + _ level: _Level, + _ hashPrefix: _Hash, + _ other: _Node + ) -> Builder { + 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 .node(node, l.collisionHash) + } + var result: Builder = .empty + let ritems = r.reverseItems + for ls: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { + let lp = l.itemPtr(at: ls) + let include = !ritems.contains(where: { $0.key == lp.pointee.key }) + if include { + result.addNewCollision(lp.pointee, l.collisionHash) + } + } + // FIXME: Consider remembering slots of shared items in r by + // caching them in a bitset. + let litems = l.reverseItems + for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { + let rp = r.itemPtr(at: rs) + let include = !litems.contains(where: { $0.key == rp.pointee.key }) + if include { + result.addNewCollision(rp.pointee, r.collisionHash) + } + } + return result + } + } + } + + @inlinable + internal func _symmetricDifference_slow_left( + _ level: _Level, + _ hashPrefix: _Hash, + _ other: _Node + ) -> Builder { + // `self` is a collision node on a compressed path. The other tree might + // have the same set of collisions, just expanded a bit deeper. + read { l in + other.read { r in + assert(l.isCollisionNode && !r.isCollisionNode) + let bucket = l.collisionHash[level] + if r.itemMap.contains(bucket) { + let rslot = r.itemMap.slot(of: bucket) + let rp = r.itemPtr(at: rslot) + let litems = l.reverseItems + if let li = litems.firstIndex(where: { $0.key == rp.pointee.key }) { + if l.itemCount == 2 { + var node = other.copy() + node.replaceItem(at: bucket, rslot, with: litems[1 &- li]) + return .node(node, l.collisionHash) + } + let lslot = _Slot(litems.count &- 1 &- li) + var child = self.copy() + _ = child.removeItem(at: lslot, .invalid) + var node = other.copy(withFreeSpace: _Node.spaceForSpawningChild) + _ = node.removeItem(at: rslot, bucket) + node.insertChild(child, bucket) + return .node(node, hashPrefix) + } + var node = other.copy(withFreeSpace: _Node.spaceForSpawningChild) + let item = node.removeItem(at: rslot, bucket) + let child = self.copyNodeAndAppendCollision { + $0.initialize(to: item) + } + node.insertChild(child.node, bucket) + return .node(node, hashPrefix) + } + if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + let rp = r.childPtr(at: rslot) + let hp = hashPrefix.appending(bucket, at: level) + let child = rp.pointee._symmetricDifference( + level.descend(), hp, self) + return other.replacingChild(level, hp, rslot, with: child) + } + var node = other.copy(withFreeSpace: _Node.spaceForNewChild) + node.insertChild(self, bucket) + return .node(node, hashPrefix) + } + } + } +} diff --git a/Sources/PersistentCollections/Node/_Node+Structural union.swift b/Sources/PersistentCollections/Node/_Node+Structural union.swift index 4500575a..7d129c0c 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural union.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural union.swift @@ -139,15 +139,13 @@ extension _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 { + for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { + let p = r.itemPtr(at: rs) if !litems.contains(where: { $0.key == p.pointee.key }) { _ = node.ensureUniqueAndAppendCollision( isUnique: copied, p.pointee) copied = true } - p -= 1 } return (copied, node) } diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift index b80312be..bc4bbabb 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift @@ -210,6 +210,17 @@ extension _Node { self.count &+= 1 } + @inlinable @inline(__always) + internal func copyNodeAndInsertItem( + at bucket: _Bucket, + _ item: __owned Element + ) -> _Node { + let slot = read { $0.itemMap.slot(of: bucket) } + return copyNodeAndInsertItem(at: bucket, itemSlot: slot) { + $0.initialize(to: item) + } + } + @inlinable @inline(never) internal func copyNodeAndInsertItem( at bucket: _Bucket, diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift index 56e9966f..49083c2d 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra symmetricDifference.swift @@ -26,9 +26,9 @@ extension PersistentSet { /// parts of the input trees directly into the result. @inlinable public func symmetricDifference(_ other: __owned Self) -> Self { - // FIXME: Do this with a structural merge. - let a = self.subtracting(other) - let b = other.subtracting(self) - return a.union(b) + let branch = _root.symmetricDifference(.top, .emptyPrefix, other._root) + guard let branch = branch else { return self } + let root = branch.finalize(.top) + return PersistentSet(_new: root) } } diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index bbc131ff..03dff28c 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -209,6 +209,9 @@ class PersistentSetTests: CollectionTestCase { RawCollider(6, "ACAEB"), RawCollider(7, "ACAEB"), RawCollider(8, "ACAEB"), +// RawCollider(9, "ACAEB"), +// RawCollider(10, "ADAD"), +// RawCollider(11, "ACC"), ] func test_isEqual_Self_exhaustive() { @@ -315,7 +318,7 @@ class PersistentSetTests: CollectionTestCase { } } - func test_filter_exhaustive() { + func test_filter_Self_exhaustive() { withEverySubset("a", of: testItems) { a in let x = PersistentSet(a) withEverySubset("b", of: a) { b in @@ -325,7 +328,7 @@ class PersistentSetTests: CollectionTestCase { } } - func test_union_exhaustive() { + func test_union_Self_exhaustive() { withEverySubset("a", of: testItems) { a in let x = PersistentSet(a) let u = Set(a) @@ -338,7 +341,7 @@ class PersistentSetTests: CollectionTestCase { } } - func test_symmetricDifference_exhaustive() { + func test_symmetricDifference_Self_exhaustive() { withEverySubset("a", of: testItems) { a in let x = PersistentSet(a) let u = Set(a) From 19c9f282c93e86d96341de76317e579a55ca86ab Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 29 Sep 2022 17:34:55 -0700 Subject: [PATCH 14/18] Delete _FastMembershipCheckable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We don’t actually need this, as `_customContainsEquatableElement` returning non-nil is a perfectly suitable indication that containment checking is fast. --- .../BitCollections/BitSet/BitSet+Extras.swift | 2 - .../OrderedSet/OrderedSet+Extras.swift | 14 ----- .../PersistentDictionary+Keys.swift | 2 - .../PersistentSet+SetAlgebra basics.swift | 4 +- ...sistentSet+SetAlgebra isStrictSubset.swift | 42 ++++---------- ...stentSet+SetAlgebra isStrictSuperset.swift | 44 +++++--------- .../PersistentSet+SetAlgebra isSubset.swift | 58 ++++--------------- .../_FastMembershipCheckable.swift | 27 --------- 8 files changed, 38 insertions(+), 155 deletions(-) delete mode 100644 Sources/OrderedCollections/OrderedSet/OrderedSet+Extras.swift delete mode 100644 Sources/_CollectionsUtilities/_FastMembershipCheckable.swift diff --git a/Sources/BitCollections/BitSet/BitSet+Extras.swift b/Sources/BitCollections/BitSet/BitSet+Extras.swift index 3333cbd3..7a4a1caf 100644 --- a/Sources/BitCollections/BitSet/BitSet+Extras.swift +++ b/Sources/BitCollections/BitSet/BitSet+Extras.swift @@ -11,8 +11,6 @@ import _CollectionsUtilities -extension BitSet: _FastMembershipCheckable {} - extension BitSet { /// Creates a new empty bit set with enough storage capacity to store values /// up to the given maximum value without reallocating storage. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Extras.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Extras.swift deleted file mode 100644 index 4efd0309..00000000 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Extras.swift +++ /dev/null @@ -1,14 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// 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 -// -//===----------------------------------------------------------------------===// - -import _CollectionsUtilities - -extension OrderedSet: _FastMembershipCheckable {} diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift index 36e7f10e..3c1e2029 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift @@ -67,9 +67,7 @@ extension PersistentDictionary.Keys: Sequence { ) -> Bool? { _base._root.containsKey(.top, element, _Hash(element)) } -} -extension PersistentDictionary.Keys: _FastMembershipCheckable { @inlinable public func contains(_ element: Element) -> Bool { _base._root.containsKey(.top, element, _Hash(element)) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift index 11e6da28..1986ecb1 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift @@ -11,14 +11,12 @@ import _CollectionsUtilities -extension PersistentSet: _FastMembershipCheckable { +extension PersistentSet: SetAlgebra { @inlinable public func contains(_ item: Element) -> Bool { _root.containsKey(.top, item, _Hash(item)) } -} -extension PersistentSet: SetAlgebra { @discardableResult @inlinable public mutating func insert( diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift index 0e2b7161..83691429 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSubset.swift @@ -66,36 +66,6 @@ extension PersistentSet { return isSubset(of: other) } - /// Returns a Boolean value that indicates whether the set is a strict subset - /// of the given set. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: PersistentSet = [1, 2, 3, 4] - /// let b: PersistentSet = [4, 2, 1] - /// b.isStrictSubset(of: a) // true - /// - /// - Parameter other: A sequence with a fast `contains` implementation, - /// some of whose elements may appear more than once. - /// - /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: In the worst case, this makes `self.count` - /// calls to `other.contains`, followed by *n* calls to `self.contains` - /// where *n* is the length of the sequence. - @inlinable - public func isStrictSubset( - of other: S - ) -> Bool - where S.Element == Element { - guard self.isSubset(of: other) else { return false } - return !other.allSatisfy { self.contains($0) } - } - - /// Returns a Boolean value that indicates whether the set is a strict subset /// of the given set. /// @@ -121,6 +91,18 @@ extension PersistentSet { public func isStrictSubset(of other: S) -> Bool where S.Element == Element { + var it = self.makeIterator() + guard let first = it.next() else { + return other.contains(where: { _ in true }) + } + if let match = other._customContainsEquatableElement(first) { + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return !other.allSatisfy { self.contains($0) } + } + // FIXME: Would making this a BitSet of seen positions be better? var seen: PersistentSet? = [] var isStrict = false diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift index d73d142d..160ac789 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isStrictSuperset.swift @@ -66,36 +66,6 @@ extension PersistentSet { return other._base._root.isSubset(.top, of: self._root) } - /// Returns a Boolean value that indicates whether the set is a strict - /// superset of the given set. - /// - /// Set *A* is a strict subset of another set *B* if every member of *A* is - /// also a member of *B* and *B* contains at least one element that is not a - /// member of *A*. (Ignoring the order the elements appear in the sets.) - /// - /// let a: PersistentSet = [1, 2, 3, 4] - /// let b: PersistentSet = [4, 2, 1] - /// a.isStrictSuperset(of: b.unordered) // true - /// - /// - Parameter other: A sequence with a fast `contains` implementation, - /// some of whose elements may appear more than once. - /// - /// - Returns: `true` if `self` is a strict subset of `other`; otherwise, - /// `false`. - /// - /// - Complexity: In the worst case, this makes `other.count` - /// calls to `self.contains`, followed by *n* calls to `other.contains` - /// where *n* is the length of the sequence. - @inlinable - public func isStrictSuperset( - of other: S - ) -> Bool - where S.Element == Element - { - if !other.allSatisfy({ self.contains($0) }) { return false } - return !self.allSatisfy { other.contains($0) } - } - /// Returns a Boolean value that indicates whether the set is a strict /// superset of the given set. /// @@ -121,6 +91,20 @@ extension PersistentSet { public func isStrictSuperset(of other: S) -> Bool where S.Element == Element { + var it = self.makeIterator() + guard let first = it.next() else { + return other.contains(where: { _ in true }) + } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard other.allSatisfy({ self.contains($0) }) else { return false } + guard match else { return true } + while let item = it.next() { + guard other.contains(item) else { return true } + } + return false + } + // FIXME: Would making this a BitSet of seen positions be better? var seen: PersistentSet = [] for item in other { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift index 5231a7be..3a4d7958 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra isSubset.swift @@ -60,53 +60,6 @@ extension PersistentSet { self._root.isSubset(.top, of: other._base._root) } - /// Returns a Boolean value that indicates whether this set is a subset of - /// the given set. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*, ignoring the order they appear in the two sets. - /// - /// let a: PersistentSet = [1, 2, 3, 4] - /// let b: PersistentSet = [4, 2, 1] - /// b.isSubset(of: a) // true - /// - /// - Parameter other: A container with a fast `contains` implementation. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: O(`self.count`) calls to `other.contains`. - @inlinable - public func isSubset( - of other: S - ) -> Bool - where S.Element == Element { - self.allSatisfy { other.contains($0) } - } - - /// Returns a Boolean value that indicates whether this set is a subset of - /// the given sequence. - /// - /// Set *A* is a subset of another set *B* if every member of *A* is also a - /// member of *B*, ignoring the order they appear in the two sets. - /// - /// let a: PersistentSet = [1, 2, 3, 4] - /// let b: PersistentSet = [4, 2, 1] - /// b.isSubset(of: a) // true - /// - /// - Parameter other: A sequence with a fast `contains` implementation, - /// some of whose elements may appear more than once. - /// - /// - Returns: `true` if the set is a subset of `other`; otherwise, `false`. - /// - /// - Complexity: O(`self.count`) calls to `other.contains`. - @inlinable - public func isSubset( - of other: S - ) -> Bool - where S.Element == Element { - self.allSatisfy { other.contains($0) } - } - /// Returns a Boolean value that indicates whether this set is a subset of /// the given sequence. /// @@ -130,6 +83,17 @@ extension PersistentSet { public func isSubset(of other: S) -> Bool where S.Element == Element { + var it = self.makeIterator() + guard let first = it.next() else { return true } + if let match = other._customContainsEquatableElement(first) { + // Fast path: the sequence has fast containment checks. + guard match else { return false } + while let item = it.next() { + guard other.contains(item) else { return false } + } + return true + } + // FIXME: Would making this a BitSet of seen positions be better? var seen: PersistentSet = [] for item in other { diff --git a/Sources/_CollectionsUtilities/_FastMembershipCheckable.swift b/Sources/_CollectionsUtilities/_FastMembershipCheckable.swift deleted file mode 100644 index d652fade..00000000 --- a/Sources/_CollectionsUtilities/_FastMembershipCheckable.swift +++ /dev/null @@ -1,27 +0,0 @@ -//===----------------------------------------------------------------------===// -// -// 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 -// -//===----------------------------------------------------------------------===// - -/// A utility protocol for marking container types (not necessarily -/// conforming to `Sequence` or `Collection`) that provide a -/// fast and non-destructive `contains` operation. -public protocol _FastMembershipCheckable { - // FIXME: Add as primary associated type on >=5.7 - associatedtype Element: Equatable - - /// Returns a Boolean value that indicates whether the given element exists in `self`. - /// - /// - Performance: O(log(*n*)) or better, where *n* is the size - /// of `self` (for some definition of "size"). - func contains(_ item: Element) -> Bool -} - -extension Set: _FastMembershipCheckable {} -extension Dictionary.Keys: _FastMembershipCheckable {} From 8e3e205954dada0e874e5a112e42ffd1fc6bf714 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 29 Sep 2022 17:54:08 -0700 Subject: [PATCH 15/18] [PersistentCollections] Add missing import --- Sources/PersistentCollections/Node/_Bitmap.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Sources/PersistentCollections/Node/_Bitmap.swift b/Sources/PersistentCollections/Node/_Bitmap.swift index 199b61b9..051a7732 100644 --- a/Sources/PersistentCollections/Node/_Bitmap.swift +++ b/Sources/PersistentCollections/Node/_Bitmap.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + /// A set of `_Bucket` values, represented by a 32-bit wide bitset. @usableFromInline @frozen From 6dfad714a147bc1640db12cecade34a17600cc36 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 30 Sep 2022 12:19:40 -0700 Subject: [PATCH 16/18] =?UTF-8?q?[PersistentCollections]=20=5FNode.update?= =?UTF-8?q?=20=E2=86=92=20=5FNode.updateValue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit To prevent confusion with the low-level _Node.update method. This also switches PersistentSet.insert to use `_Node.insert` instead of `_Node.updateValue`, to fix its semantics. `insert` no longer invalidates indices when the new member already exists in the collection. --- .../Node/_Node+Subtree Insertions.swift | 7 ++++--- .../Node/_Node+Subtree Modify.swift | 2 +- .../PersistentDictionary/PersistentDictionary.swift | 10 +++++++--- .../PersistentSet+SetAlgebra basics.swift | 7 +++---- 4 files changed, 15 insertions(+), 11 deletions(-) diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift index bc4bbabb..876dc278 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift @@ -120,9 +120,9 @@ extension _Node { } @inlinable - internal mutating func update( + internal mutating func updateValue( _ level: _Level, - _ key: Key, + forKey key: Key, _ hash: _Hash, _ inserter: (UnsafeMutablePointer) -> Void ) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) { @@ -159,7 +159,8 @@ extension _Node { case .descend(_, let slot): ensureUnique(isUnique: isUnique) let r = update { - $0[child: slot].update(level.descend(), key, hash, inserter) + $0[child: slot].updateValue( + level.descend(), forKey: key, hash, inserter) } if r.inserted { count &+= 1 } return r diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift b/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift index a46207c6..70440470 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift @@ -127,7 +127,7 @@ extension _Node { _finalizeRemoval(.top, state.hash, at: state.path) case (false, true): // Insertion - let r = update(.top, state.key, state.hash) { + let r = updateValue(.top, forKey: state.key, state.hash) { $0.initialize(to: (state.key, state.value.unsafelyUnwrapped)) } assert(r.inserted) diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift index 053a0a3f..bd2d3211 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift @@ -279,7 +279,9 @@ extension PersistentDictionary { _ value: __owned Value, forKey key: Key ) -> Value? { let hash = _Hash(key) - let r = _root.update(.top, key, hash) { $0.initialize(to: (key, value)) } + let r = _root.updateValue(.top, forKey: key, hash) { + $0.initialize(to: (key, value)) + } _invalidateIndices() if r.inserted { return nil } return _Node.UnsafeHandle.update(r.leaf) { @@ -296,7 +298,9 @@ extension PersistentDictionary { _ value: __owned Value, forKey key: Key ) -> Bool { let hash = _Hash(key) - let r = _root.update(.top, key, hash) { $0.initialize(to: (key, value)) } + let r = _root.updateValue(.top, forKey: key, hash) { + $0.initialize(to: (key, value)) + } if r.inserted { return true } _Node.UnsafeHandle.update(r.leaf) { $0[item: r.slot].value = value @@ -328,7 +332,7 @@ extension PersistentDictionary { with body: (inout Value) throws -> R ) rethrows -> R { let hash = _Hash(key) - let r = _root.update(.top, key, hash) { + let r = _root.updateValue(.top, forKey: key, hash) { $0.initialize(to: (key, defaultValue())) } return try _Node.UnsafeHandle.update(r.leaf) { diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift index 1986ecb1..f872c3bc 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift @@ -24,7 +24,7 @@ extension PersistentSet: SetAlgebra { ) -> (inserted: Bool, memberAfterInsert: Element) { let hash = _Hash(newMember) _invalidateIndices() - let r = _root.update(.top, newMember, hash) { + let r = _root.insert(.top, newMember, hash) { $0.initialize(to: (newMember, ())) } if r.inserted { @@ -39,13 +39,12 @@ extension PersistentSet: SetAlgebra { @inlinable internal mutating func _insert(_ newMember: __owned Element) -> Bool { let hash = _Hash(newMember) - let r = _root.update(.top, newMember, hash) { + let r = _root.insert(.top, newMember, hash) { $0.initialize(to: (newMember, ())) } return r.inserted } - @discardableResult @inlinable public mutating func remove(_ member: Element) -> Element? { @@ -58,7 +57,7 @@ extension PersistentSet: SetAlgebra { @inlinable public mutating func update(with newMember: __owned Element) -> Element? { let hash = _Hash(newMember) - let r = _root.update(.top, newMember, hash) { + let r = _root.updateValue(.top, forKey: newMember, hash) { $0.initialize(to: (newMember, ())) } if r.inserted { return nil } From 963011b1e5af5b3b4259fbb7f25bb83476da645a Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 30 Sep 2022 12:20:12 -0700 Subject: [PATCH 17/18] =?UTF-8?q?[PersistentSet]=20insert:=20Don=E2=80=99t?= =?UTF-8?q?=20invalidate=20indices=20when=20the=20inserted=20member=20alre?= =?UTF-8?q?ady=20exists?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../PersistentSet/PersistentSet+SetAlgebra basics.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift index f872c3bc..391cfa96 100644 --- a/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift +++ b/Sources/PersistentCollections/PersistentSet/PersistentSet+SetAlgebra basics.swift @@ -23,11 +23,11 @@ extension PersistentSet: SetAlgebra { _ newMember: __owned Element ) -> (inserted: Bool, memberAfterInsert: Element) { let hash = _Hash(newMember) - _invalidateIndices() let r = _root.insert(.top, newMember, hash) { $0.initialize(to: (newMember, ())) } if r.inserted { + _invalidateIndices() return (true, newMember) } return _Node.UnsafeHandle.read(r.leaf) { From f71ebd9494b3b0b8c1450017f8c30fb61e4dcc37 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Fri, 30 Sep 2022 19:55:04 -0700 Subject: [PATCH 18/18] [PersistentDictionary] Implement structural merge operations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merging is best done in-place, as merging a non-empty dictionary will always mutate the dictionary, so we don’t have to tiptoe around uniqueness issues. (The union operation on PersistentSet is vaguely similar, but not quite — unlike with merge, union is able directly link shared subtrees into the result. However, a similar optimization may be worthwhile for symmetricDifference.) --- .../Node/_Node+Structural merge.swift | 322 ++++++++++++++++++ .../Node/_Node+Structural union.swift | 50 ++- .../Node/_Node+Subtree Insertions.swift | 7 +- .../PersistentDictionary+Merge.swift | 20 +- .../Utilities/LifetimeTracker.swift | 6 + .../PersistentCollections Fixtures.swift | 83 ++++- .../PersistentDictionary Tests.swift | 49 +++ .../PersistentSet Tests.swift | 21 +- 8 files changed, 523 insertions(+), 35 deletions(-) create mode 100644 Sources/PersistentCollections/Node/_Node+Structural merge.swift diff --git a/Sources/PersistentCollections/Node/_Node+Structural merge.swift b/Sources/PersistentCollections/Node/_Node+Structural merge.swift new file mode 100644 index 00000000..8548ee86 --- /dev/null +++ b/Sources/PersistentCollections/Node/_Node+Structural merge.swift @@ -0,0 +1,322 @@ +//===----------------------------------------------------------------------===// +// +// 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 mutating func merge( + _ level: _Level, + _ hashPrefix: _Hash, + _ other: _Node, + _ combine: (Value, Value) throws -> Value + ) rethrows { + guard other.count > 0 else { return } + guard self.count > 0 else { + self = other + return + } + if level.isAtRoot, self.hasSingletonItem { + // In this special case, the root node may turn into a collision node + // during the merge process. Prevent this from causing issues below by + // handling it up front. + var copy = other + try self.read { l in + let lp = l.itemPtr(at: .zero) + let res = copy.updateValue( + level, forKey: lp.pointee.key, _Hash(lp.pointee.key) + ) { + $0.initialize(to: lp.pointee) + } + if !res.inserted { + try UnsafeHandle.update(res.leaf) { + let p = $0.itemPtr(at: res.slot) + p.pointee.value = try combine(lp.pointee.value, p.pointee.value) + } + } + } + self = copy + return + } + + try _merge(level, hashPrefix, other, combine) + } + + @inlinable + internal mutating func _merge( + _ level: _Level, + _ hashPrefix: _Hash, + _ other: _Node, + _ combine: (Value, Value) throws -> Value + ) rethrows { + // Note: don't check storage identities -- we do need to merge the contents + // of identical nodes. + + if self.isCollisionNode || other.isCollisionNode { + try _merge_slow(level, hashPrefix, other, combine) + return + } + + var isUnique = self.isUnique() + + try other.read { r in + let (originalItems, originalChildren) = self.read { + ($0.itemMap, $0.childMap) + } + + for (bucket, _) in originalItems { + assert(!isCollisionNode) + if r.itemMap.contains(bucket) { + let rslot = r.itemMap.slot(of: bucket) + let rp = r.itemPtr(at: rslot) + let lslot = self.read { $0.itemMap.slot(of: bucket) } + let conflict = self.read { $0[item: lslot].key == rp.pointee.key } + if conflict { + self.ensureUnique(isUnique: isUnique) + try self.update { + let p = $0.itemPtr(at: lslot) + p.pointee.value = try combine(p.pointee.value, rp.pointee.value) + } + } else { + _ = self.ensureUniqueAndSpawnChild( + isUnique: isUnique, + level: level, + replacing: bucket, + itemSlot: lslot, + newHash: _Hash(rp.pointee.key), + { $0.initialize(to: rp.pointee) }) + // If we hadn't handled the singleton root node case above, + // then this call would sometimes turn `self` into a collision + // node on a compressed path, causing mischief. + assert(!self.isCollisionNode) + } + isUnique = true + } + else if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + let rp = r.childPtr(at: rslot) + + self.ensureUnique( + isUnique: isUnique, withFreeSpace: _Node.spaceForSpawningChild) + let item = self.removeItem(at: bucket) + var child = rp.pointee + let r = child.updateValue( + level.descend(), forKey: item.key, _Hash(item.key) + ) { + $0.initialize(to: item) + } + if !r.inserted { + try UnsafeHandle.update(r.leaf) { + let p = $0.itemPtr(at: r.slot) + p.pointee.value = try combine(item.value, p.pointee.value) + } + } + self.insertChild(child, bucket) + isUnique = true + } + } + + for (bucket, _) in originalChildren { + assert(!isCollisionNode) + let lslot = self.read { $0.childMap.slot(of: bucket) } + + if r.itemMap.contains(bucket) { + let rslot = r.itemMap.slot(of: bucket) + let rp = r.itemPtr(at: rslot) + self.ensureUnique(isUnique: isUnique) + let h = _Hash(rp.pointee.key) + let res = self.update { l in + l[child: lslot].updateValue( + level.descend(), forKey: rp.pointee.key, h + ) { + $0.initialize(to: rp.pointee) + } + } + if res.inserted { + self.count &+= 1 + } else { + try UnsafeHandle.update(res.leaf) { + let p = $0.itemPtr(at: res.slot) + p.pointee.value = try combine(p.pointee.value, rp.pointee.value) + } + } + isUnique = true + } + else if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + self.ensureUnique(isUnique: isUnique) + try self.update { l in + try l[child: lslot].merge( + level.descend(), + hashPrefix.appending(bucket, at: level), + r[child: rslot], + combine) + } + isUnique = true + } + } + + assert(!self.isCollisionNode) + + /// Add buckets in `other` that we haven't processed above. + let seen = self.read { l in l.itemMap.union(l.childMap) } + for (bucket, _) in r.itemMap.subtracting(seen) { + let rslot = r.itemMap.slot(of: bucket) + self.ensureUniqueAndInsertItem( + isUnique: isUnique, r[item: rslot], at: bucket) + isUnique = true + } + for (bucket, _) in r.childMap.subtracting(seen) { + let rslot = r.childMap.slot(of: bucket) + self.ensureUnique( + isUnique: isUnique, withFreeSpace: _Node.spaceForNewChild) + self.insertChild(r[child: rslot], bucket) + isUnique = true + } + + assert(isUnique) + } + } + + @inlinable @inline(never) + internal mutating func _merge_slow( + _ level: _Level, + _ hashPrefix: _Hash, + _ other: _Node, + _ combine: (Value, Value) throws -> Value + ) rethrows { + let lc = self.isCollisionNode + let rc = other.isCollisionNode + if lc && rc { + guard self.collisionHash == other.collisionHash else { + self = _Node.build( + level: level, + child1: self, self.collisionHash, + child2: other, other.collisionHash) + return + } + var isUnique = self.isUnique() + return try other.read { r in + let originalItemCount = self.count + for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { + let rp = r.itemPtr(at: rs) + let lslot = self.read { l in + let litems = l.reverseItems + return litems + .suffix(originalItemCount) + .firstIndex { $0.key == rp.pointee.key } + .map { _Slot(litems.count &- 1 &- $0) } + } + if let lslot = lslot { + self.ensureUnique(isUnique: isUnique) + try self.update { + let p = $0.itemPtr(at: lslot) + p.pointee.value = try combine(p.pointee.value, rp.pointee.value) + } + } else { + _ = self.ensureUniqueAndAppendCollision( + isUnique: isUnique, rp.pointee) + } + isUnique = true + } + return + } + } + + // 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 try other.read { r in + let bucket = self.collisionHash[level] + 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 res = self.updateValue( + level.descend(), forKey: rp.pointee.key, h + ) { + $0.initialize(to: rp.pointee) + } + if !res.inserted { + try UnsafeHandle.update(res.leaf) { + let p = $0.itemPtr(at: res.slot) + p.pointee.value = try combine(p.pointee.value, rp.pointee.value) + } + } + self = other._copyNodeAndReplaceItemWithNewChild( + level: level, self, at: bucket, itemSlot: rslot) + return + } + + if r.childMap.contains(bucket) { + let rslot = r.childMap.slot(of: bucket) + let h = hashPrefix.appending(bucket, at: level) + try self._merge(level.descend(), h, r[child: rslot], combine) + var node = other.copy() + _ = node.replaceChild(at: bucket, rslot, with: self) + self = node + return + } + + var node = other.copy(withFreeSpace: _Node.spaceForNewChild) + node.insertChild(self, bucket) + self = node + return + } + } + + assert(rc) + let isUnique = self.isUnique() + // `other` is a collision node on a compressed path. + return try other.read { r in + let bucket = r.collisionHash[level] + if self.read({ $0.itemMap.contains(bucket) }) { + self.ensureUnique( + isUnique: isUnique, withFreeSpace: _Node.spaceForSpawningChild) + let item = self.removeItem(at: bucket) + let h = _Hash(item.key) + var copy = other + let res = copy.updateValue(level.descend(), forKey: item.key, h) { + $0.initialize(to: item) + } + if !res.inserted { + try UnsafeHandle.update(res.leaf) { + let p = $0.itemPtr(at: res.slot) + p.pointee.value = try combine(item.value, p.pointee.value) + } + } + assert(self.count > 0) // Singleton case handled up front above + self.insertChild(copy, bucket) + return + } + if self.read({ $0.childMap.contains(bucket) }) { + self.ensureUnique(isUnique: isUnique) + let delta = try self.update { l in + let lslot = l.childMap.slot(of: bucket) + let h = hashPrefix.appending(bucket, at: level) + let lchild = l.childPtr(at: lslot) + let origCount = lchild.pointee.count + try lchild.pointee._merge(level.descend(), h, other, combine) + return lchild.pointee.count &- origCount + } + assert(delta >= 0) + self.count &+= delta + return + } + self.ensureUnique( + isUnique: isUnique, withFreeSpace: _Node.spaceForNewChild) + self.insertChild(other, bucket) + return + } + } +} diff --git a/Sources/PersistentCollections/Node/_Node+Structural union.swift b/Sources/PersistentCollections/Node/_Node+Structural union.swift index 7d129c0c..01b0de64 100644 --- a/Sources/PersistentCollections/Node/_Node+Structural union.swift +++ b/Sources/PersistentCollections/Node/_Node+Structural union.swift @@ -18,7 +18,35 @@ extension _Node { ) -> (copied: Bool, node: _Node) { guard self.count > 0 else { return (true, other) } guard other.count > 0 else { return (false, self) } + if level.isAtRoot, self.hasSingletonItem { + // In this special case, the root node may turn into a collision node + // during the merge process. Prevent this from causing issues below by + // handling it up front. + return self.read { l in + let lp = l.itemPtr(at: .zero) + var copy = other + let r = copy.updateValue( + level, forKey: lp.pointee.key, _Hash(lp.pointee.key) + ) { + $0.initialize(to: lp.pointee) + } + if !r.inserted { + UnsafeHandle.update(r.leaf) { + $0[item: r.slot] = lp.pointee + } + } + return (true, copy) + } + } + return _union(level, hashPrefix, other) + } + @inlinable + internal func _union( + _ level: _Level, + _ hashPrefix: _Hash, + _ other: _Node + ) -> (copied: Bool, node: _Node) { if self.raw.storage === other.raw.storage { return (false, self) } @@ -33,6 +61,7 @@ extension _Node { var copied = false for (bucket, lslot) in l.itemMap { + assert(!node.isCollisionNode) if r.itemMap.contains(bucket) { let rslot = r.itemMap.slot(of: bucket) let lp = l.itemPtr(at: lslot) @@ -49,6 +78,10 @@ extension _Node { itemSlot: slot, newHash: _Hash(rp.pointee.key), { $0.initialize(to: rp.pointee) }) + // If we hadn't handled the singleton root node case above, + // then this call would sometimes turn `node` into a collision + // node on a compressed path, causing mischief. + assert(!node.isCollisionNode) copied = true } } @@ -66,6 +99,7 @@ extension _Node { } for (bucket, lslot) in l.childMap { + assert(!node.isCollisionNode) if r.itemMap.contains(bucket) { let rslot = r.itemMap.slot(of: bucket) let rp = r.itemPtr(at: rslot) @@ -82,7 +116,7 @@ extension _Node { } else if r.childMap.contains(bucket) { let rslot = r.childMap.slot(of: bucket) - let child = l[child: lslot].union( + let child = l[child: lslot]._union( level.descend(), hashPrefix.appending(bucket, at: level), r[child: rslot]) @@ -97,8 +131,11 @@ extension _Node { } } + assert(!node.isCollisionNode) + /// Add buckets in `other` that we haven't processed above. let seen = l.itemMap.union(l.childMap) + for (bucket, _) in r.itemMap.subtracting(seen) { let rslot = r.itemMap.slot(of: bucket) node.ensureUniqueAndInsertItem( @@ -181,7 +218,7 @@ extension _Node { 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]) + let res = self._union(level.descend(), h, r[child: rslot]) var node = other.copy() let delta = node.replaceChild(at: bucket, rslot, with: res.node) assert(delta >= 0) @@ -202,12 +239,7 @@ extension _Node { let bucket = r.collisionHash[level] if l.itemMap.contains(bucket) { let lslot = l.itemMap.slot(of: bucket) - let lp = l.itemPtr(at: lslot) - if l.hasSingletonItem { - let hash = _Hash(lp.pointee.key) - let replacement = other.inserting(level, lp.pointee, hash) - return (true, replacement.node) - } + assert(!l.hasSingletonItem) // Handled up front above let node = self.copyNodeAndPushItemIntoNewChild( level: level, other, @@ -218,7 +250,7 @@ extension _Node { if l.childMap.contains(bucket) { let lslot = l.childMap.slot(of: bucket) let h = hashPrefix.appending(bucket, at: level) - let child = l[child: lslot].union(level.descend(), h, other) + let child = l[child: lslot]._union(level.descend(), h, other) guard child.copied else { return (false, self) } var node = self.copy() let delta = node.replaceChild(at: bucket, lslot, with: child.node) diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift index 876dc278..845f9938 100644 --- a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift +++ b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift @@ -486,7 +486,12 @@ extension _Node { let item = removeItem(at: itemSlot, bucket) let hash = _Hash(item.key) let r = newChild.inserting(level.descend(), item, hash) - insertChild(r.node, bucket) + if self.count == 0, r.node.isCollisionNode { + // Compression + self = newChild + } else { + insertChild(r.node, bucket) + } } @inlinable @inline(never) diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift index 410ec581..d50533f8 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift @@ -10,12 +10,20 @@ //===----------------------------------------------------------------------===// extension PersistentDictionary { + @inlinable + public mutating func merge( + _ keysAndValues: Self, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows { + _invalidateIndices() + try _root.merge(.top, .emptyPrefix, keysAndValues._root, combine) + } + @inlinable public mutating func merge( _ keysAndValues: __owned S, uniquingKeysWith combine: (Value, Value) throws -> Value ) rethrows where S.Element == (Key, Value) { - // FIXME: Do a structural merge for (key, value) in keysAndValues { try self.updateValue(forKey: key) { target in if let old = target { @@ -38,6 +46,16 @@ extension PersistentDictionary { uniquingKeysWith: combine) } + @inlinable + public func merging( + _ other: Self, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows -> Self { + var copy = self + try copy.merge(other, uniquingKeysWith: combine) + return copy + } + @inlinable public func merging( _ other: __owned S, diff --git a/Sources/_CollectionsTestSupport/Utilities/LifetimeTracker.swift b/Sources/_CollectionsTestSupport/Utilities/LifetimeTracker.swift index e920a675..682dc04d 100644 --- a/Sources/_CollectionsTestSupport/Utilities/LifetimeTracker.swift +++ b/Sources/_CollectionsTestSupport/Utilities/LifetimeTracker.swift @@ -40,6 +40,12 @@ public class LifetimeTracker { public func instances(for items: S) -> [LifetimeTracked] { return items.map { LifetimeTracked($0, for: self) } } + + public func instances( + for items: S, by transform: (S.Element) -> T + ) -> [LifetimeTracked] { + items.map { instance(for: transform($0)) } + } } @inlinable diff --git a/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift b/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift index 66ee863e..ff145b1e 100644 --- a/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift +++ b/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift @@ -12,6 +12,71 @@ import _CollectionsTestSupport import PersistentCollections +/// A set of items whose subsets will produce a bunch of interesting test +/// cases. +/// +/// Note: Try to keep this short. Every new item added here will quadruple +/// testing costs. +let testItems = [ + RawCollider(1, "A"), + RawCollider(2, "B"), + RawCollider(3, "ACA"), + RawCollider(4, "ACB"), + RawCollider(5, "ACAD"), + RawCollider(6, "ACAD"), + RawCollider(7, "ACAEB"), + RawCollider(8, "ACAEB"), + RawCollider(9, "ACAEB"), + // RawCollider(10, "ACAEB"), + // RawCollider(11, "ADAD"), + // RawCollider(12, "ACC"), +] + +extension LifetimeTracker { + func persistentDictionary( + for items: C, + keyTransform: (C.Element) -> Key, + valueTransform: (C.Element) -> Value + ) -> PersistentDictionary, LifetimeTracked> { + PersistentDictionary( + uniqueKeys: instances(for: items, by: keyTransform), + values: instances(for: items, by: valueTransform)) + } + + func persistentDictionary( + for keys: C, + by valueTransform: (C.Element) -> Value + ) -> PersistentDictionary, LifetimeTracked> + where C.Element: Hashable { + PersistentDictionary( + uniqueKeys: instances(for: keys), + values: instances(for: keys, by: valueTransform)) + } + + func dictionary( + for items: C, + keyTransform: (C.Element) -> Key, + valueTransform: (C.Element) -> Value + ) -> Dictionary, LifetimeTracked> { + Dictionary( + uniqueKeysWithValues: zip( + instances(for: items, by: keyTransform), + instances(for: items, by: valueTransform))) + } + + func dictionary( + for keys: C, + by valueTransform: (C.Element) -> Value + ) -> Dictionary, LifetimeTracked> + where C.Element: Hashable { + Dictionary( + uniqueKeysWithValues: zip( + instances(for: keys), + instances(for: keys, by: valueTransform))) + } + +} + /// A list of example trees to use while testing persistent hash maps. /// /// Each example has a name and a list of path specifications or collisions. @@ -338,15 +403,25 @@ extension LifetimeTracker { return (PersistentDictionary(uniqueKeysWithValues: ref2), ref) } + func persistentDictionary( + for fixture: Fixture, + valueTransform: (Int) -> Value + ) -> ( + map: PersistentDictionary, LifetimeTracked>, + ref: [(key: LifetimeTracked, value: LifetimeTracked)] + ) { + persistentDictionary( + for: fixture, + keyTransform: { $0 }, + valueTransform: { valueTransform($0.identity) }) + } + func persistentDictionary( for fixture: Fixture ) -> ( map: PersistentDictionary, LifetimeTracked>, ref: [(key: LifetimeTracked, value: LifetimeTracked)] ) { - persistentDictionary( - for: fixture, - keyTransform: { $0 }, - valueTransform: { $0.identity + 1000 }) + persistentDictionary(for: fixture) { $0 + 1000 } } } diff --git a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift index 8a3279fc..d3befb66 100644 --- a/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentDictionary Tests.swift @@ -1489,6 +1489,55 @@ class PersistentDictionaryTests: CollectionTestCase { } } + func test_filter_exhaustive() { + withEverySubset("a", of: testItems) { a in + let x = PersistentDictionary( + uniqueKeysWithValues: a.lazy.map { + ($0, $0.identity + 100) + }) + withEverySubset("b", of: a) { b in + let y = Dictionary( + uniqueKeysWithValues: b.lazy.map { + ($0, $0.identity + 100) + }) + expectEqualDictionaries(x.filter { y[$0.key] == $0.value }, y) + } + } + } + + func test_merge_exhaustive() { + withEverySubset("a", of: testItems) { a in + withEverySubset("b", of: testItems) { b in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + func combine( + _ a: LifetimeTracked, _ b: LifetimeTracked + ) -> LifetimeTracked { + expectEqual(b.payload, a.payload + 100) + return tracker.instance(for: 100 - a.payload) + } + var expected1 = tracker.dictionary( + for: a, by: { $0.identity + 100 }) + let expected2 = tracker.dictionary( + for: b, by: { $0.identity + 200 }) + + var actual1 = tracker.persistentDictionary( + for: a, by: { $0.identity + 100 }) + let actual2 = tracker.persistentDictionary( + for: b, by: { $0.identity + 200 }) + + expected1.merge(expected2, uniquingKeysWith: combine) + + withHiddenCopies(if: isShared, of: &expected1) { expected1 in + actual1.merge(actual2, uniquingKeysWith: combine) + expectEqualDictionaries(actual1, expected1) + } + } + } + } + } + } + // MARK: - diff --git a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift index 03dff28c..0390f361 100644 --- a/Tests/PersistentCollectionsTests/PersistentSet Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentSet Tests.swift @@ -195,25 +195,6 @@ class PersistentSetTests: CollectionTestCase { expectEqualSets(s6.intersection(s9), []) } - /// A set of items whose subsets will produce a bunch of interesting test - /// cases. - /// - /// Note: Try to keep this short. Every new item added here will quadruple - /// testing costs. - let testItems = [ - RawCollider(1, "A"), - RawCollider(2, "ACA"), - RawCollider(3, "ACB"), - RawCollider(4, "ACAD"), - RawCollider(5, "ACAD"), - RawCollider(6, "ACAEB"), - RawCollider(7, "ACAEB"), - RawCollider(8, "ACAEB"), -// RawCollider(9, "ACAEB"), -// RawCollider(10, "ADAD"), -// RawCollider(11, "ACC"), - ] - func test_isEqual_Self_exhaustive() { withEverySubset("a", of: testItems) { a in let x = PersistentSet(a) @@ -318,7 +299,7 @@ class PersistentSetTests: CollectionTestCase { } } - func test_filter_Self_exhaustive() { + func test_filter_exhaustive() { withEverySubset("a", of: testItems) { a in let x = PersistentSet(a) withEverySubset("b", of: a) { b in