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)