Sources: Add unsafe keywords where needed

This commit is contained in:
Karoy Lorentey committed 2026-10-01 11:14:29 -07:00
1 parent 13f71ad927
commit d07dc32dfa
301 files changed
+6051 -5498

No files matched your search

@@ -121,7 +121,9 @@ extension _HashNode.Builder {
assert(!node.hasSingletonItem)
kind = .collisionNode(node)
} else if node.hasSingletonItem {
kind = node.read { .item($0[item: .zero], at: $0.itemMap.first!) }
kind = unsafe node.read {
unsafe .item($0[item: .zero], at: $0.itemMap.first!)
}
} else {
kind = .node(node)
}
@@ -145,6 +147,7 @@ extension _HashNode.Builder {
extension _HashNode {
@inlinable
@unsafe
internal mutating func applyReplacement(
_ level: _HashLevel,
_ replacement: Builder
@@ -168,6 +171,7 @@ extension _HashNode {
extension _HashNode.Builder {
@inlinable
@unsafe
internal mutating func addNewCollision(
_ level: _HashLevel, _ newItem: __owned Element, _ hash: _Hash
) {
@@ -183,7 +187,7 @@ extension _HashNode.Builder {
kind = .empty
assert(node.isCollisionNode)
assert(hash == node.collisionHash)
_ = node.ensureUniqueAndAppendCollision(isUnique: true, newItem)
_ = unsafe node.ensureUniqueAndAppendCollision(isUnique: true, newItem)
kind = .collisionNode(node)
case .node:
fatalError()
@@ -191,6 +195,7 @@ extension _HashNode.Builder {
}
@inlinable
@unsafe
internal mutating func addNewItem(
_ level: _HashLevel, _ newItem: __owned Element, at newBucket: _Bucket
) {
@@ -218,6 +223,7 @@ extension _HashNode.Builder {
}
@inlinable
@unsafe
internal mutating func addNewChildNode(
_ level: _HashLevel, _ newChild: __owned _HashNode, at newBucket: _Bucket
) {
@@ -239,7 +245,7 @@ extension _HashNode.Builder {
let isUnique = node.isUnique()
node.ensureUnique(
isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild)
node.insertChild(newChild, newBucket)
unsafe node.insertChild(newChild, newBucket)
self.kind = .node(node)
case .collisionNode(var node):
// Expansion
@@ -252,6 +258,7 @@ extension _HashNode.Builder {
}
@inlinable
@unsafe
internal mutating func addNewChildBranch(
_ level: _HashLevel, _ newChild: __owned Self, at newBucket: _Bucket
) {
@@ -261,13 +268,14 @@ extension _HashNode.Builder {
case .empty:
break
case .item(let newItem, _):
self.addNewItem(level, newItem, at: newBucket)
unsafe self.addNewItem(level, newItem, at: newBucket)
case .node(let newNode), .collisionNode(let newNode):
self.addNewChildNode(level, newNode, at: newBucket)
unsafe self.addNewChildNode(level, newNode, at: newBucket)
}
}
@inlinable
@unsafe
internal static func childBranch(
_ level: _HashLevel, _ child: Self, at bucket: _Bucket
) -> Self {
@@ -289,20 +297,22 @@ extension _HashNode.Builder {
extension _HashNode.Builder {
@inlinable
@unsafe
internal mutating func copyCollisions(
from source: _HashNode.UnsafeHandle,
upTo end: _HashSlot
) {
assert(isEmpty)
assert(source.isCollisionNode)
assert(end < source.itemsEndSlot)
let h = source.collisionHash
assert(unsafe source.isCollisionNode)
assert(unsafe end < source.itemsEndSlot)
let h = unsafe source.collisionHash
for slot: _HashSlot in stride(from: .zero, to: end, by: 1) {
self.addNewCollision(self.level, source[item: slot], h)
unsafe self.addNewCollision(self.level, source[item: slot], h)
}
}
@inlinable
@unsafe
internal mutating func copyItems(
_ level: _HashLevel,
from source: _HashNode.UnsafeHandle,
@@ -310,13 +320,14 @@ extension _HashNode.Builder {
) {
assert(level == self.level)
assert(isEmpty)
assert(!source.isCollisionNode)
for (b, s) in source.itemMap.intersection(_Bitmap(upTo: end)) {
self.addNewItem(level, source[item: s], at: b)
assert(unsafe !source.isCollisionNode)
for (b, s) in unsafe source.itemMap.intersection(_Bitmap(upTo: end)) {
unsafe self.addNewItem(level, source[item: s], at: b)
}
}
@inlinable
@unsafe
internal mutating func copyItemsAndChildren(
_ level: _HashLevel,
from source: _HashNode.UnsafeHandle,
@@ -324,12 +335,12 @@ extension _HashNode.Builder {
) {
assert(level == self.level)
assert(isEmpty)
assert(!source.isCollisionNode)
for (b, s) in source.itemMap {
self.addNewItem(level, source[item: s], at: b)
assert(unsafe !source.isCollisionNode)
for (b, s) in unsafe source.itemMap {
unsafe self.addNewItem(level, source[item: s], at: b)
}
for (b, s) in source.childMap.intersection(_Bitmap(upTo: end)) {
self.addNewChildNode(level, source[child: s], at: b)
for (b, s) in unsafe source.childMap.intersection(_Bitmap(upTo: end)) {
unsafe self.addNewChildNode(level, source[child: s], at: b)
}
}
}
@@ -355,7 +366,7 @@ extension _HashNode.Builder {
@inlinable
internal func mapValuesToVoid() -> _HashNode<Key, Void>.Builder {
if Value.self == Void.self {
return unsafeBitCast(self, to: _HashNode<Key, Void>.Builder.self)
return unsafe unsafeBitCast(self, to: _HashNode<Key, Void>.Builder.self)
}
return mapValues { _ in () }
}
@@ -24,8 +24,8 @@ extension _HashNode {
restPrefix: String = "",
depth: Int = 0
) {
read {
$0.dump(
unsafe read {
unsafe $0.dump(
iterationOrder: iterationOrder,
limit: limit,
extra: "count: \(count), ",
@@ -39,7 +39,9 @@ extension _HashNode {
extension _HashNode.Storage {
@usableFromInline
final internal func dump(iterationOrder: Bool = false) {
UnsafeHandle.read(self) { $0.dump(iterationOrder: iterationOrder) }
unsafe UnsafeHandle.read(self) {
unsafe $0.dump(iterationOrder: iterationOrder)
}
}
}
@@ -51,7 +53,7 @@ extension _HashNode {
}
extension _HashNode.UnsafeHandle {
internal func _itemString(at slot: _HashSlot) -> String {
let item = self[item: slot]
let item = unsafe self[item: slot]
return _HashNode._itemString(for: item)
}
@@ -74,20 +76,20 @@ extension _HashNode.UnsafeHandle {
firstPrefix += " "
}
print("""
\(firstPrefix)\(isCollisionNode ? "CollisionNode" : "Node")(\
at: \(_addressString(for: _header)), \
\(isCollisionNode ? "hash: \(collisionHash), " : "")\
\(firstPrefix)\(unsafe isCollisionNode ? "CollisionNode" : "Node")(\
at: \(_addressString(for: unsafe _header)), \
\(unsafe isCollisionNode ? "hash: \(unsafe collisionHash), " : "")\
\(extra)\
byteCapacity: \(byteCapacity), \
freeBytes: \(bytesFree))
byteCapacity: \(unsafe byteCapacity), \
freeBytes: \(unsafe bytesFree))
""")
guard limit > 0 else { return }
if iterationOrder {
for slot in stride(from: .zero, to: itemsEndSlot, by: 1) {
print(" \(restPrefix)[\(slot)] \(_itemString(at: slot))")
for slot in stride(from: .zero, to: unsafe itemsEndSlot, by: 1) {
print(" \(restPrefix)[\(slot)] \(unsafe _itemString(at: slot))")
}
for slot in stride(from: .zero, to: childrenEndSlot, by: 1) {
self[child: slot].dump(
for slot in stride(from: .zero, to: unsafe childrenEndSlot, by: 1) {
unsafe self[child: slot].dump(
iterationOrder: true,
limit: limit - 1,
firstPrefix: " \(restPrefix).\(slot)",
@@ -95,9 +97,9 @@ extension _HashNode.UnsafeHandle {
depth: depth + 1)
}
}
else if isCollisionNode {
for slot in stride(from: .zero, to: itemsEndSlot, by: 1) {
print("\(restPrefix)[\(slot)] \(_itemString(at: slot))")
else if unsafe isCollisionNode {
for slot in stride(from: .zero, to: unsafe itemsEndSlot, by: 1) {
print("\(restPrefix)[\(slot)] \(unsafe _itemString(at: slot))")
}
} else {
var itemSlot: _HashSlot = .zero
@@ -105,11 +107,11 @@ extension _HashNode.UnsafeHandle {
for b in 0 ..< UInt(_Bitmap.capacity) {
let bucket = _Bucket(b)
let bucketStr = "#\(String(b, radix: _Bitmap.capacity, uppercase: true))"
if itemMap.contains(bucket) {
print("\(restPrefix) \(bucketStr) \(_itemString(at: itemSlot))")
if unsafe itemMap.contains(bucket) {
print("\(restPrefix) \(bucketStr) \(unsafe _itemString(at: itemSlot))")
itemSlot = itemSlot.next()
} else if childMap.contains(bucket) {
self[child: childSlot].dump(
} else if unsafe childMap.contains(bucket) {
unsafe self[child: childSlot].dump(
iterationOrder: false,
limit: limit - 1,
firstPrefix: "\(restPrefix) \(bucketStr) ",
@@ -18,7 +18,7 @@ import InternalCollectionsUtilities
extension _HashNode {
@inlinable @inline(__always)
internal static func _emptyNode() -> _HashNode {
_HashNode(storage: _emptySingleton, count: 0)
unsafe _HashNode(storage: _emptySingleton, count: 0)
}
@inlinable
@@ -27,9 +27,9 @@ extension _HashNode {
_ item1: __owned Element,
_ item2: __owned Element
) -> _HashNode {
let node = _HashNode.allocateCollision(count: 2, hash) { items in
items.initializeElement(at: 1, to: item1)
items.initializeElement(at: 0, to: item2)
let node = unsafe _HashNode.allocateCollision(count: 2, hash) { items in
unsafe items.initializeElement(at: 1, to: item1)
unsafe items.initializeElement(at: 0, to: item2)
}.node
node._invariantCheck()
return node
@@ -41,9 +41,9 @@ extension _HashNode {
_ item1: __owned Element,
_ inserter2: (UnsafeMutablePointer<Element>) -> Void
) -> _HashNode {
let node = _HashNode.allocateCollision(count: 2, hash) { items in
items.initializeElement(at: 1, to: item1)
inserter2(items.baseAddress.unsafelyUnwrapped)
let node = unsafe _HashNode.allocateCollision(count: 2, hash) { items in
unsafe items.initializeElement(at: 1, to: item1)
unsafe inserter2(items.baseAddress.unsafelyUnwrapped)
}.node
node._invariantCheck()
return node
@@ -54,13 +54,13 @@ extension _HashNode {
_ item: __owned Element,
_ bucket: _Bucket
) -> _HashNode {
let r = _HashNode.allocate(
let r = unsafe _HashNode.allocate(
itemMap: _Bitmap(bucket),
childMap: .empty,
count: 1
) { children, items in
assert(items.count == 1 && children.count == 0)
items.initializeElement(at: 0, to: item)
unsafe items.initializeElement(at: 0, to: item)
}
r.node._invariantCheck()
return r.node
@@ -73,9 +73,9 @@ extension _HashNode {
_ item2: __owned Element,
_ bucket2: _Bucket
) -> _HashNode {
_regularNode(
unsafe _regularNode(
item1, bucket1,
{ $0.initialize(to: item2) }, bucket2).node
{ unsafe $0.initialize(to: item2) }, bucket2).node
}
@inlinable
@@ -86,7 +86,7 @@ extension _HashNode {
_ bucket2: _Bucket
) -> (node: _HashNode, slot1: _HashSlot, slot2: _HashSlot) {
assert(bucket1 != bucket2)
let r = _HashNode.allocate(
let r = unsafe _HashNode.allocate(
itemMap: _Bitmap(bucket1, bucket2),
childMap: .empty,
count: 2
@@ -94,8 +94,8 @@ extension _HashNode {
assert(items.count == 2 && children.count == 0)
let i1 = bucket1 < bucket2 ? 1 : 0
let i2 = 1 &- i1
items.initializeElement(at: i1, to: item1)
inserter2(items.baseAddress.unsafelyUnwrapped + i2)
unsafe items.initializeElement(at: i1, to: item1)
unsafe inserter2(items.baseAddress.unsafelyUnwrapped + i2)
return (_HashSlot(i2), _HashSlot(i1)) // Note: swapped
}
r.node._invariantCheck()
@@ -107,13 +107,13 @@ extension _HashNode {
_ child: __owned _HashNode,
_ bucket: _Bucket
) -> _HashNode {
let r = _HashNode.allocate(
let r = unsafe _HashNode.allocate(
itemMap: .empty,
childMap: _Bitmap(bucket),
count: child.count
) { children, items in
assert(items.count == 0 && children.count == 1)
children.initializeElement(at: 0, to: child)
unsafe children.initializeElement(at: 0, to: child)
}
r.node._invariantCheck()
return r.node
@@ -126,8 +126,8 @@ extension _HashNode {
_ child: __owned _HashNode,
_ childBucket: _Bucket
) -> _HashNode {
_regularNode(
{ $0.initialize(to: item) }, itemBucket,
unsafe _regularNode(
{ unsafe $0.initialize(to: item) }, itemBucket,
child, childBucket)
}
@@ -139,14 +139,14 @@ extension _HashNode {
_ childBucket: _Bucket
) -> _HashNode {
assert(itemBucket != childBucket)
let r = _HashNode.allocate(
let r = unsafe _HashNode.allocate(
itemMap: _Bitmap(itemBucket),
childMap: _Bitmap(childBucket),
count: child.count &+ 1
) { children, items in
assert(items.count == 1 && children.count == 1)
inserter(items.baseAddress.unsafelyUnwrapped)
children.initializeElement(at: 0, to: child)
unsafe inserter(items.baseAddress.unsafelyUnwrapped)
unsafe children.initializeElement(at: 0, to: child)
}
r.node._invariantCheck()
return r.node
@@ -160,7 +160,7 @@ extension _HashNode {
_ child2Bucket: _Bucket
) -> _HashNode {
assert(child1Bucket != child2Bucket)
let r = _HashNode.allocate(
let r = unsafe _HashNode.allocate(
itemMap: .empty,
childMap: _Bitmap(child1Bucket, child2Bucket),
count: child1.count &+ child2.count
@@ -168,8 +168,8 @@ extension _HashNode {
assert(items.count == 0 && children.count == 2)
let i1 = child1Bucket < child2Bucket ? 0 : 1
let i2 = 1 &- i1
children.initializeElement(at: i1, to: child1)
children.initializeElement(at: i2, to: child2)
unsafe children.initializeElement(at: i1, to: child1)
unsafe children.initializeElement(at: i2, to: child2)
}
r.node._invariantCheck()
return r.node
@@ -178,6 +178,7 @@ extension _HashNode {
extension _HashNode {
@inlinable
@unsafe
internal static func build(
level: _HashLevel,
item1: __owned Element,
@@ -187,15 +188,16 @@ extension _HashNode {
) -> (top: _HashNode, leaf: _UnmanagedHashNode, slot1: _HashSlot, slot2: _HashSlot) {
assert(hash1.isEqual(to: hash2, upTo: level.ascend()))
if hash1 == hash2 {
let top = _collisionNode(hash1, item1, inserter2)
return (top, top.unmanaged, _HashSlot(0), _HashSlot(1))
let top = unsafe _collisionNode(hash1, item1, inserter2)
return unsafe (top, top.unmanaged, _HashSlot(0), _HashSlot(1))
}
let r = _build(
let r = unsafe _build(
level: level, item1: item1, hash1, item2: inserter2, hash2)
return (r.top, r.leaf, r.slot1, r.slot2)
return unsafe (r.top, r.leaf, r.slot1, r.slot2)
}
@inlinable
@unsafe
internal static func _build(
level: _HashLevel,
item1: __owned Element,
@@ -207,14 +209,14 @@ extension _HashNode {
let b1 = hash1[level]
let b2 = hash2[level]
guard b1 == b2 else {
let r = _regularNode(item1, b1, inserter2, b2)
return (r.node, r.node.unmanaged, r.slot1, r.slot2)
let r = unsafe _regularNode(item1, b1, inserter2, b2)
return unsafe (r.node, r.node.unmanaged, r.slot1, r.slot2)
}
let r = _build(
let r = unsafe _build(
level: level.descend(),
item1: item1, hash1,
item2: inserter2, hash2)
return (_regularNode(r.top, b1), r.leaf, r.slot1, r.slot2)
return unsafe (_regularNode(r.top, b1), r.leaf, r.slot1, r.slot2)
}
@inlinable
@@ -230,14 +232,14 @@ extension _HashNode {
let b1 = hash1[level]
let b2 = hash2[level]
if b1 == b2 {
let node = build(
let node = unsafe build(
level: level.descend(),
item1: inserter1, hash1,
child2: child2, hash2)
return (_regularNode(node.top, b1), node.leaf, node.slot1, node.slot2)
return unsafe (_regularNode(node.top, b1), node.leaf, node.slot1, node.slot2)
}
let node = _regularNode(inserter1, hash1[level], child2, hash2[level])
return (node, node.unmanaged, .zero, .zero)
let node = unsafe _regularNode(inserter1, hash1[level], child2, hash2[level])
return unsafe (node, node.unmanaged, .zero, .zero)
}
@inlinable
@@ -18,7 +18,7 @@ extension _HashNode {
internal func find(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (descend: Bool, slot: _HashSlot)? {
read { $0.find(level, key, hash) }
unsafe read { unsafe $0.find(level, key, hash) }
}
}
@@ -27,19 +27,19 @@ extension _HashNode.UnsafeHandle {
internal func find(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (descend: Bool, slot: _HashSlot)? {
guard !isCollisionNode else {
let r = _findInCollision(level, key, hash)
guard unsafe !isCollisionNode else {
let r = unsafe _findInCollision(level, key, hash)
guard r.code == 0 else { return nil }
return (false, r.slot)
}
let bucket = hash[level]
if itemMap.contains(bucket) {
let slot = itemMap.slot(of: bucket)
guard self[item: slot].key == key else { return nil }
if unsafe itemMap.contains(bucket) {
let slot = unsafe itemMap.slot(of: bucket)
guard unsafe self[item: slot].key == key else { return nil }
return (false, slot)
}
if childMap.contains(bucket) {
let slot = childMap.slot(of: bucket)
if unsafe childMap.contains(bucket) {
let slot = unsafe childMap.slot(of: bucket)
return (true, slot)
}
return nil
@@ -49,14 +49,14 @@ extension _HashNode.UnsafeHandle {
internal func _findInCollision(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (code: Int, slot: _HashSlot) {
assert(isCollisionNode)
assert(unsafe isCollisionNode)
if !level.isAtBottom {
if hash != self.collisionHash { return (2, .zero) }
if unsafe hash != self.collisionHash { return (2, .zero) }
}
// Note: this searches the items in reverse insertion order.
guard let slot = reverseItems.firstIndex(where: { $0.key == key })
else { return (1, self.itemsEndSlot) }
return (0, _HashSlot(itemCount &- 1 &- slot))
guard let slot = unsafe reverseItems.firstIndex(where: { $0.key == key })
else { return (1, unsafe self.itemsEndSlot) }
return (0, unsafe _HashSlot(itemCount &- 1 &- slot))
}
}
@@ -135,7 +135,7 @@ extension _HashNode {
internal func findForInsertion(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> _FindResult {
read { $0.findForInsertion(level, key, hash) }
unsafe read { unsafe $0.findForInsertion(level, key, hash) }
}
}
@@ -144,8 +144,8 @@ extension _HashNode.UnsafeHandle {
internal func findForInsertion(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> _FindResult {
guard !isCollisionNode else {
let r = _findInCollision(level, key, hash)
guard unsafe !isCollisionNode else {
let r = unsafe _findInCollision(level, key, hash)
if r.code == 0 {
return .found(.invalid, r.slot)
}
@@ -156,18 +156,18 @@ extension _HashNode.UnsafeHandle {
return .expansion
}
let bucket = hash[level]
if itemMap.contains(bucket) {
let slot = itemMap.slot(of: bucket)
if self[item: slot].key == key {
if unsafe itemMap.contains(bucket) {
let slot = unsafe itemMap.slot(of: bucket)
if unsafe self[item: slot].key == key {
return .found(bucket, slot)
}
return .spawnChild(bucket, slot)
}
if childMap.contains(bucket) {
let slot = childMap.slot(of: bucket)
if unsafe childMap.contains(bucket) {
let slot = unsafe childMap.slot(of: bucket)
return .descend(bucket, slot)
}
let slot = itemMap.slot(of: bucket)
let slot = unsafe itemMap.slot(of: bucket)
return .insert(bucket, slot)
}
}
@@ -177,17 +177,17 @@ extension _HashNode.UnsafeHandle {
extension _HashNode {
@inlinable
internal func get(_ level: _HashLevel, _ key: Key, _ hash: _Hash) -> Value? {
var node = unmanaged
var node = unsafe unmanaged
var level = level
while true {
let r = UnsafeHandle.read(node) { $0.find(level, key, hash) }
let r = unsafe UnsafeHandle.read(node) { unsafe $0.find(level, key, hash) }
guard let r = r else {
return nil
}
guard r.descend else {
return UnsafeHandle.read(node) { $0[item: r.slot].value }
return unsafe UnsafeHandle.read(node) { unsafe $0[item: r.slot].value }
}
node = node.unmanagedChild(at: r.slot)
unsafe node = node.unmanagedChild(at: r.slot)
level = level.descend()
}
}
@@ -198,13 +198,13 @@ extension _HashNode {
internal func containsKey(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> Bool {
var node = unmanaged
var node = unsafe unmanaged
var level = level
while true {
let r = UnsafeHandle.read(node) { $0.find(level, key, hash) }
let r = unsafe UnsafeHandle.read(node) { unsafe $0.find(level, key, hash) }
guard let r = r else { return false }
guard r.descend else { return true }
node = node.unmanagedChild(at: r.slot)
unsafe node = node.unmanagedChild(at: r.slot)
level = level.descend()
}
}
@@ -215,17 +215,17 @@ extension _HashNode {
internal func lookup(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (node: _UnmanagedHashNode, slot: _HashSlot)? {
var node = unmanaged
var node = unsafe unmanaged
var level = level
while true {
let r = UnsafeHandle.read(node) { $0.find(level, key, hash) }
let r = unsafe UnsafeHandle.read(node) { unsafe $0.find(level, key, hash) }
guard let r = r else {
return nil
}
guard r.descend else {
return (node, r.slot)
return unsafe (node, r.slot)
}
node = node.unmanagedChild(at: r.slot)
unsafe node = node.unmanagedChild(at: r.slot)
level = level.descend()
}
}
@@ -238,32 +238,32 @@ extension _HashNode {
) -> Int? {
guard let r = find(level, key, hash) else { return nil }
guard r.descend else { return r.slot.value }
return read { h in
let children = h.children
let p = children[r.slot.value]
return unsafe read { h in
let children = unsafe h.children
let p = unsafe children[r.slot.value]
.position(forKey: key, level.descend(), hash)
guard let p = p else { return nil }
let c = h.itemCount &+ p
return children[..<r.slot.value].reduce(into: c) { $0 &+= $1.count }
let c = unsafe h.itemCount &+ p
return unsafe children[..<r.slot.value].reduce(into: c) { $0 &+= $1.count }
}
}
@inlinable
internal func item(position: Int) -> Element {
assert(position >= 0 && position < self.count)
return read {
return unsafe read {
var itemsToSkip = position
let itemCount = $0.itemCount
let itemCount = unsafe $0.itemCount
if itemsToSkip < itemCount {
return $0[item: _HashSlot(itemsToSkip)]
return unsafe $0[item: _HashSlot(itemsToSkip)]
}
itemsToSkip -= itemCount
let children = $0.children
let children = unsafe $0.children
for i in children.indices {
if itemsToSkip < children[i].count {
return children[i].item(position: itemsToSkip)
if unsafe itemsToSkip < children[i].count {
return unsafe children[i].item(position: itemsToSkip)
}
itemsToSkip -= children[i].count
unsafe itemsToSkip -= children[i].count
}
fatalError("Inconsistent tree")
}
@@ -24,35 +24,36 @@ extension _HashNode.UnsafeHandle {
/// ready to store the new item. It is the caller's responsibility to
/// initialize this memory.
@inlinable
@unsafe
internal func _makeRoomForNewItem(
at slot: _HashSlot, _ bucket: _Bucket
) -> UnsafeMutablePointer<Element> {
assertMutable()
let c = itemCount
let c = unsafe itemCount
assert(slot.value <= c)
let stride = MemoryLayout<Element>.stride
assert(bytesFree >= stride)
bytesFree &-= stride
assert(unsafe bytesFree >= stride)
unsafe bytesFree &-= stride
let start = _memory
let start = unsafe _memory
.advanced(by: byteCapacity &- (c &+ 1) &* stride)
.bindMemory(to: Element.self, capacity: 1)
let prefix = c &- slot.value
start.moveInitialize(from: start + 1, count: prefix)
unsafe start.moveInitialize(from: start + 1, count: prefix)
if bucket.isInvalid {
assert(isCollisionNode)
collisionCount &+= 1
assert(unsafe isCollisionNode)
unsafe collisionCount &+= 1
} else {
assert(!itemMap.contains(bucket))
assert(!childMap.contains(bucket))
itemMap.insert(bucket)
assert(itemMap.slot(of: bucket) == slot)
assert(unsafe !itemMap.contains(bucket))
assert(unsafe !childMap.contains(bucket))
unsafe itemMap.insert(bucket)
assert(unsafe itemMap.slot(of: bucket) == slot)
}
return start + prefix
return unsafe start + prefix
}
/// Insert `child` at `slot`. There must be enough free space in the node
@@ -61,59 +62,63 @@ extension _HashNode.UnsafeHandle {
/// `childMap` must not yet reflect the insertion at the time this
/// function is called. This method does not update `childMap`.
@inlinable
@unsafe
internal func _insertChild(_ child: __owned _HashNode, at slot: _HashSlot) {
assertMutable()
assert(!isCollisionNode)
assert(unsafe !isCollisionNode)
let c = childMap.count
let c = unsafe childMap.count
assert(slot.value <= c)
let stride = MemoryLayout<_HashNode>.stride
assert(bytesFree >= stride)
bytesFree &-= stride
assert(unsafe bytesFree >= stride)
unsafe bytesFree &-= stride
_memory.bindMemory(to: _HashNode.self, capacity: c &+ 1)
let q = _childrenStart + slot.value
(q + 1).moveInitialize(from: q, count: c &- slot.value)
q.initialize(to: child)
unsafe _memory.bindMemory(to: _HashNode.self, capacity: c &+ 1)
let q = unsafe _childrenStart + slot.value
unsafe (q + 1).moveInitialize(from: q, count: c &- slot.value)
unsafe q.initialize(to: child)
}
}
extension _HashNode {
@inlinable @inline(__always)
@unsafe
internal mutating func insertItem(
_ item: __owned Element, at bucket: _Bucket
) {
let slot = read { $0.itemMap.slot(of: bucket) }
self.insertItem(item, at: slot, bucket)
let slot = unsafe read { unsafe $0.itemMap.slot(of: bucket) }
unsafe self.insertItem(item, at: slot, bucket)
}
@inlinable @inline(__always)
@unsafe
internal mutating func insertItem(
_ item: __owned Element, at slot: _HashSlot, _ bucket: _Bucket
) {
self.count &+= 1
update {
let p = $0._makeRoomForNewItem(at: slot, bucket)
p.initialize(to: item)
unsafe update {
let p = unsafe $0._makeRoomForNewItem(at: slot, bucket)
unsafe p.initialize(to: item)
}
}
/// Insert `child` in `bucket`. There must be enough free space in the
/// node to fit the new child.
@inlinable
@unsafe
internal mutating func insertChild(
_ child: __owned _HashNode, _ bucket: _Bucket
) {
count &+= child.count
update {
assert(!$0.isCollisionNode)
assert(!$0.itemMap.contains(bucket))
assert(!$0.childMap.contains(bucket))
unsafe update {
assert(unsafe !$0.isCollisionNode)
assert(unsafe !$0.itemMap.contains(bucket))
assert(unsafe !$0.childMap.contains(bucket))
let slot = $0.childMap.slot(of: bucket)
$0._insertChild(child, at: slot)
$0.childMap.insert(bucket)
let slot = unsafe $0.childMap.slot(of: bucket)
unsafe $0._insertChild(child, at: slot)
unsafe $0.childMap.insert(bucket)
}
}
}
@@ -20,26 +20,27 @@ extension _HashNode.UnsafeHandle {
/// `itemMap` must not yet reflect the removal at the time this
/// function is called. This method does not update `itemMap`.
@inlinable
@unsafe
internal func _removeItem<R>(
at slot: _HashSlot,
by remover: (UnsafeMutablePointer<Element>) -> R
) -> R {
assertMutable()
let c = itemCount
let c = unsafe itemCount
assert(slot.value < c)
let stride = MemoryLayout<Element>.stride
bytesFree &+= stride
unsafe bytesFree &+= stride
let start = _memory
let start = unsafe _memory
.advanced(by: byteCapacity &- stride &* c)
.assumingMemoryBound(to: Element.self)
let prefix = c &- 1 &- slot.value
let q = start + prefix
let q = unsafe start + prefix
defer {
(start + 1).moveInitialize(from: start, count: prefix)
unsafe (start + 1).moveInitialize(from: start, count: prefix)
}
return remover(q)
return unsafe remover(q)
}
/// Remove and return the child at `slot`, increasing the amount of free
@@ -48,35 +49,38 @@ extension _HashNode.UnsafeHandle {
/// `childMap` must not yet reflect the removal at the time this
/// function is called. This method does not update `childMap`.
@inlinable
@unsafe
internal func _removeChild(at slot: _HashSlot) -> _HashNode {
assertMutable()
assert(!isCollisionNode)
let count = childCount
assert(unsafe !isCollisionNode)
let count = unsafe childCount
assert(slot.value < count)
bytesFree &+= MemoryLayout<_HashNode>.stride
unsafe bytesFree &+= MemoryLayout<_HashNode>.stride
let q = _childrenStart + slot.value
let child = q.move()
q.moveInitialize(from: q + 1, count: count &- 1 &- slot.value)
let q = unsafe _childrenStart + slot.value
let child = unsafe q.move()
unsafe q.moveInitialize(from: q + 1, count: count &- 1 &- slot.value)
return child
}
}
extension _HashNode {
@inlinable
@unsafe
internal mutating func removeItem(
at bucket: _Bucket
) -> Element {
let slot = read { $0.itemMap.slot(of: bucket) }
return removeItem(at: bucket, slot, by: { $0.move() })
let slot = unsafe read { unsafe $0.itemMap.slot(of: bucket) }
return unsafe removeItem(at: bucket, slot, by: { unsafe $0.move() })
}
@inlinable
@unsafe
internal mutating func removeItem(
at bucket: _Bucket, _ slot: _HashSlot
) -> Element {
removeItem(at: bucket, slot, by: { $0.move() })
unsafe removeItem(at: bucket, slot, by: { unsafe $0.move() })
}
/// Remove the item at `slot`, increasing the amount of free
@@ -85,6 +89,7 @@ extension _HashNode {
/// The closure `remove` is called to perform the deinitialization of the
/// storage slot corresponding to the item to be removed.
@inlinable
@unsafe
internal mutating func removeItem<R>(
at bucket: _Bucket, _ slot: _HashSlot,
by remover: (UnsafeMutablePointer<Element>) -> R
@@ -92,30 +97,31 @@ extension _HashNode {
defer { _invariantCheck() }
assert(count > 0)
count &-= 1
return update {
let old = $0._removeItem(at: slot, by: remover)
if $0.isCollisionNode {
assert(slot.value < $0.collisionCount)
$0.collisionCount &-= 1
return unsafe update {
let old = unsafe $0._removeItem(at: slot, by: remover)
if unsafe $0.isCollisionNode {
assert(unsafe slot.value < $0.collisionCount)
unsafe $0.collisionCount &-= 1
} else {
assert($0.itemMap.contains(bucket))
assert($0.itemMap.slot(of: bucket) == slot)
$0.itemMap.remove(bucket)
assert(unsafe $0.itemMap.contains(bucket))
assert(unsafe $0.itemMap.slot(of: bucket) == slot)
unsafe $0.itemMap.remove(bucket)
}
return old
}
}
@inlinable
@unsafe
internal mutating func removeChild(
at bucket: _Bucket, _ slot: _HashSlot
) -> _HashNode {
assert(!isCollisionNode)
let child: _HashNode = update {
assert($0.childMap.contains(bucket))
assert($0.childMap.slot(of: bucket) == slot)
let child = $0._removeChild(at: slot)
$0.childMap.remove(bucket)
let child: _HashNode = unsafe update {
assert(unsafe $0.childMap.contains(bucket))
assert(unsafe $0.childMap.slot(of: bucket) == slot)
let child = unsafe $0._removeChild(at: slot)
unsafe $0.childMap.remove(bucket)
return child
}
assert(self.count >= child.count)
@@ -124,14 +130,15 @@ extension _HashNode {
}
@inlinable
@unsafe
internal mutating func removeSingletonItem() -> Element {
defer { _invariantCheck() }
assert(count == 1)
count = 0
return update {
assert($0.hasSingletonItem)
let old = $0._removeItem(at: .zero) { $0.move() }
$0.clear()
return unsafe update {
assert(unsafe $0.hasSingletonItem)
let old = unsafe $0._removeItem(at: .zero) { unsafe $0.move() }
unsafe $0.clear()
return old
}
}
@@ -139,10 +146,10 @@ extension _HashNode {
@inlinable
internal mutating func removeSingletonChild() -> _HashNode {
defer { _invariantCheck() }
let child: _HashNode = update {
assert($0.hasSingletonChild)
let child = $0._removeChild(at: .zero)
$0.childMap = .empty
let child: _HashNode = unsafe update {
assert(unsafe $0.hasSingletonChild)
let child = unsafe $0._removeChild(at: .zero)
unsafe $0.childMap = .empty
return child
}
assert(self.count == child.count)
@@ -13,36 +13,39 @@
extension _HashNode {
@inlinable
@unsafe
internal mutating func replaceItem(
at bucket: _Bucket, _ slot: _HashSlot, with item: __owned 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
unsafe update {
assert(unsafe $0.isCollisionNode || $0.itemMap.contains(bucket))
assert(unsafe $0.isCollisionNode || slot == $0.itemMap.slot(of: bucket))
assert(unsafe !$0.isCollisionNode || slot.value < $0.collisionCount)
unsafe $0[item: slot] = item
}
}
@inlinable
@unsafe
internal mutating func replaceChild(
at bucket: _Bucket, with child: __owned _HashNode
) -> Int {
let slot = read { $0.childMap.slot(of: bucket) }
return replaceChild(at: bucket, slot, with: child)
let slot = unsafe read { unsafe $0.childMap.slot(of: bucket) }
return unsafe replaceChild(at: bucket, slot, with: child)
}
@inlinable
@unsafe
internal mutating func replaceChild(
at bucket: _Bucket, _ slot: _HashSlot, with child: __owned _HashNode
) -> Int {
let delta: Int = 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
let delta: Int = unsafe update {
assert(unsafe !$0.isCollisionNode)
assert(unsafe $0.childMap.contains(bucket))
assert(unsafe $0.childMap.slot(of: bucket) == slot)
let p = unsafe $0.childPtr(at: slot)
let delta = unsafe child.count &- p.pointee.count
unsafe p.pointee = child
return delta
}
self.count &+= delta
@@ -50,6 +53,7 @@ extension _HashNode {
}
@inlinable
@unsafe
internal func replacingChild(
_ level: _HashLevel,
at bucket: _Bucket,
@@ -57,26 +61,26 @@ extension _HashNode {
with child: __owned Builder
) -> Builder {
assert(child.level == level.descend())
read {
assert(!$0.isCollisionNode)
assert($0.childMap.contains(bucket))
assert(slot == $0.childMap.slot(of: bucket))
unsafe read {
assert(unsafe !$0.isCollisionNode)
assert(unsafe $0.childMap.contains(bucket))
assert(unsafe slot == $0.childMap.slot(of: bucket))
}
switch child.kind {
case .empty:
return _removingChild(level, at: bucket, slot)
return unsafe _removingChild(level, at: bucket, slot)
case let .item(item, _):
if hasSingletonChild {
return .item(level, item, at: bucket)
}
var node = self.copy(withFreeSpace: _HashNode.spaceForInlinedChild)
_ = node.removeChild(at: bucket, slot)
node.insertItem(item, at: bucket)
_ = unsafe node.removeChild(at: bucket, slot)
unsafe node.insertItem(item, at: bucket)
node._invariantCheck()
return .node(level, node)
case let .node(node):
var copy = self.copy()
_ = copy.replaceChild(at: bucket, slot, with: node)
_ = unsafe copy.replaceChild(at: bucket, slot, with: node)
return .node(level, copy)
case let .collisionNode(node):
if hasSingletonChild {
@@ -85,7 +89,7 @@ extension _HashNode {
return .collisionNode(level, node)
}
var copy = self.copy()
_ = copy.replaceChild(at: bucket, slot, with: node)
_ = unsafe copy.replaceChild(at: bucket, slot, with: node)
return .node(level, copy)
}
}
@@ -47,9 +47,9 @@ extension _HashNode {
@inlinable
deinit {
UnsafeHandle.update(self) { handle in
handle.children.deinitialize()
handle.reverseItems.deinitialize()
unsafe UnsafeHandle.update(self) { handle in
unsafe handle.children.deinitialize()
unsafe handle.reverseItems.deinitialize()
}
}
}
@@ -89,16 +89,16 @@ extension _HashNode.Storage {
_HashNodeHeader(byteCapacity: mincap * childStride)
}
object.withUnsafeMutablePointers { header, elements in
unsafe object.withUnsafeMutablePointers { header, elements in
let start = UnsafeRawPointer(elements)
let end = start
let end = unsafe start
.advanced(by: Int(header.pointee.byteCapacity))
.alignedDown(for: Element.self)
header.pointee._byteCapacity = UInt32(start.distance(to: end))
header.pointee._bytesFree = header.pointee._byteCapacity
assert(byteCapacity <= header.pointee.byteCapacity)
unsafe header.pointee._byteCapacity = UInt32(start.distance(to: end))
unsafe header.pointee._bytesFree = header.pointee._byteCapacity
assert(unsafe byteCapacity <= header.pointee.byteCapacity)
}
return unsafeDowncast(object, to: _HashNode.Storage.self)
return unsafe unsafeDowncast(object, to: _HashNode.Storage.self)
}
}
@@ -176,19 +176,19 @@ extension _HashNode {
let storage = Storage.allocate(
byteCapacity: occupiedBytes &+ extraBytes)
var node = _HashNode(storage: storage, count: count)
let result: R = node.update {
$0.itemMap = itemMap
$0.childMap = childMap
let result: R = unsafe node.update {
unsafe $0.itemMap = itemMap
unsafe $0.childMap = childMap
assert(occupiedBytes <= $0.bytesFree)
$0.bytesFree &-= occupiedBytes
assert(unsafe occupiedBytes <= $0.bytesFree)
unsafe $0.bytesFree &-= occupiedBytes
let childStart = $0._memory
let childStart = unsafe $0._memory
.bindMemory(to: _HashNode.self, capacity: childCount)
let itemStart = ($0._memory + ($0.byteCapacity - itemBytes))
let itemStart = unsafe ($0._memory + ($0.byteCapacity - itemBytes))
.bindMemory(to: Element.self, capacity: itemCount)
return initializer(
return unsafe initializer(
UnsafeMutableBufferPointer(start: childStart, count: childCount),
UnsafeMutableBufferPointer(start: itemStart, count: itemCount))
}
@@ -210,19 +210,19 @@ extension _HashNode {
assert(MemoryLayout<_Hash>.alignment <= MemoryLayout<_RawHashNode>.alignment)
let storage = Storage.allocate(byteCapacity: bytes &+ extraBytes)
var node = _HashNode(storage: storage, count: count)
let result: R = node.update {
$0.itemMap = _Bitmap(bitPattern: count)
$0.childMap = $0.itemMap
assert(bytes <= $0.bytesFree)
$0.bytesFree &-= bytes
let result: R = unsafe node.update {
unsafe $0.itemMap = _Bitmap(bitPattern: count)
unsafe $0.childMap = $0.itemMap
assert(unsafe bytes <= $0.bytesFree)
unsafe $0.bytesFree &-= bytes
$0._memory.storeBytes(of: hash, as: _Hash.self)
unsafe $0._memory.storeBytes(of: hash, as: _Hash.self)
let itemStart = ($0._memory + ($0.byteCapacity &- itemBytes))
let itemStart = unsafe ($0._memory + ($0.byteCapacity &- itemBytes))
.bindMemory(to: Element.self, capacity: count)
let items = UnsafeMutableBufferPointer(start: itemStart, count: count)
return initializer(items)
let items = unsafe UnsafeMutableBufferPointer(start: itemStart, count: count)
return unsafe initializer(items)
}
return (node, result)
}
@@ -233,23 +233,23 @@ extension _HashNode {
assert(space >= 0)
if isCollisionNode {
return read { src in
Self.allocateCollision(
return unsafe read { src in
unsafe Self.allocateCollision(
count: self.count, self.collisionHash
) { dstItems in
dstItems.initializeAll(fromContentsOf: src.reverseItems)
unsafe dstItems.initializeAll(fromContentsOf: src.reverseItems)
}.node
}
}
return read { src in
Self.allocate(
return unsafe read { src in
unsafe Self.allocate(
itemMap: src.itemMap,
childMap: src.childMap,
count: self.count,
extraBytes: space
) { dstChildren, dstItems in
dstChildren.initializeAll(fromContentsOf: src.children)
dstItems.initializeAll(fromContentsOf: src.reverseItems)
unsafe dstChildren.initializeAll(fromContentsOf: src.children)
unsafe dstItems.initializeAll(fromContentsOf: src.reverseItems)
}.node
}
}
@@ -259,26 +259,26 @@ extension _HashNode {
assert(space >= 0)
let c = self.count
if isCollisionNode {
self = update { src in
Self.allocateCollision(
self = unsafe update { src in
unsafe Self.allocateCollision(
count: c, src.collisionHash
) { dstItems in
dstItems.moveInitializeAll(fromContentsOf: src.reverseItems)
src.clear()
unsafe dstItems.moveInitializeAll(fromContentsOf: src.reverseItems)
unsafe src.clear()
}.node
}
return
}
self = update { src in
Self.allocate(
self = unsafe update { src in
unsafe Self.allocate(
itemMap: src.itemMap,
childMap: src.childMap,
count: c,
extraBytes: space
) { dstChildren, dstItems in
dstChildren.moveInitializeAll(fromContentsOf: src.children)
dstItems.moveInitializeAll(fromContentsOf: src.reverseItems)
src.clear()
unsafe dstChildren.moveInitializeAll(fromContentsOf: src.children)
unsafe dstItems.moveInitializeAll(fromContentsOf: src.reverseItems)
unsafe src.clear()
}.node
}
}
@@ -17,30 +17,30 @@ extension _HashNode {
_ level: _HashLevel,
_ transform: (Value) throws -> T?
) rethrows -> _HashNode<Key, T>.Builder {
return try self.read {
return unsafe try self.read {
var result: _HashNode<Key, T>.Builder = .empty(level)
if isCollisionNode {
let items = $0.reverseItems
let items = unsafe $0.reverseItems
for i in items.indices {
if let v = try transform(items[i].value) {
result.addNewCollision(level, (items[i].key, v), $0.collisionHash)
if let v = unsafe try transform(items[i].value) {
unsafe result.addNewCollision(level, (items[i].key, v), $0.collisionHash)
}
}
return result
}
for (bucket, slot) in $0.itemMap {
let p = $0.itemPtr(at: slot)
if let v = try transform(p.pointee.value) {
result.addNewItem(level, (p.pointee.key, v), at: bucket)
for (bucket, slot) in unsafe $0.itemMap {
let p = unsafe $0.itemPtr(at: slot)
if let v = unsafe try transform(p.pointee.value) {
unsafe result.addNewItem(level, (p.pointee.key, v), at: bucket)
}
}
for (bucket, slot) in $0.childMap {
let branch = try $0[child: slot]
for (bucket, slot) in unsafe $0.childMap {
let branch = unsafe try $0[child: slot]
.compactMapValues(level.descend(), transform)
result.addNewChildBranch(level, branch, at: bucket)
unsafe result.addNewChildBranch(level, branch, at: bucket)
}
return result
}
@@ -20,35 +20,35 @@ extension _HashNode {
guard !isCollisionNode else {
return try _filter_slow(level, isIncluded)
}
return try self.read {
return unsafe try self.read {
var result: Builder = .empty(level)
var removing = false // true if we need to remove something
for (bucket, slot) in $0.itemMap {
let p = $0.itemPtr(at: slot)
let include = try isIncluded(p.pointee)
for (bucket, slot) in unsafe $0.itemMap {
let p = unsafe $0.itemPtr(at: slot)
let include = try isIncluded(unsafe p.pointee)
switch (include, removing) {
case (true, true):
result.addNewItem(level, p.pointee, at: bucket)
unsafe result.addNewItem(level, p.pointee, at: bucket)
case (false, false):
removing = true
result.copyItems(level, from: $0, upTo: bucket)
unsafe result.copyItems(level, from: $0, upTo: bucket)
default:
break
}
}
for (bucket, slot) in $0.childMap {
let branch = try $0[child: slot].filter(level.descend(), isIncluded)
for (bucket, slot) in unsafe $0.childMap {
let branch = unsafe try $0[child: slot].filter(level.descend(), isIncluded)
if let branch = branch {
assert(branch.count < self.count)
if !removing {
removing = true
result.copyItemsAndChildren(level, from: $0, upTo: bucket)
unsafe result.copyItemsAndChildren(level, from: $0, upTo: bucket)
}
result.addNewChildBranch(level, branch, at: bucket)
unsafe result.addNewChildBranch(level, branch, at: bucket)
} else if removing {
result.addNewChildNode(level, $0[child: slot], at: bucket)
unsafe result.addNewChildNode(level, $0[child: slot], at: bucket)
}
}
@@ -62,19 +62,19 @@ extension _HashNode {
_ level: _HashLevel,
_ isIncluded: (Element) throws -> Bool
) rethrows -> Builder? {
try self.read {
unsafe try self.read {
var result: Builder = .empty(level)
var removing = false
for slot: _HashSlot in stride(from: .zero, to: $0.itemsEndSlot, by: 1) {
let p = $0.itemPtr(at: slot)
let include = try isIncluded(p.pointee)
for slot: _HashSlot in stride(from: .zero, to: unsafe $0.itemsEndSlot, by: 1) {
let p = unsafe $0.itemPtr(at: slot)
let include = unsafe try isIncluded(p.pointee)
if include, removing {
result.addNewCollision(level, p.pointee, $0.collisionHash)
unsafe result.addNewCollision(level, p.pointee, $0.collisionHash)
}
else if !include, !removing {
removing = true
result.copyCollisions(from: $0, upTo: slot)
unsafe result.copyCollisions(from: $0, upTo: slot)
}
}
guard removing else { return nil }
@@ -36,68 +36,68 @@ extension _HashNode {
return _intersection_slow(level, other)
}
return self.read { l in
other.read { r in
return unsafe self.read { l in
unsafe other.read { r in
var result: Builder = .empty(level)
var removing = false
for (bucket, lslot) in l.itemMap {
let lp = l.itemPtr(at: lslot)
for (bucket, lslot) in unsafe l.itemMap {
let lp = unsafe l.itemPtr(at: lslot)
let include: Bool
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
include = (lp.pointee.key == r[item: rslot].key)
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
include = unsafe (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)
include = r[child: rslot]
else if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
let h = unsafe _Hash(lp.pointee.key)
include = unsafe r[child: rslot]
.containsKey(level.descend(), lp.pointee.key, h)
}
else { include = false}
if include, removing {
result.addNewItem(level, lp.pointee, at: bucket)
unsafe result.addNewItem(level, lp.pointee, at: bucket)
}
else if !include, !removing {
removing = true
result.copyItems(level, from: l, upTo: bucket)
unsafe result.copyItems(level, from: l, upTo: bucket)
}
}
for (bucket, lslot) in l.childMap {
if r.itemMap.contains(bucket) {
for (bucket, lslot) in unsafe l.childMap {
if unsafe r.itemMap.contains(bucket) {
if !removing {
removing = true
result.copyItemsAndChildren(level, from: l, upTo: bucket)
unsafe result.copyItemsAndChildren(level, from: l, upTo: 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 {
let item = UnsafeHandle.read(res.node) { $0[item: res.slot] }
result.addNewItem(level, item, at: bucket)
let rslot = unsafe r.itemMap.slot(of: bucket)
let rp = unsafe r.itemPtr(at: rslot)
let h = unsafe _Hash(rp.pointee.key)
let res = unsafe l[child: lslot].lookup(level.descend(), rp.pointee.key, h)
if let res = unsafe res {
let item = unsafe UnsafeHandle.read(res.node) { unsafe $0[item: res.slot] }
unsafe result.addNewItem(level, item, at: bucket)
}
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let branch = l[child: lslot]
else if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
let branch = unsafe l[child: lslot]
._intersection(level.descend(), r[child: rslot])
if let branch = branch {
assert(branch.count < self.count)
if !removing {
removing = true
result.copyItemsAndChildren(level, from: l, upTo: bucket)
unsafe result.copyItemsAndChildren(level, from: l, upTo: bucket)
}
result.addNewChildBranch(level, branch, at: bucket)
unsafe result.addNewChildBranch(level, branch, at: bucket)
} else if removing {
result.addNewChildNode(level, l[child: lslot], at: bucket)
unsafe result.addNewChildNode(level, l[child: lslot], at: bucket)
}
}
else if !removing {
removing = true
result.copyItemsAndChildren(level, from: l, upTo: bucket)
unsafe result.copyItemsAndChildren(level, from: l, upTo: bucket)
}
}
guard removing else { return nil }
@@ -114,22 +114,22 @@ extension _HashNode {
let lc = self.isCollisionNode
let rc = other.isCollisionNode
if lc && rc {
return read { l in
other.read { r in
return unsafe read { l in
unsafe other.read { r in
var result: Builder = .empty(level)
guard l.collisionHash == r.collisionHash else { return result }
guard unsafe l.collisionHash == r.collisionHash else { return result }
var removing = false
let ritems = r.reverseItems
for lslot: _HashSlot in stride(from: .zero, to: l.itemsEndSlot, by: 1) {
let lp = l.itemPtr(at: lslot)
let include = ritems.contains { $0.key == lp.pointee.key }
let ritems = unsafe r.reverseItems
for lslot: _HashSlot in stride(from: .zero, to: unsafe l.itemsEndSlot, by: 1) {
let lp = unsafe l.itemPtr(at: lslot)
let include = unsafe ritems.contains { unsafe $0.key == lp.pointee.key }
if include, removing {
result.addNewCollision(level, lp.pointee, l.collisionHash)
unsafe result.addNewCollision(level, lp.pointee, l.collisionHash)
}
else if !include, !removing {
removing = true
result.copyCollisions(from: l, upTo: lslot)
unsafe result.copyCollisions(from: l, upTo: lslot)
}
}
guard removing else { return nil }
@@ -145,21 +145,21 @@ extension _HashNode {
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 ritem = r.itemPtr(at: rslot)
let litems = l.reverseItems
let i = litems.firstIndex { $0.key == ritem.pointee.key }
return unsafe read { l in
unsafe other.read { r in
let bucket = unsafe l.collisionHash[level]
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let ritem = unsafe r.itemPtr(at: rslot)
let litems = unsafe l.reverseItems
let i = unsafe litems.firstIndex { unsafe $0.key == ritem.pointee.key }
guard let i = i else { return .empty(level) }
return .item(level, litems[i], at: l.collisionHash[level])
return unsafe .item(level, litems[i], at: l.collisionHash[level])
}
if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
return _intersection(level.descend(), r[child: rslot])
.map { .childBranch(level, $0, at: bucket) }
if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
return unsafe _intersection(level.descend(), r[child: rslot])
.map { unsafe .childBranch(level, $0, at: bucket) }
}
return .empty(level)
}
@@ -168,27 +168,27 @@ extension _HashNode {
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 litem = l.itemPtr(at: lslot)
let ritems = r.reverseItems
let found = ritems.contains { $0.key == litem.pointee.key }
return unsafe read { l in
unsafe other.read { r in
let bucket = unsafe r.collisionHash[level]
if unsafe l.itemMap.contains(bucket) {
let lslot = unsafe l.itemMap.slot(of: bucket)
let litem = unsafe l.itemPtr(at: lslot)
let ritems = unsafe r.reverseItems
let found = unsafe ritems.contains { unsafe $0.key == litem.pointee.key }
guard found else { return .empty(level) }
return .item(level, litem.pointee, at: bucket)
return unsafe .item(level, litem.pointee, at: bucket)
}
if l.childMap.contains(bucket) {
let lslot = l.childMap.slot(of: bucket)
let branch = l[child: lslot]._intersection(level.descend(), other)
if unsafe l.childMap.contains(bucket) {
let lslot = unsafe l.childMap.slot(of: bucket)
let branch = unsafe l[child: lslot]._intersection(level.descend(), other)
guard let branch = branch else {
assert(l[child: lslot].isCollisionNode)
assert(l[child: lslot].collisionHash == r.collisionHash)
assert(unsafe l[child: lslot].isCollisionNode)
assert(unsafe l[child: lslot].collisionHash == r.collisionHash)
// Compression
return .collisionNode(level, l[child: lslot])
return .collisionNode(level, unsafe l[child: lslot])
}
return .childBranch(level, branch, at: bucket)
return unsafe .childBranch(level, branch, at: bucket)
}
return .empty(level)
}
@@ -29,42 +29,42 @@ extension _HashNode {
return other._isDisjointCollision(level, with: self)
}
return self.read { l in
other.read { r in
let lmap = l.itemMap.union(l.childMap)
let rmap = r.itemMap.union(r.childMap)
if lmap.isDisjoint(with: rmap) { return true }
return unsafe self.read { l in
unsafe other.read { r in
let lmap = unsafe l.itemMap.union(l.childMap)
let rmap = unsafe r.itemMap.union(r.childMap)
if lmap.isDisjoint(with: rmap) { return true }
for (bucket, _) in l.itemMap.intersection(r.itemMap) {
let lslot = l.itemMap.slot(of: bucket)
let rslot = r.itemMap.slot(of: bucket)
guard l[item: lslot].key != r[item: rslot].key else { return false }
for (bucket, _) in unsafe l.itemMap.intersection(r.itemMap) {
let lslot = unsafe l.itemMap.slot(of: bucket)
let rslot = unsafe r.itemMap.slot(of: bucket)
guard unsafe l[item: lslot].key != r[item: rslot].key else { return false }
}
for (bucket, _) in l.itemMap.intersection(r.childMap) {
let lslot = l.itemMap.slot(of: bucket)
let hash = _Hash(l[item: lslot].key)
let rslot = r.childMap.slot(of: bucket)
let found = r[child: rslot].containsKey(
for (bucket, _) in unsafe l.itemMap.intersection(r.childMap) {
let lslot = unsafe l.itemMap.slot(of: bucket)
let hash = unsafe _Hash(l[item: lslot].key)
let rslot = unsafe r.childMap.slot(of: bucket)
let found = unsafe r[child: rslot].containsKey(
level.descend(),
l[item: lslot].key,
hash)
if found { return false }
}
for (bucket, _) in l.childMap.intersection(r.itemMap) {
let lslot = l.childMap.slot(of: bucket)
let rslot = r.itemMap.slot(of: bucket)
let hash = _Hash(r[item: rslot].key)
let found = l[child: lslot].containsKey(
for (bucket, _) in unsafe l.childMap.intersection(r.itemMap) {
let lslot = unsafe l.childMap.slot(of: bucket)
let rslot = unsafe r.itemMap.slot(of: bucket)
let hash = unsafe _Hash(r[item: rslot].key)
let found = unsafe l[child: lslot].containsKey(
level.descend(),
r[item: rslot].key,
hash)
if found { return false }
}
for (bucket, _) in l.childMap.intersection(r.childMap) {
let lslot = l.childMap.slot(of: bucket)
let rslot = r.childMap.slot(of: bucket)
for (bucket, _) in unsafe l.childMap.intersection(r.childMap) {
let lslot = unsafe l.childMap.slot(of: bucket)
let rslot = unsafe r.childMap.slot(of: bucket)
guard
l[child: lslot].isDisjoint(level.descend(), with: r[child: rslot])
unsafe l[child: lslot].isDisjoint(level.descend(), with: r[child: rslot])
else { return false }
}
return true
@@ -79,13 +79,13 @@ extension _HashNode {
) -> Bool {
assert(isCollisionNode)
if other.isCollisionNode {
return read { l in
other.read { r in
guard l.collisionHash == r.collisionHash else { return true }
let litems = l.reverseItems
let ritems = r.reverseItems
return litems.allSatisfy { li in
!ritems.contains { ri in li.key == ri.key }
return unsafe read { l in
unsafe other.read { r in
guard unsafe l.collisionHash == r.collisionHash else { return true }
let litems = unsafe l.reverseItems
let ritems = unsafe r.reverseItems
return unsafe litems.allSatisfy { li in
unsafe !ritems.contains { ri in li.key == ri.key }
}
}
}
@@ -93,18 +93,18 @@ extension _HashNode {
// `self` is on a compressed path. Try descending down by one level.
assert(!level.isAtBottom)
let bucket = self.collisionHash[level]
return other.read { r in
if r.childMap.contains(bucket) {
let slot = r.childMap.slot(of: bucket)
return isDisjoint(level.descend(), with: r[child: slot])
return unsafe other.read { r in
if unsafe r.childMap.contains(bucket) {
let slot = unsafe r.childMap.slot(of: bucket)
return unsafe isDisjoint(level.descend(), with: r[child: slot])
}
if r.itemMap.contains(bucket) {
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 }
return !l.reverseItems.contains { $0.key == p.pointee.key }
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let p = unsafe r.itemPtr(at: rslot)
let hash = unsafe _Hash(p.pointee.key)
return unsafe read { l in
guard unsafe hash == l.collisionHash else { return true }
return unsafe !l.reverseItems.contains { unsafe $0.key == p.pointee.key }
}
}
return true
@@ -24,15 +24,15 @@ extension _HashNode {
if self.isCollisionNode {
guard other.isCollisionNode else { return false }
return self.read { lhs in
other.read { rhs in
guard lhs.collisionHash == rhs.collisionHash else { return false }
let l = lhs.reverseItems
let r = rhs.reverseItems
return unsafe self.read { lhs in
unsafe other.read { rhs in
guard unsafe lhs.collisionHash == rhs.collisionHash else { return false }
let l = unsafe lhs.reverseItems
let r = unsafe rhs.reverseItems
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)
let found = unsafe r.contains {
unsafe l[i].key == $0.key && areEquivalent(l[i].value, $0.value)
}
guard found else { return false }
}
@@ -42,19 +42,19 @@ extension _HashNode {
}
guard !other.isCollisionNode else { return false }
return self.read { l in
other.read { r in
guard l.itemMap == r.itemMap else { return false }
guard l.childMap == r.childMap else { return false }
return unsafe self.read { l in
unsafe other.read { r in
guard unsafe l.itemMap == r.itemMap else { return false }
guard unsafe l.childMap == r.childMap else { return false }
guard l.reverseItems.elementsEqual(
guard unsafe l.reverseItems.elementsEqual(
r.reverseItems,
by: { $0.key == $1.key && areEquivalent($0.value, $1.value) })
else { return false }
let lc = l.children
let rc = r.children
return lc.elementsEqual(
let lc = unsafe l.children
let rc = unsafe r.children
return unsafe lc.elementsEqual(
rc,
by: { $0.isEqualSet(to: $1, by: areEquivalent) })
}
@@ -26,12 +26,12 @@ extension _HashNode {
if self.isCollisionNode {
if other.isCollisionNode {
guard self.collisionHash == other.collisionHash else { return false }
return read { l in
other.read { r in
let li = l.reverseItems
let ri = r.reverseItems
return l.reverseItems.indices.allSatisfy { i in
ri.contains { $0.key == li[i].key }
return unsafe read { l in
unsafe other.read { r in
let li = unsafe l.reverseItems
let ri = unsafe r.reverseItems
return unsafe l.reverseItems.indices.allSatisfy { i in
unsafe ri.contains { unsafe $0.key == li[i].key }
}
}
}
@@ -39,39 +39,39 @@ extension _HashNode {
// `self` is on a compressed path. Try to descend down by one level.
assert(!level.isAtBottom)
let bucket = self.collisionHash[level]
return other.read {
guard $0.childMap.contains(bucket) else { return false }
let slot = $0.childMap.slot(of: bucket)
return self.isSubset(level.descend(), of: $0[child: slot])
return unsafe other.read {
guard unsafe $0.childMap.contains(bucket) else { return false }
let slot = unsafe $0.childMap.slot(of: bucket)
return unsafe self.isSubset(level.descend(), of: $0[child: slot])
}
}
if other.isCollisionNode {
return read { l in
guard level.isAtRoot, l.hasSingletonItem else { return false }
return unsafe read { l in
guard level.isAtRoot, unsafe 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 unsafe other.read { r in
let hash = unsafe _Hash(l[item: .zero].key)
return unsafe r.find(level, l[item: .zero].key, hash) != nil
}
}
}
return self.read { l in
other.read { r in
guard l.childMap.isSubset(of: r.childMap) else { return false }
guard l.itemMap.isSubset(of: r.itemMap.union(r.childMap)) else {
return unsafe self.read { l in
unsafe other.read { r in
guard unsafe l.childMap.isSubset(of: r.childMap) else { return false }
guard unsafe l.itemMap.isSubset(of: r.itemMap.union(r.childMap)) else {
return false
}
for (bucket, lslot) in l.itemMap {
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
guard l[item: lslot].key == r[item: rslot].key else { return false }
for (bucket, lslot) in unsafe l.itemMap {
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
guard unsafe l[item: lslot].key == r[item: rslot].key else { return false }
} else {
let hash = _Hash(l[item: lslot].key)
let rslot = r.childMap.slot(of: bucket)
let hash = unsafe _Hash(l[item: lslot].key)
let rslot = unsafe r.childMap.slot(of: bucket)
guard
r[child: rslot].containsKey(
unsafe r[child: rslot].containsKey(
level.descend(),
l[item: lslot].key,
hash)
@@ -79,9 +79,9 @@ extension _HashNode {
}
}
for (bucket, lslot) in l.childMap {
let rslot = r.childMap.slot(of: bucket)
guard l[child: lslot].isSubset(level.descend(), of: r[child: rslot])
for (bucket, lslot) in unsafe l.childMap {
let rslot = unsafe r.childMap.slot(of: bucket)
guard unsafe l[child: lslot].isSubset(level.descend(), of: r[child: rslot])
else { return false }
}
return true
@@ -21,28 +21,28 @@ extension _HashNode {
_ transform: (Element) throws -> T
) rethrows -> _HashNode<Key, T> {
let c = self.count
return try read { source in
return unsafe try read { source in
var result: _HashNode<Key, T>
if isCollisionNode {
result = _HashNode<Key, T>.allocateCollision(
result = unsafe _HashNode<Key, T>.allocateCollision(
count: c, source.collisionHash,
initializingWith: { _ in }
).node
} else {
result = _HashNode<Key, T>.allocate(
result = unsafe _HashNode<Key, T>.allocate(
itemMap: source.itemMap,
childMap: source.childMap,
count: c,
initializingWith: { _, _ in }
).node
}
try result.update { target in
let sourceItems = source.reverseItems
let targetItems = target.reverseItems
unsafe try result.update { target in
let sourceItems = unsafe source.reverseItems
let targetItems = unsafe target.reverseItems
assert(sourceItems.count == targetItems.count)
let sourceChildren = source.children
let targetChildren = target.children
let sourceChildren = unsafe source.children
let targetChildren = unsafe target.children
assert(sourceChildren.count == targetChildren.count)
var i = 0
@@ -52,21 +52,21 @@ extension _HashNode {
defer {
if !success {
targetItems.prefix(i).deinitialize()
targetChildren.prefix(j).deinitialize()
target.clear()
unsafe targetItems.prefix(i).deinitialize()
unsafe targetChildren.prefix(j).deinitialize()
unsafe target.clear()
}
}
while i < targetItems.count {
let key = sourceItems[i].key
let value = try transform(sourceItems[i])
targetItems.initializeElement(at: i, to: (key, value))
let key = unsafe sourceItems[i].key
let value = unsafe try transform(sourceItems[i])
unsafe targetItems.initializeElement(at: i, to: (key, value))
i += 1
}
while j < targetChildren.count {
let child = try sourceChildren[j].mapValues(transform)
targetChildren.initializeElement(at: j, to: child)
let child = unsafe try sourceChildren[j].mapValues(transform)
unsafe targetChildren.initializeElement(at: j, to: child)
j += 1
}
success = true
@@ -81,7 +81,7 @@ extension _HashNode {
copy: Bool = false, extraBytes: Int = 0
) -> _HashNode<Key, Void> {
if Value.self == Void.self {
let node = unsafeBitCast(self, to: _HashNode<Key, Void>.self)
let node = unsafe unsafeBitCast(self, to: _HashNode<Key, Void>.self)
guard copy || !node.hasFreeSpace(extraBytes) else { return node }
return node.copy(withFreeSpace: extraBytes)
}
@@ -29,21 +29,21 @@ extension _HashNode {
// during the merge process. Prevent this from causing issues below by
// handling it up front.
var copy = other
let delta = try self.read { l in
let lp = l.itemPtr(at: .zero)
let delta = unsafe try self.read { l in
let lp = unsafe l.itemPtr(at: .zero)
let c = copy.count
let res = copy.updateValue(
let res = unsafe copy.updateValue(
level, forKey: lp.pointee.key, _Hash(lp.pointee.key)
) {
$0.initialize(to: lp.pointee)
unsafe $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)
if unsafe !res.inserted {
unsafe try UnsafeHandle.update(res.leaf) {
let p = unsafe $0.itemPtr(at: res.slot)
unsafe p.pointee.value = try combine(lp.pointee.value, p.pointee.value)
}
}
return c - (res.inserted ? 0 : 1)
return unsafe c - (res.inserted ? 0 : 1)
}
self = copy
return delta
@@ -65,35 +65,35 @@ extension _HashNode {
return try _merge_slow(level, other, combine)
}
return try other.read { r in
return unsafe try other.read { r in
var isUnique = self.isUnique()
var delta = 0
let (originalItems, originalChildren) = self.read {
($0.itemMap, $0.childMap)
let (originalItems, originalChildren) = unsafe self.read {
unsafe ($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 unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let rp = unsafe r.itemPtr(at: rslot)
let lslot = unsafe self.read { unsafe $0.itemMap.slot(of: bucket) }
let conflict = unsafe self.read { unsafe $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)
unsafe try self.update {
let p = unsafe $0.itemPtr(at: lslot)
unsafe p.pointee.value = try combine(p.pointee.value, rp.pointee.value)
}
} else {
_ = self.ensureUniqueAndSpawnChild(
_ = unsafe self.ensureUniqueAndSpawnChild(
isUnique: isUnique,
level: level,
replacing: bucket,
itemSlot: lslot,
newHash: _Hash(rp.pointee.key),
{ $0.initialize(to: rp.pointee) })
{ unsafe $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.
@@ -102,27 +102,27 @@ extension _HashNode {
}
isUnique = true
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let rp = r.childPtr(at: rslot)
else if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
let rp = unsafe r.childPtr(at: rslot)
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _HashNode.spaceForSpawningChild)
let item = self.removeItem(at: bucket)
let item = unsafe self.removeItem(at: bucket)
delta &-= 1
var child = rp.pointee
let r = child.updateValue(
var child = unsafe rp.pointee
let r = unsafe child.updateValue(
level.descend(), forKey: item.key, _Hash(item.key)
) {
$0.initialize(to: item)
unsafe $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)
if unsafe !r.inserted {
try unsafe UnsafeHandle.update(r.leaf) {
let p = unsafe $0.itemPtr(at: r.slot)
unsafe p.pointee.value = try combine(item.value, p.pointee.value)
}
}
self.insertChild(child, bucket)
unsafe self.insertChild(child, bucket)
isUnique = true
delta &+= child.count
}
@@ -130,36 +130,36 @@ extension _HashNode {
for (bucket, _) in originalChildren {
assert(!isCollisionNode)
let lslot = self.read { $0.childMap.slot(of: bucket) }
let lslot = unsafe self.read { unsafe $0.childMap.slot(of: bucket) }
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let rp = unsafe r.itemPtr(at: rslot)
self.ensureUnique(isUnique: isUnique)
let h = _Hash(rp.pointee.key)
let res = self.update { l in
l[child: lslot].updateValue(
let h = unsafe _Hash(rp.pointee.key)
let res = unsafe self.update { l in
unsafe l[child: lslot].updateValue(
level.descend(), forKey: rp.pointee.key, h
) {
$0.initialize(to: rp.pointee)
unsafe $0.initialize(to: rp.pointee)
}
}
if res.inserted {
if unsafe res.inserted {
self.count &+= 1
delta &+= 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)
unsafe try UnsafeHandle.update(res.leaf) {
let p = unsafe $0.itemPtr(at: res.slot)
unsafe 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)
else if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
self.ensureUnique(isUnique: isUnique)
let d = try self.update { l in
try l[child: lslot].merge(
let d = unsafe try self.update { l in
unsafe try l[child: lslot].merge(
level.descend(),
r[child: rslot],
combine)
@@ -173,20 +173,20 @@ extension _HashNode {
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(
let seen = unsafe self.read { l in unsafe l.itemMap.union(l.childMap) }
for (bucket, _) in unsafe r.itemMap.subtracting(seen) {
let rslot = unsafe r.itemMap.slot(of: bucket)
unsafe self.ensureUniqueAndInsertItem(
isUnique: isUnique, r[item: rslot], at: bucket)
delta &+= 1
isUnique = true
}
for (bucket, _) in r.childMap.subtracting(seen) {
let rslot = r.childMap.slot(of: bucket)
for (bucket, _) in unsafe r.childMap.subtracting(seen) {
let rslot = unsafe r.childMap.slot(of: bucket)
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild)
self.insertChild(r[child: rslot], bucket)
delta &+= r[child: rslot].count
unsafe self.insertChild(r[child: rslot], bucket)
unsafe delta &+= r[child: rslot].count
isUnique = true
}
@@ -211,27 +211,27 @@ extension _HashNode {
child2: other, other.collisionHash)
return other.count
}
return try other.read { r in
return unsafe try other.read { r in
var isUnique = self.isUnique()
var delta = 0
let originalItemCount = self.count
for rs: _HashSlot in stride(from: .zero, to: r.itemsEndSlot, by: 1) {
let rp = r.itemPtr(at: rs)
let lslot: _HashSlot? = self.read { l in
let litems = l.reverseItems
return litems
for rs: _HashSlot in stride(from: .zero, to: unsafe r.itemsEndSlot, by: 1) {
let rp = unsafe r.itemPtr(at: rs)
let lslot: _HashSlot? = unsafe self.read { l in
let litems = unsafe l.reverseItems
return unsafe litems
.suffix(originalItemCount)
.firstIndex { $0.key == rp.pointee.key }
.firstIndex { unsafe $0.key == rp.pointee.key }
.map { _HashSlot(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)
unsafe try self.update {
let p = unsafe $0.itemPtr(at: lslot)
unsafe p.pointee.value = try combine(p.pointee.value, rp.pointee.value)
}
} else {
_ = self.ensureUniqueAndAppendCollision(
_ = unsafe self.ensureUniqueAndAppendCollision(
isUnique: isUnique, rp.pointee)
delta &+= 1
}
@@ -247,41 +247,41 @@ extension _HashNode {
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
return unsafe 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)
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let rp = unsafe r.itemPtr(at: rslot)
let h = _Hash(rp.pointee.key)
let res = self.updateValue(
let h = unsafe _Hash(rp.pointee.key)
let res = unsafe self.updateValue(
level.descend(), forKey: rp.pointee.key, h
) {
$0.initialize(to: rp.pointee)
unsafe $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)
if unsafe !res.inserted {
unsafe try UnsafeHandle.update(res.leaf) {
let p = unsafe $0.itemPtr(at: res.slot)
unsafe p.pointee.value = try combine(p.pointee.value, rp.pointee.value)
}
}
self = other._copyNodeAndReplaceItemWithNewChild(
self = unsafe other._copyNodeAndReplaceItemWithNewChild(
level: level, self, at: bucket, itemSlot: rslot)
return other.count - (res.inserted ? 0 : 1)
return unsafe other.count - (res.inserted ? 0 : 1)
}
if r.childMap.contains(bucket) {
if unsafe r.childMap.contains(bucket) {
let originalCount = self.count
let rslot = r.childMap.slot(of: bucket)
_ = try self._merge(level.descend(), r[child: rslot], combine)
let rslot = unsafe r.childMap.slot(of: bucket)
_ = unsafe try self._merge(level.descend(), r[child: rslot], combine)
var node = other.copy()
_ = node.replaceChild(at: bucket, rslot, with: self)
_ = unsafe node.replaceChild(at: bucket, rslot, with: self)
self = node
return self.count - originalCount
}
var node = other.copy(withFreeSpace: _HashNode.spaceForNewChild)
node.insertChild(self, bucket)
unsafe node.insertChild(self, bucket)
self = node
return other.count
}
@@ -290,33 +290,33 @@ extension _HashNode {
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) }) {
return unsafe try other.read { r in
let bucket = unsafe r.collisionHash[level]
if unsafe self.read({ unsafe $0.itemMap.contains(bucket) }) {
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _HashNode.spaceForSpawningChild)
let item = self.removeItem(at: bucket)
let item = unsafe 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)
let res = unsafe copy.updateValue(level.descend(), forKey: item.key, h) {
unsafe $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)
if unsafe !res.inserted {
unsafe try UnsafeHandle.update(res.leaf) {
let p = unsafe $0.itemPtr(at: res.slot)
unsafe 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 other.count - (res.inserted ? 0 : 1)
unsafe self.insertChild(copy, bucket)
return unsafe other.count - (res.inserted ? 0 : 1)
}
if self.read({ $0.childMap.contains(bucket) }) {
if unsafe self.read({ unsafe $0.childMap.contains(bucket) }) {
self.ensureUnique(isUnique: isUnique)
let delta: Int = try self.update { l in
let lslot = l.childMap.slot(of: bucket)
let lchild = l.childPtr(at: lslot)
return try lchild.pointee._merge(level.descend(), other, combine)
let delta: Int = unsafe try self.update { l in
let lslot = unsafe l.childMap.slot(of: bucket)
let lchild = unsafe l.childPtr(at: lslot)
return unsafe try lchild.pointee._merge(level.descend(), other, combine)
}
assert(delta >= 0)
self.count &+= delta
@@ -324,7 +324,7 @@ extension _HashNode {
}
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild)
self.insertChild(other, bucket)
unsafe self.insertChild(other, bucket)
return other.count
}
}
@@ -36,22 +36,22 @@ extension _HashNode {
return _subtracting_slow(level, other)
}
return self.read { l in
other.read { r in
return unsafe self.read { l in
unsafe other.read { r in
var result: Builder = .empty(level)
var removing = false
for (bucket, lslot) in l.itemMap {
let lp = l.itemPtr(at: lslot)
for (bucket, lslot) in unsafe l.itemMap {
let lp = unsafe l.itemPtr(at: lslot)
let include: Bool
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
include = (lp.pointee.key != r[item: rslot].key)
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
include = unsafe (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)
include = !r[child: rslot]
else if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
let h = unsafe _Hash(lp.pointee.key)
include = unsafe !r[child: rslot]
.containsKey(level.descend(), lp.pointee.key, h)
}
else {
@@ -59,48 +59,48 @@ extension _HashNode {
}
if include, removing {
result.addNewItem(level, lp.pointee, at: bucket)
unsafe result.addNewItem(level, lp.pointee, at: bucket)
}
else if !include, !removing {
removing = true
result.copyItems(level, from: l, upTo: bucket)
unsafe result.copyItems(level, from: l, upTo: bucket)
}
}
for (bucket, lslot) in l.childMap {
for (bucket, lslot) in unsafe l.childMap {
var done = false
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 = l[child: lslot]
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let rp = unsafe r.itemPtr(at: rslot)
let h = unsafe _Hash(rp.pointee.key)
let child = unsafe l[child: lslot]
.removing(level.descend(), rp.pointee.key, h)?.replacement
if let child = child {
assert(child.count < self.count)
if !removing {
removing = true
result.copyItemsAndChildren(level, from: l, upTo: bucket)
unsafe result.copyItemsAndChildren(level, from: l, upTo: bucket)
}
result.addNewChildBranch(level, child, at: bucket)
unsafe result.addNewChildBranch(level, child, at: bucket)
done = true
}
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let child = l[child: lslot]
else if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
let child = unsafe l[child: lslot]
._subtracting(level.descend(), r[child: rslot])
if let child = child {
assert(child.count < self.count)
if !removing {
removing = true
result.copyItemsAndChildren(level, from: l, upTo: bucket)
unsafe result.copyItemsAndChildren(level, from: l, upTo: bucket)
}
result.addNewChildBranch(level, child, at: bucket)
unsafe result.addNewChildBranch(level, child, at: bucket)
done = true
}
}
if !done, removing {
result.addNewChildNode(level, l[child: lslot], at: bucket)
unsafe result.addNewChildNode(level, l[child: lslot], at: bucket)
}
}
guard removing else { return nil }
@@ -117,24 +117,24 @@ extension _HashNode {
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 unsafe read { l in
unsafe other.read { r in
guard unsafe l.collisionHash == r.collisionHash else {
return nil
}
var result: Builder = .empty(level)
var removing = false
let ritems = r.reverseItems
for lslot: _HashSlot in stride(from: .zero, to: l.itemsEndSlot, by: 1) {
let lp = l.itemPtr(at: lslot)
let include = !ritems.contains { $0.key == lp.pointee.key }
let ritems = unsafe r.reverseItems
for lslot: _HashSlot in stride(from: .zero, to: unsafe l.itemsEndSlot, by: 1) {
let lp = unsafe l.itemPtr(at: lslot)
let include = unsafe !ritems.contains { unsafe $0.key == lp.pointee.key }
if include, removing {
result.addNewCollision(level, lp.pointee, l.collisionHash)
unsafe result.addNewCollision(level, lp.pointee, l.collisionHash)
}
else if !include, !removing {
removing = true
result.copyCollisions(from: l, upTo: lslot)
unsafe result.copyCollisions(from: l, upTo: lslot)
}
}
guard removing else { return nil }
@@ -150,22 +150,22 @@ extension _HashNode {
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 ritem = r.itemPtr(at: rslot)
let h = _Hash(ritem.pointee.key)
let res = l.find(level, ritem.pointee.key, h)
return unsafe read { l in
unsafe other.read { r in
let bucket = unsafe l.collisionHash[level]
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let ritem = unsafe r.itemPtr(at: rslot)
let h = unsafe _Hash(ritem.pointee.key)
let res = unsafe l.find(level, ritem.pointee.key, h)
guard let res = res else { return nil }
return self._removingItemFromLeaf(level, at: bucket, res.slot)
return unsafe self._removingItemFromLeaf(level, at: bucket, res.slot)
.replacement
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
return _subtracting(level.descend(), r[child: rslot])
.map { .childBranch(level, $0, at: bucket) }
else if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
return unsafe _subtracting(level.descend(), r[child: rslot])
.map { unsafe .childBranch(level, $0, at: bucket) }
}
return nil
}
@@ -174,24 +174,24 @@ extension _HashNode {
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 litem = l.itemPtr(at: lslot)
let h = _Hash(litem.pointee.key)
let res = r.find(level, litem.pointee.key, h)
return unsafe read { l in
unsafe other.read { r in
let bucket = unsafe r.collisionHash[level]
if unsafe l.itemMap.contains(bucket) {
let lslot = unsafe l.itemMap.slot(of: bucket)
let litem = unsafe l.itemPtr(at: lslot)
let h = unsafe _Hash(litem.pointee.key)
let res = unsafe r.find(level, litem.pointee.key, h)
if res == nil { return nil }
return self._removingItemFromLeaf(level, at: bucket, lslot)
return unsafe self._removingItemFromLeaf(level, at: bucket, lslot)
.replacement
}
if l.childMap.contains(bucket) {
let lslot = l.childMap.slot(of: bucket)
let branch = l[child: lslot]._subtracting(level.descend(), other)
if unsafe l.childMap.contains(bucket) {
let lslot = unsafe l.childMap.slot(of: bucket)
let branch = unsafe l[child: lslot]._subtracting(level.descend(), other)
guard let branch = branch else { return nil }
var result = self._removingChild(level, at: bucket, lslot)
result.addNewChildBranch(level, branch, at: bucket)
var result = unsafe self._removingChild(level, at: bucket, lslot)
unsafe result.addNewChildBranch(level, branch, at: bucket)
return result
}
return nil
@@ -40,89 +40,89 @@ extension _HashNode {
return _symmetricDifference_slow(level, other)
}
return self.read { l in
other.read { r in
return unsafe self.read { l in
unsafe other.read { r in
var result: VoidNode.Builder = .empty(level)
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 = VoidNode.build(
for (bucket, lslot) in unsafe l.itemMap {
let lp = unsafe l.itemPtr(at: lslot)
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let rp = unsafe r.itemPtr(at: rslot)
if unsafe lp.pointee.key != rp.pointee.key {
let h1 = unsafe _Hash(lp.pointee.key)
let h2 = unsafe _Hash(rp.pointee.key)
let child = unsafe VoidNode.build(
level: level.descend(),
item1: (lp.pointee.key, ()), h1,
item2: { $0.initialize(to: (rp.pointee.key, ())) }, h2)
result.addNewChildNode(level, child.top, at: bucket)
item2: { unsafe $0.initialize(to: (rp.pointee.key, ())) }, h2)
unsafe result.addNewChildNode(level, child.top, at: bucket)
}
}
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
else if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
let rp = unsafe r.childPtr(at: rslot)
let h = unsafe _Hash(lp.pointee.key)
let child = unsafe rp.pointee
.removing(level.descend(), lp.pointee.key, h)?.replacement
if let child = child {
let child = child.mapValuesToVoid()
result.addNewChildBranch(level, child, at: bucket)
unsafe result.addNewChildBranch(level, child, at: bucket)
}
else {
var child2 = rp.pointee
var child2 = unsafe rp.pointee
.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
let r = child2.insert(level.descend(), (lp.pointee.key, ()), h)
assert(r.inserted)
result.addNewChildNode(level, child2, at: bucket)
let r = unsafe child2.insert(level.descend(), (lp.pointee.key, ()), h)
assert(unsafe r.inserted)
unsafe result.addNewChildNode(level, child2, at: bucket)
}
}
else {
result.addNewItem(level, (lp.pointee.key, ()), at: bucket)
unsafe result.addNewItem(level, (lp.pointee.key, ()), at: bucket)
}
}
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
for (bucket, lslot) in unsafe l.childMap {
let lp = unsafe l.childPtr(at: lslot)
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let rp = unsafe r.itemPtr(at: rslot)
let h = unsafe _Hash(rp.pointee.key)
let child = unsafe lp.pointee
.mapValuesToVoid()
.removing(level.descend(), rp.pointee.key, h)?.replacement
if let child = child {
result.addNewChildBranch(level, child, at: bucket)
unsafe result.addNewChildBranch(level, child, at: bucket)
}
else {
var child2 = lp.pointee.mapValuesToVoid(
var child2 = unsafe lp.pointee.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
let r2 = child2.insert(level.descend(), (rp.pointee.key, ()), h)
assert(r2.inserted)
result.addNewChildNode(level, child2, at: bucket)
let r2 = unsafe child2.insert(level.descend(), (rp.pointee.key, ()), h)
assert(unsafe r2.inserted)
unsafe result.addNewChildNode(level, child2, at: bucket)
}
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let b = l[child: lslot]._symmetricDifference(
else if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
let b = unsafe l[child: lslot]._symmetricDifference(
level.descend(), r[child: rslot])
result.addNewChildBranch(level, b, at: bucket)
unsafe result.addNewChildBranch(level, b, at: bucket)
}
else {
result.addNewChildNode(
unsafe result.addNewChildNode(
level, lp.pointee.mapValuesToVoid(), at: bucket)
}
}
let seen = l.itemMap.union(l.childMap)
for (bucket, rslot) in r.itemMap {
let seen = unsafe l.itemMap.union(l.childMap)
for (bucket, rslot) in unsafe r.itemMap {
guard !seen.contains(bucket) else { continue }
result.addNewItem(level, (r[item: rslot].key, ()), at: bucket)
unsafe result.addNewItem(level, (r[item: rslot].key, ()), at: bucket)
}
for (bucket, rslot) in r.childMap {
for (bucket, rslot) in unsafe r.childMap {
guard !seen.contains(bucket) else { continue }
result.addNewChildNode(
unsafe result.addNewChildNode(
level, r[child: rslot].mapValuesToVoid(), at: bucket)
}
return result
@@ -151,32 +151,32 @@ extension _HashNode {
_ other: _HashNode<Key, Value2>
) -> _HashNode<Key, Void>.Builder {
typealias VoidNode = _HashNode<Key, Void>
return read { l in
other.read { r in
guard l.collisionHash == r.collisionHash else {
let node = VoidNode.build(
return unsafe read { l in
unsafe other.read { r in
guard unsafe l.collisionHash == r.collisionHash else {
let node = unsafe VoidNode.build(
level: level,
child1: self.mapValuesToVoid(), l.collisionHash,
child2: other.mapValuesToVoid(), r.collisionHash)
return .node(level, node)
}
var result: VoidNode.Builder = .empty(level)
let ritems = r.reverseItems
for ls: _HashSlot 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 })
let ritems = unsafe r.reverseItems
for ls: _HashSlot in stride(from: .zero, to: unsafe l.itemsEndSlot, by: 1) {
let lp = unsafe l.itemPtr(at: ls)
let include = unsafe !ritems.contains(where: { unsafe $0.key == lp.pointee.key })
if include {
result.addNewCollision(level, (lp.pointee.key, ()), l.collisionHash)
unsafe result.addNewCollision(level, (lp.pointee.key, ()), l.collisionHash)
}
}
// FIXME: Consider remembering slots of shared items in r by
// caching them in a bitset.
let litems = l.reverseItems
for rs: _HashSlot 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 })
let litems = unsafe l.reverseItems
for rs: _HashSlot in stride(from: .zero, to: unsafe r.itemsEndSlot, by: 1) {
let rp = unsafe r.itemPtr(at: rs)
let include = unsafe !litems.contains(where: { unsafe $0.key == rp.pointee.key })
if include {
result.addNewCollision(level, (rp.pointee.key, ()), r.collisionHash)
unsafe result.addNewCollision(level, (rp.pointee.key, ()), r.collisionHash)
}
}
return result
@@ -192,77 +192,77 @@ extension _HashNode {
typealias VoidNode = _HashNode<Key, Void>
// `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
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 rh = _Hash(rp.pointee.key)
guard rh == l.collisionHash else {
return unsafe read { l in
unsafe other.read { r in
assert(unsafe l.isCollisionNode && !r.isCollisionNode)
let bucket = unsafe l.collisionHash[level]
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let rp = unsafe r.itemPtr(at: rslot)
let rh = unsafe _Hash(rp.pointee.key)
guard unsafe rh == l.collisionHash else {
var copy = other.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForSpawningChild)
let item = copy.removeItem(at: bucket, rslot)
let child = VoidNode.build(
let item = unsafe copy.removeItem(at: bucket, rslot)
let child = unsafe VoidNode.build(
level: level.descend(),
item1: { $0.initialize(to: (item.key, ())) }, rh,
item1: { unsafe $0.initialize(to: (item.key, ())) }, rh,
child2: self.mapValuesToVoid(), l.collisionHash)
copy.insertChild(child.top, bucket)
unsafe copy.insertChild(child.top, bucket)
return .node(level, copy)
}
let litems = l.reverseItems
if let li = litems.firstIndex(where: { $0.key == rp.pointee.key }) {
if l.itemCount == 2 {
let litems = unsafe l.reverseItems
if let li = unsafe litems.firstIndex(where: { unsafe $0.key == rp.pointee.key }) {
if unsafe l.itemCount == 2 {
var node = other.mapValuesToVoid(copy: true)
node.replaceItem(
unsafe node.replaceItem(
at: bucket, rslot,
with: (litems[1 &- li].key, ()))
return .node(level, node)
}
let lslot = _HashSlot(litems.count &- 1 &- li)
var child = self.mapValuesToVoid(copy: true)
_ = child.removeItem(at: .invalid, lslot)
_ = unsafe child.removeItem(at: .invalid, lslot)
if other.hasSingletonItem {
// Compression
return .collisionNode(level, child)
}
var node = other.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForSpawningChild)
_ = node.removeItem(at: bucket, rslot)
node.insertChild(child, bucket)
_ = unsafe node.removeItem(at: bucket, rslot)
unsafe node.insertChild(child, bucket)
return .node(level, node)
}
if other.hasSingletonItem {
// Compression
var copy = self.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
_ = copy.ensureUniqueAndAppendCollision(
_ = unsafe copy.ensureUniqueAndAppendCollision(
isUnique: true,
(r[item: .zero].key, ()))
return .collisionNode(level, copy)
}
var node = other.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForSpawningChild)
let item = node.removeItem(at: bucket, rslot)
let item = unsafe node.removeItem(at: bucket, rslot)
var child = self.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
_ = child.ensureUniqueAndAppendCollision(
_ = unsafe child.ensureUniqueAndAppendCollision(
isUnique: true, (item.key, ()))
node.insertChild(child, bucket)
unsafe node.insertChild(child, bucket)
return .node(level, node)
}
if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let rp = r.childPtr(at: rslot)
let child = rp.pointee._symmetricDifference(level.descend(), self)
return other
if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
let rp = unsafe r.childPtr(at: rslot)
let child = unsafe rp.pointee._symmetricDifference(level.descend(), self)
return unsafe other
.mapValuesToVoid()
.replacingChild(level, at: bucket, rslot, with: child)
}
var node = other
.mapValuesToVoid(copy: true, extraBytes: VoidNode.spaceForNewChild)
node.insertChild(self.mapValuesToVoid(), bucket)
unsafe node.insertChild(self.mapValuesToVoid(), bucket)
return .node(level, node)
}
}
@@ -23,17 +23,17 @@ extension _HashNode {
// 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)
return unsafe self.read { l in
let lp = unsafe l.itemPtr(at: .zero)
var copy = other.mapValuesToVoid(copy: true)
let r = copy.updateValue(
let r = unsafe copy.updateValue(
level, forKey: lp.pointee.key, _Hash(lp.pointee.key)
) {
$0.initialize(to: (lp.pointee.key, ()))
unsafe $0.initialize(to: (lp.pointee.key, ()))
}
if !r.inserted {
UnsafeHandle.update(r.leaf) {
$0[item: r.slot] = lp.pointee
if unsafe !r.inserted {
unsafe UnsafeHandle.update(r.leaf) {
unsafe $0[item: r.slot] = lp.pointee
}
}
return (true, copy)
@@ -55,29 +55,29 @@ extension _HashNode {
return _union_slow(level, other)
}
return self.read { l in
other.read { r in
return unsafe self.read { l in
unsafe other.read { r in
var node = self.mapValuesToVoid()
var copied = false
for (bucket, lslot) in l.itemMap {
for (bucket, lslot) in unsafe l.itemMap {
assert(!node.isCollisionNode)
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 {
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let lp = unsafe l.itemPtr(at: lslot)
let rp = unsafe r.itemPtr(at: rslot)
if unsafe lp.pointee.key != rp.pointee.key {
let slot = (
copied
? node.read { $0.itemMap.slot(of: bucket) }
? unsafe node.read { unsafe $0.itemMap.slot(of: bucket) }
: lslot)
_ = node.ensureUniqueAndSpawnChild(
_ = unsafe node.ensureUniqueAndSpawnChild(
isUnique: copied,
level: level,
replacing: bucket,
itemSlot: slot,
newHash: _Hash(rp.pointee.key),
{ $0.initialize(to: (rp.pointee.key, ())) })
{ unsafe $0.initialize(to: (rp.pointee.key, ())) })
// 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.
@@ -85,46 +85,46 @@ extension _HashNode {
copied = true
}
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let rp = r.childPtr(at: rslot)
else if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
let rp = unsafe r.childPtr(at: rslot)
node.ensureUnique(
isUnique: copied, withFreeSpace: _HashNode.spaceForSpawningChild)
let item = node.removeItem(at: bucket)
let r = rp.pointee.mapValuesToVoid()
let item = unsafe node.removeItem(at: bucket)
let r = unsafe rp.pointee.mapValuesToVoid()
.inserting(level.descend(), (item.key, ()), _Hash(item.key))
node.insertChild(r.node, bucket)
unsafe node.insertChild(r.node, bucket)
copied = true
}
}
for (bucket, lslot) in l.childMap {
for (bucket, lslot) in unsafe l.childMap {
assert(!node.isCollisionNode)
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].mapValuesToVoid()
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let rp = unsafe r.itemPtr(at: rslot)
let h = unsafe _Hash(rp.pointee.key)
let r = unsafe l[child: lslot].mapValuesToVoid()
.inserting(level.descend(), (rp.pointee.key, ()), h)
guard r.inserted else {
guard unsafe r.inserted else {
// Nothing to do
continue
}
node.ensureUnique(isUnique: copied)
let delta = node.replaceChild(at: bucket, with: r.node)
let delta = unsafe node.replaceChild(at: bucket, with: r.node)
assert(delta == 1)
copied = true
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let child = l[child: lslot]._union(level.descend(), r[child: rslot])
else if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
let child = unsafe l[child: lslot]._union(level.descend(), r[child: rslot])
guard child.copied else {
// Nothing to do
continue
}
node.ensureUnique(isUnique: copied)
let delta = node.replaceChild(at: bucket, with: child.node)
let delta = unsafe node.replaceChild(at: bucket, with: child.node)
assert(delta > 0) // If we didn't add an item, why did we copy?
copied = true
}
@@ -133,20 +133,20 @@ extension _HashNode {
assert(!node.isCollisionNode)
/// Add buckets in `other` that we haven't processed above.
let seen = l.itemMap.union(l.childMap)
let seen = unsafe l.itemMap.union(l.childMap)
for (bucket, _) in r.itemMap.subtracting(seen) {
let rslot = r.itemMap.slot(of: bucket)
node.ensureUniqueAndInsertItem(
for (bucket, _) in unsafe r.itemMap.subtracting(seen) {
let rslot = unsafe r.itemMap.slot(of: bucket)
unsafe node.ensureUniqueAndInsertItem(
isUnique: copied, (r[item: rslot].key, ()), at: bucket)
copied = true
}
for (bucket, _) in r.childMap.subtracting(seen) {
let rslot = r.childMap.slot(of: bucket)
for (bucket, _) in unsafe r.childMap.subtracting(seen) {
let rslot = unsafe r.childMap.slot(of: bucket)
node.ensureUnique(
isUnique: copied, withFreeSpace: _HashNode.spaceForNewChild)
copied = true
node.insertChild(r[child: rslot].mapValuesToVoid(), bucket)
unsafe node.insertChild(r[child: rslot].mapValuesToVoid(), bucket)
}
return (copied, node)
@@ -162,10 +162,10 @@ extension _HashNode {
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 = _HashNode<Key, Void>.build(
return unsafe read { l in
unsafe other.read { r in
guard unsafe l.collisionHash == r.collisionHash else {
let node = unsafe _HashNode<Key, Void>.build(
level: level,
child1: self.mapValuesToVoid(), l.collisionHash,
child2: other.mapValuesToVoid(), r.collisionHash)
@@ -173,11 +173,11 @@ extension _HashNode {
}
var copied = false
var node = self.mapValuesToVoid()
let litems = l.reverseItems
for rs: _HashSlot 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(
let litems = unsafe l.reverseItems
for rs: _HashSlot in stride(from: .zero, to: unsafe r.itemsEndSlot, by: 1) {
let p = unsafe r.itemPtr(at: rs)
if unsafe !litems.contains(where: { unsafe $0.key == p.pointee.key }) {
_ = unsafe node.ensureUniqueAndAppendCollision(
isUnique: copied, (p.pointee.key, ()))
copied = true
}
@@ -193,35 +193,35 @@ extension _HashNode {
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 rp = r.itemPtr(at: rslot)
return unsafe read { l in
unsafe other.read { r in
let bucket = unsafe l.collisionHash[level]
if unsafe r.itemMap.contains(bucket) {
let rslot = unsafe r.itemMap.slot(of: bucket)
let rp = unsafe r.itemPtr(at: rslot)
if
r.hasSingletonItem
&& l.reverseItems.contains(where: { $0.key == rp.pointee.key })
unsafe r.hasSingletonItem
&& l.reverseItems.contains(where: { unsafe $0.key == rp.pointee.key })
{
return (false, self.mapValuesToVoid())
}
let node = other.mapValuesToVoid().copyNodeAndPushItemIntoNewChild(
let node = unsafe other.mapValuesToVoid().copyNodeAndPushItemIntoNewChild(
level: level, self.mapValuesToVoid(), at: bucket, itemSlot: rslot)
return (true, node)
}
if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let res = self._union(level.descend(), r[child: rslot])
if unsafe r.childMap.contains(bucket) {
let rslot = unsafe r.childMap.slot(of: bucket)
let res = unsafe self._union(level.descend(), r[child: rslot])
var node = other.mapValuesToVoid(copy: true)
let delta = node.replaceChild(at: bucket, rslot, with: res.node)
let delta = unsafe node.replaceChild(at: bucket, rslot, with: res.node)
assert(delta >= 0)
return (true, node)
}
var node = other.mapValuesToVoid(
copy: true, extraBytes: _HashNode<Key, Void>.spaceForNewChild)
node.insertChild(self.mapValuesToVoid(), bucket)
unsafe node.insertChild(self.mapValuesToVoid(), bucket)
return (true, node)
}
}
@@ -229,29 +229,29 @@ extension _HashNode {
assert(rc)
// `other` is a collision node on a compressed path.
return read { l -> (copied: Bool, node: _HashNode<Key, Void>) in
other.read { r -> (copied: Bool, node: _HashNode<Key, Void>) in
let bucket = r.collisionHash[level]
if l.itemMap.contains(bucket) {
let lslot = l.itemMap.slot(of: bucket)
assert(!l.hasSingletonItem) // Handled up front above
let node = self.mapValuesToVoid().copyNodeAndPushItemIntoNewChild(
return unsafe read { l -> (copied: Bool, node: _HashNode<Key, Void>) in
unsafe other.read { r -> (copied: Bool, node: _HashNode<Key, Void>) in
let bucket = unsafe r.collisionHash[level]
if unsafe l.itemMap.contains(bucket) {
let lslot = unsafe l.itemMap.slot(of: bucket)
assert(unsafe !l.hasSingletonItem) // Handled up front above
let node = unsafe self.mapValuesToVoid().copyNodeAndPushItemIntoNewChild(
level: level, other.mapValuesToVoid(), at: bucket, itemSlot: lslot)
return (true, node)
}
if l.childMap.contains(bucket) {
let lslot = l.childMap.slot(of: bucket)
let child = l[child: lslot]._union(level.descend(), other)
if unsafe l.childMap.contains(bucket) {
let lslot = unsafe l.childMap.slot(of: bucket)
let child = unsafe l[child: lslot]._union(level.descend(), other)
guard child.copied else { return (false, self.mapValuesToVoid()) }
var node = self.mapValuesToVoid(copy: true)
let delta = node.replaceChild(at: bucket, lslot, with: child.node)
let delta = unsafe 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.mapValuesToVoid(
copy: true, extraBytes: _HashNode.spaceForNewChild)
node.insertChild(other.mapValuesToVoid(), bucket)
unsafe node.insertChild(other.mapValuesToVoid(), bucket)
return (true, node)
}
}
@@ -22,7 +22,7 @@ extension _HashNode {
_ item: Element,
_ hash: _Hash
) -> (inserted: Bool, leaf: _UnmanagedHashNode, slot: _HashSlot) {
insert(level, item.key, hash) { $0.initialize(to: item) }
unsafe insert(level, item.key, hash) { unsafe $0.initialize(to: item) }
}
@inlinable
@@ -35,43 +35,43 @@ extension _HashNode {
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 = unsafe self.inserting(level, key, hash, inserter)
self = unsafe r.node
return unsafe (r.inserted, r.leaf, r.slot)
}
let r = findForInsertion(level, key, hash)
switch r {
case .found(_, let slot):
return (false, unmanaged, slot)
return (false, unsafe unmanaged, slot)
case .insert(let bucket, let slot):
ensureUniqueAndInsertItem(
unsafe ensureUniqueAndInsertItem(
isUnique: true, at: bucket, itemSlot: slot, inserter)
return (true, unmanaged, slot)
return (true, unsafe unmanaged, slot)
case .appendCollision:
let slot = ensureUniqueAndAppendCollision(isUnique: true, inserter)
return (true, unmanaged, slot)
let slot = unsafe ensureUniqueAndAppendCollision(isUnique: true, inserter)
return (true, unsafe unmanaged, slot)
case .spawnChild(let bucket, let slot):
let r = ensureUniqueAndSpawnChild(
let r = unsafe ensureUniqueAndSpawnChild(
isUnique: true,
level: level,
replacing: bucket,
itemSlot: slot,
newHash: hash,
inserter)
return (true, r.leaf, r.slot)
return unsafe (true, r.leaf, r.slot)
case .expansion:
let r = _HashNode.build(
let r = unsafe _HashNode.build(
level: level,
item1: inserter, hash,
child2: self, self.collisionHash)
self = r.top
return (true, r.leaf, r.slot1)
self = unsafe r.top
return unsafe (true, r.leaf, r.slot1)
case .descend(_, let slot):
let r = update {
$0[child: slot].insert(level.descend(), key, hash, inserter)
let r = unsafe update {
unsafe $0[child: slot].insert(level.descend(), key, hash, inserter)
}
if r.inserted { count &+= 1 }
return r
if unsafe r.inserted { count &+= 1 }
return unsafe r
}
}
@@ -83,7 +83,7 @@ extension _HashNode {
) -> (
inserted: Bool, node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot
) {
inserting(level, item.key, hash, { $0.initialize(to: item) })
unsafe inserting(level, item.key, hash, { unsafe $0.initialize(to: item) })
}
@inlinable
@@ -99,40 +99,40 @@ extension _HashNode {
let r = findForInsertion(level, key, hash)
switch r {
case .found(_, let slot):
return (false, self, unmanaged, slot)
return unsafe (false, self, unmanaged, slot)
case .insert(let bucket, let slot):
let node = copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter)
return (true, node, node.unmanaged, slot)
let node = unsafe copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter)
return unsafe (true, node, node.unmanaged, slot)
case .appendCollision:
let r = copyNodeAndAppendCollision(inserter)
return (true, r.node, r.node.unmanaged, r.slot)
let r = unsafe copyNodeAndAppendCollision(inserter)
return unsafe (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(
let existingHash = unsafe read { unsafe _Hash($0[item: slot].key) }
let r = unsafe copyNodeAndSpawnChild(
level: level,
replacing: bucket,
itemSlot: slot,
existingHash: existingHash,
newHash: hash,
inserter)
return (true, r.node, r.leaf, r.slot)
return unsafe (true, r.node, r.leaf, r.slot)
case .expansion:
let r = _HashNode.build(
let r = unsafe _HashNode.build(
level: level,
item1: inserter, hash,
child2: self, self.collisionHash)
return (true, r.top, r.leaf, r.slot1)
return unsafe (true, r.top, r.leaf, r.slot1)
case .descend(_, let slot):
let r = read {
$0[child: slot].inserting(level.descend(), key, hash, inserter)
let r = unsafe read {
unsafe $0[child: slot].inserting(level.descend(), key, hash, inserter)
}
guard r.inserted else {
return (false, self, r.leaf, r.slot)
guard unsafe r.inserted else {
return unsafe (false, self, r.leaf, r.slot)
}
var copy = self.copy()
copy.update { $0[child: slot] = r.node }
unsafe copy.update { unsafe $0[child: slot] = r.node }
copy.count &+= 1
return (true, copy, r.leaf, r.slot)
return unsafe (true, copy, r.leaf, r.slot)
}
}
@@ -149,38 +149,38 @@ extension _HashNode {
switch r {
case .found(_, let slot):
ensureUnique(isUnique: isUnique)
return (false, unmanaged, slot)
return unsafe (false, unmanaged, slot)
case .insert(let bucket, let slot):
ensureUniqueAndInsertItem(
unsafe ensureUniqueAndInsertItem(
isUnique: isUnique, at: bucket, itemSlot: slot, inserter)
return (true, unmanaged, slot)
return unsafe (true, unmanaged, slot)
case .appendCollision:
let slot = ensureUniqueAndAppendCollision(isUnique: isUnique, inserter)
return (true, unmanaged, slot)
let slot = unsafe ensureUniqueAndAppendCollision(isUnique: isUnique, inserter)
return unsafe (true, unmanaged, slot)
case .spawnChild(let bucket, let slot):
let r = ensureUniqueAndSpawnChild(
let r = unsafe ensureUniqueAndSpawnChild(
isUnique: isUnique,
level: level,
replacing: bucket,
itemSlot: slot,
newHash: hash,
inserter)
return (true, r.leaf, r.slot)
return unsafe (true, r.leaf, r.slot)
case .expansion:
let r = _HashNode.build(
let r = unsafe _HashNode.build(
level: level,
item1: inserter, hash,
child2: self, self.collisionHash)
self = r.top
return (true, r.leaf, r.slot1)
self = unsafe r.top
return unsafe (true, r.leaf, r.slot1)
case .descend(_, let slot):
ensureUnique(isUnique: isUnique)
let r = update {
$0[child: slot].updateValue(
let r = unsafe update {
unsafe $0[child: slot].updateValue(
level.descend(), forKey: key, hash, inserter)
}
if r.inserted { count &+= 1 }
return r
if unsafe r.inserted { count &+= 1 }
return unsafe r
}
}
}
@@ -192,13 +192,13 @@ extension _HashNode {
_ item: Element,
at bucket: _Bucket
) {
let slot = self.read { $0.itemMap.slot(of: bucket) }
ensureUniqueAndInsertItem(
let slot = unsafe self.read { unsafe $0.itemMap.slot(of: bucket) }
unsafe ensureUniqueAndInsertItem(
isUnique: isUnique,
at: bucket,
itemSlot: slot
) {
$0.initialize(to: item)
unsafe $0.initialize(to: item)
}
}
@@ -212,17 +212,17 @@ extension _HashNode {
assert(!isCollisionNode)
if !isUnique {
self = copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter)
self = unsafe copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter)
return
}
if !hasFreeSpace(Self.spaceForNewItem) {
resizeNodeAndInsertItem(at: bucket, itemSlot: slot, inserter)
unsafe resizeNodeAndInsertItem(at: bucket, itemSlot: slot, inserter)
return
}
// In-place insert.
update {
let p = $0._makeRoomForNewItem(at: slot, bucket)
inserter(p)
unsafe update {
let p = unsafe $0._makeRoomForNewItem(at: slot, bucket)
unsafe inserter(p)
}
self.count &+= 1
}
@@ -235,25 +235,25 @@ extension _HashNode {
) -> _HashNode {
assert(!isCollisionNode)
let c = self.count
return read { src in
assert(!src.itemMap.contains(bucket))
assert(!src.childMap.contains(bucket))
return Self.allocate(
return unsafe read { src in
assert(unsafe !src.itemMap.contains(bucket))
assert(unsafe !src.childMap.contains(bucket))
return unsafe Self.allocate(
itemMap: src.itemMap.inserting(bucket),
childMap: src.childMap,
count: c &+ 1
) { dstChildren, dstItems in
dstChildren.initializeAll(fromContentsOf: src.children)
unsafe dstChildren.initializeAll(fromContentsOf: src.children)
let srcItems = src.reverseItems
let srcItems = unsafe src.reverseItems
assert(dstItems.count == srcItems.count + 1)
dstItems.suffix(slot.value)
unsafe dstItems.suffix(slot.value)
.initializeAll(fromContentsOf: srcItems.suffix(slot.value))
let rest = srcItems.count &- slot.value
dstItems.prefix(rest)
unsafe dstItems.prefix(rest)
.initializeAll(fromContentsOf: srcItems.prefix(rest))
inserter(dstItems.baseAddress! + rest)
unsafe inserter(dstItems.baseAddress! + rest)
}.node
}
}
@@ -266,27 +266,27 @@ extension _HashNode {
) {
assert(!isCollisionNode)
let c = self.count
self = update { src in
assert(!src.itemMap.contains(bucket))
assert(!src.childMap.contains(bucket))
return Self.allocate(
self = unsafe update { src in
assert(unsafe !src.itemMap.contains(bucket))
assert(unsafe !src.childMap.contains(bucket))
return unsafe Self.allocate(
itemMap: src.itemMap.inserting(bucket),
childMap: src.childMap,
count: c &+ 1
) { dstChildren, dstItems in
dstChildren.moveInitializeAll(fromContentsOf: src.children)
unsafe dstChildren.moveInitializeAll(fromContentsOf: src.children)
let srcItems = src.reverseItems
let srcItems = unsafe src.reverseItems
assert(dstItems.count == srcItems.count + 1)
dstItems.suffix(slot.value)
unsafe dstItems.suffix(slot.value)
.moveInitializeAll(fromContentsOf: srcItems.suffix(slot.value))
let rest = srcItems.count &- slot.value
dstItems.prefix(rest)
unsafe dstItems.prefix(rest)
.moveInitializeAll(fromContentsOf: srcItems.prefix(rest))
inserter(dstItems.baseAddress! + rest)
unsafe inserter(dstItems.baseAddress! + rest)
src.clear()
unsafe src.clear()
}.node
}
}
@@ -294,71 +294,75 @@ extension _HashNode {
extension _HashNode {
@inlinable
@unsafe
internal mutating func ensureUniqueAndAppendCollision(
isUnique: Bool,
_ item: Element
) -> _HashSlot {
ensureUniqueAndAppendCollision(isUnique: isUnique) {
$0.initialize(to: item)
unsafe ensureUniqueAndAppendCollision(isUnique: isUnique) {
unsafe $0.initialize(to: item)
}
}
@inlinable
@unsafe
internal mutating func ensureUniqueAndAppendCollision(
isUnique: Bool,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> _HashSlot {
assert(isCollisionNode)
if !isUnique {
let r = copyNodeAndAppendCollision(inserter)
let r = unsafe copyNodeAndAppendCollision(inserter)
self = r.node
return r.slot
}
if !hasFreeSpace(Self.spaceForNewItem) {
return resizeNodeAndAppendCollision(inserter)
return unsafe resizeNodeAndAppendCollision(inserter)
}
// In-place insert.
update {
let p = $0._makeRoomForNewItem(at: $0.itemsEndSlot, .invalid)
inserter(p)
unsafe update {
let p = unsafe $0._makeRoomForNewItem(at: $0.itemsEndSlot, .invalid)
unsafe inserter(p)
}
self.count &+= 1
return _HashSlot(self.count &- 1)
}
@inlinable @inline(never)
@unsafe
internal func copyNodeAndAppendCollision(
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (node: _HashNode, slot: _HashSlot) {
assert(isCollisionNode)
assert(self.count == read { $0.collisionCount })
assert(unsafe self.count == read { unsafe $0.collisionCount })
let c = self.count
let node = read { src in
Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in
let srcItems = src.reverseItems
let node = unsafe read { src in
unsafe Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in
let srcItems = unsafe src.reverseItems
assert(dstItems.count == srcItems.count + 1)
dstItems.dropFirst().initializeAll(fromContentsOf: srcItems)
inserter(dstItems.baseAddress!)
unsafe dstItems.dropFirst().initializeAll(fromContentsOf: srcItems)
unsafe inserter(dstItems.baseAddress!)
}.node
}
return (node, _HashSlot(c))
}
@inlinable @inline(never)
@unsafe
internal mutating func resizeNodeAndAppendCollision(
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> _HashSlot {
assert(isCollisionNode)
assert(self.count == read { $0.collisionCount })
assert(unsafe self.count == read { unsafe $0.collisionCount })
let c = self.count
self = update { src in
Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in
let srcItems = src.reverseItems
self = unsafe update { src in
unsafe Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in
let srcItems = unsafe src.reverseItems
assert(dstItems.count == srcItems.count + 1)
dstItems.dropFirst().moveInitializeAll(fromContentsOf: srcItems)
inserter(dstItems.baseAddress!)
unsafe dstItems.dropFirst().moveInitializeAll(fromContentsOf: srcItems)
unsafe inserter(dstItems.baseAddress!)
src.clear()
unsafe src.clear()
}.node
}
return _HashSlot(c)
@@ -367,6 +371,7 @@ extension _HashNode {
extension _HashNode {
@inlinable
@unsafe
internal func _copyNodeAndReplaceItemWithNewChild(
level: _HashLevel,
_ newChild: __owned _HashNode,
@@ -374,40 +379,40 @@ extension _HashNode {
itemSlot: _HashSlot
) -> _HashNode {
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)
return unsafe read { src in
assert(unsafe !src.isCollisionNode)
assert(unsafe src.itemMap.contains(bucket))
assert(unsafe !src.childMap.contains(bucket))
assert(unsafe src.itemMap.slot(of: bucket) == itemSlot)
if src.hasSingletonItem && newChild.isCollisionNode {
if unsafe src.hasSingletonItem && newChild.isCollisionNode {
// Compression
return newChild
}
let childSlot = src.childMap.slot(of: bucket)
return Self.allocate(
let childSlot = unsafe src.childMap.slot(of: bucket)
return unsafe 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
let srcChildren = unsafe src.children
let srcItems = unsafe src.reverseItems
// Initialize children.
dstChildren.prefix(childSlot.value)
unsafe dstChildren.prefix(childSlot.value)
.initializeAll(fromContentsOf: srcChildren.prefix(childSlot.value))
let rest = srcChildren.count &- childSlot.value
dstChildren.suffix(rest)
unsafe dstChildren.suffix(rest)
.initializeAll(fromContentsOf: srcChildren.suffix(rest))
dstChildren.initializeElement(at: childSlot.value, to: newChild)
unsafe dstChildren.initializeElement(at: childSlot.value, to: newChild)
// Initialize items.
dstItems.suffix(itemSlot.value)
unsafe dstItems.suffix(itemSlot.value)
.initializeAll(fromContentsOf: srcItems.suffix(itemSlot.value))
let rest2 = dstItems.count &- itemSlot.value
dstItems.prefix(rest2)
unsafe dstItems.prefix(rest2)
.initializeAll(fromContentsOf: srcItems.prefix(rest2))
}.node
}
@@ -416,6 +421,7 @@ extension _HashNode {
/// The item at `itemSlot` must have already been deinitialized by the time
/// this function is called.
@inlinable
@unsafe
internal mutating func _resizeNodeAndReplaceItemWithNewChild(
level: _HashLevel,
_ newChild: __owned _HashNode,
@@ -423,38 +429,38 @@ extension _HashNode {
itemSlot: _HashSlot
) {
let c = self.count
let node: _HashNode = update { src in
assert(!src.isCollisionNode)
assert(src.itemMap.contains(bucket))
assert(!src.childMap.contains(bucket))
assert(src.itemMap.slot(of: bucket) == itemSlot)
let node: _HashNode = unsafe update { src in
assert(unsafe !src.isCollisionNode)
assert(unsafe src.itemMap.contains(bucket))
assert(unsafe !src.childMap.contains(bucket))
assert(unsafe src.itemMap.slot(of: bucket) == itemSlot)
let childSlot = src.childMap.slot(of: bucket)
return Self.allocate(
let childSlot = unsafe src.childMap.slot(of: bucket)
return unsafe 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
let srcChildren = unsafe src.children
let srcItems = unsafe src.reverseItems
// Initialize children.
dstChildren.prefix(childSlot.value)
unsafe dstChildren.prefix(childSlot.value)
.moveInitializeAll(fromContentsOf: srcChildren.prefix(childSlot.value))
let rest = srcChildren.count &- childSlot.value
dstChildren.suffix(rest)
unsafe dstChildren.suffix(rest)
.moveInitializeAll(fromContentsOf: srcChildren.suffix(rest))
dstChildren.initializeElement(at: childSlot.value, to: newChild)
unsafe dstChildren.initializeElement(at: childSlot.value, to: newChild)
// Initialize items.
dstItems.suffix(itemSlot.value)
unsafe dstItems.suffix(itemSlot.value)
.moveInitializeAll(fromContentsOf: srcItems.suffix(itemSlot.value))
let rest2 = dstItems.count &- itemSlot.value
dstItems.prefix(rest2)
unsafe dstItems.prefix(rest2)
.moveInitializeAll(fromContentsOf: srcItems.prefix(rest2))
src.clear()
unsafe src.clear()
}.node
}
self = node
@@ -463,6 +469,7 @@ extension _HashNode {
extension _HashNode {
@inlinable @inline(never)
@unsafe
internal func copyNodeAndPushItemIntoNewChild(
level: _HashLevel,
_ newChild: __owned _HashNode,
@@ -470,10 +477,10 @@ extension _HashNode {
itemSlot: _HashSlot
) -> _HashNode {
assert(!isCollisionNode)
let item = read { $0[item: itemSlot] }
let item = unsafe read { unsafe $0[item: itemSlot] }
let hash = _Hash(item.key)
let r = newChild.inserting(level.descend(), item, hash)
return _copyNodeAndReplaceItemWithNewChild(
let r = unsafe newChild.inserting(level.descend(), item, hash)
return unsafe _copyNodeAndReplaceItemWithNewChild(
level: level,
r.node,
at: bucket,
@@ -483,6 +490,7 @@ extension _HashNode {
extension _HashNode {
@inlinable
@unsafe
internal mutating func ensureUniqueAndSpawnChild(
isUnique: Bool,
level: _HashLevel,
@@ -491,27 +499,27 @@ extension _HashNode {
newHash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) {
let existingHash = read { _Hash($0[item: itemSlot].key) }
let existingHash = unsafe read { unsafe _Hash($0[item: itemSlot].key) }
assert(existingHash.isEqual(to: newHash, upTo: level))
if newHash == existingHash, hasSingletonItem {
// Convert current node to a collision node.
self = _HashNode._collisionNode(newHash, read { $0[item: .zero] }, inserter)
return (unmanaged, _HashSlot(1))
self = unsafe _HashNode._collisionNode(newHash, read { unsafe $0[item: .zero] }, inserter)
return unsafe (unmanaged, _HashSlot(1))
}
if !isUnique {
let r = copyNodeAndSpawnChild(
let r = unsafe copyNodeAndSpawnChild(
level: level,
replacing: bucket,
itemSlot: itemSlot,
existingHash: existingHash,
newHash: newHash,
inserter)
self = r.node
return (r.leaf, r.slot)
self = unsafe r.node
return unsafe (r.leaf, r.slot)
}
if !hasFreeSpace(Self.spaceForSpawningChild) {
return resizeNodeAndSpawnChild(
return unsafe resizeNodeAndSpawnChild(
level: level,
replacing: bucket,
itemSlot: itemSlot,
@@ -520,16 +528,17 @@ extension _HashNode {
inserter)
}
let existing = removeItem(at: bucket, itemSlot)
let r = _HashNode.build(
let existing = unsafe removeItem(at: bucket, itemSlot)
let r = unsafe _HashNode.build(
level: level.descend(),
item1: existing, existingHash,
item2: inserter, newHash)
insertChild(r.top, bucket)
return (r.leaf, r.slot2)
unsafe insertChild(r.top, bucket)
return unsafe (r.leaf, r.slot2)
}
@inlinable @inline(never)
@unsafe
internal func copyNodeAndSpawnChild(
level: _HashLevel,
replacing bucket: _Bucket,
@@ -538,22 +547,23 @@ extension _HashNode {
newHash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot) {
let r = read {
_HashNode.build(
let r = unsafe read {
unsafe _HashNode.build(
level: level.descend(),
item1: $0[item: itemSlot], existingHash,
item2: inserter, newHash)
}
let node = _copyNodeAndReplaceItemWithNewChild(
let node = unsafe _copyNodeAndReplaceItemWithNewChild(
level: level,
r.top,
at: bucket,
itemSlot: itemSlot)
node._invariantCheck()
return (node, r.leaf, r.slot2)
return unsafe (node, r.leaf, r.slot2)
}
@inlinable @inline(never)
@unsafe
internal mutating func resizeNodeAndSpawnChild(
level: _HashLevel,
replacing bucket: _Bucket,
@@ -562,19 +572,19 @@ extension _HashNode {
newHash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) {
let r = update {
_HashNode.build(
let r = unsafe update {
unsafe _HashNode.build(
level: level.descend(),
item1: $0.itemPtr(at: itemSlot).move(), existingHash,
item2: inserter, newHash)
}
_resizeNodeAndReplaceItemWithNewChild(
unsafe _resizeNodeAndReplaceItemWithNewChild(
level: level,
r.top,
at: bucket,
itemSlot: itemSlot)
_invariantCheck()
return (r.leaf, r.slot2)
return unsafe (r.leaf, r.slot2)
}
}
@@ -19,9 +19,9 @@ extension _HashNode {
level: _HashLevel, at path: _UnsafePath
) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) {
ensureUnique(isUnique: isUnique())
guard level < path.level else { return (unmanaged, path.currentItemSlot) }
return update {
$0[child: path.childSlot(at: level)]
guard level < path.level else { return unsafe (unmanaged, path.currentItemSlot) }
return unsafe update {
unsafe $0[child: path.childSlot(at: level)]
.ensureUnique(level: level.descend(), at: path)
}
}
@@ -30,20 +30,25 @@ extension _HashNode {
extension _HashNode {
@usableFromInline
@frozen
@unsafe
internal struct ValueUpdateState {
@usableFromInline
@safe
internal var key: Key
@usableFromInline
@safe
internal var value: Value?
@usableFromInline
@safe
internal let hash: _Hash
@usableFromInline
internal var path: _UnsafePath
@usableFromInline
@safe
internal var found: Bool
@inlinable
@@ -55,22 +60,24 @@ extension _HashNode {
self.key = key
self.value = nil
self.hash = hash
self.path = path
unsafe self.path = path
self.found = false
}
}
@inlinable
@unsafe
internal mutating func prepareValueUpdate(
_ key: Key,
_ hash: _Hash
) -> ValueUpdateState {
var state = ValueUpdateState(key, hash, _UnsafePath(root: raw))
_prepareValueUpdate(&state)
return state
var state = unsafe ValueUpdateState(key, hash, _UnsafePath(root: raw))
unsafe _prepareValueUpdate(&state)
return unsafe state
}
@inlinable
@unsafe
internal mutating func _prepareValueUpdate(
_ state: inout ValueUpdateState
) {
@@ -81,59 +88,60 @@ extension _HashNode {
// If the key already exists, we ensure uniqueness for its node and extract
// its item but otherwise leave the tree as it was.
let isUnique = self.isUnique()
let r = findForInsertion(state.path.level, state.key, state.hash)
let r = unsafe findForInsertion(state.path.level, state.key, state.hash)
switch r {
case .found(_, let slot):
ensureUnique(isUnique: isUnique)
state.path.node = unmanaged
state.path.selectItem(at: slot)
unsafe state.path.node = unmanaged
unsafe state.path.selectItem(at: slot)
state.found = true
(state.key, state.value) = update { $0.itemPtr(at: slot).move() }
(state.key, state.value) = unsafe update { unsafe $0.itemPtr(at: slot).move() }
case .insert(_, let slot):
state.path.selectItem(at: slot)
unsafe state.path.selectItem(at: slot)
case .appendCollision:
state.path.selectItem(at: _HashSlot(self.count))
unsafe state.path.selectItem(at: _HashSlot(self.count))
case .spawnChild(_, let slot):
state.path.selectItem(at: slot)
unsafe state.path.selectItem(at: slot)
case .expansion:
state.path.selectEnd()
unsafe state.path.selectEnd()
case .descend(_, let slot):
ensureUnique(isUnique: isUnique)
update {
let p = $0.childPtr(at: slot)
state.path.descendToChild(p.pointee.unmanaged, at: slot)
p.pointee._prepareValueUpdate(&state)
unsafe update {
let p = unsafe $0.childPtr(at: slot)
unsafe state.path.descendToChild(p.pointee.unmanaged, at: slot)
unsafe p.pointee._prepareValueUpdate(&state)
}
}
}
@inlinable
@unsafe
internal mutating func finalizeValueUpdate(
_ state: __owned ValueUpdateState
) {
switch (state.found, state.value != nil) {
case (true, true):
// Fast path: updating an existing value.
UnsafeHandle.update(state.path.node) {
$0.itemPtr(at: state.path.currentItemSlot)
unsafe UnsafeHandle.update(state.path.node) {
unsafe $0.itemPtr(at: state.path.currentItemSlot)
.initialize(to: (state.key, state.value.unsafelyUnwrapped))
}
case (true, false):
// Removal
let remainder = _finalizeRemoval(.top, state.hash, at: state.path)
let remainder = unsafe _finalizeRemoval(.top, state.hash, at: state.path)
assert(remainder == nil)
case (false, true):
// Insertion
let r = updateValue(.top, forKey: state.key, state.hash) {
$0.initialize(to: (state.key, state.value.unsafelyUnwrapped))
let r = unsafe updateValue(.top, forKey: state.key, state.hash) {
unsafe $0.initialize(to: (state.key, state.value.unsafelyUnwrapped))
}
assert(r.inserted)
assert(unsafe r.inserted)
case (false, false):
// Noop
break
@@ -141,20 +149,21 @@ extension _HashNode {
}
@inlinable
@unsafe
internal mutating func _finalizeRemoval(
_ level: _HashLevel, _ hash: _Hash, at path: _UnsafePath
) -> Element? {
assert(isUnique())
if level == path.level {
return _removeItemFromUniqueLeafNode(
return unsafe _removeItemFromUniqueLeafNode(
level, at: hash[level], path.currentItemSlot, by: { _ in }
).remainder
}
let slot = path.childSlot(at: level)
let remainder = update {
$0[child: slot]._finalizeRemoval(level.descend(), hash, at: path)
let slot = unsafe path.childSlot(at: level)
let remainder = unsafe update {
unsafe $0[child: slot]._finalizeRemoval(level.descend(), hash, at: path)
}
return _fixupUniqueAncestorAfterItemRemoval(
return unsafe _fixupUniqueAncestorAfterItemRemoval(
level, at: { _ in hash[level] }, slot, remainder: remainder)
}
}
@@ -162,17 +171,21 @@ extension _HashNode {
extension _HashNode {
@usableFromInline
@frozen
@unsafe
internal struct DefaultedValueUpdateState {
@usableFromInline
@safe
internal var item: Element
@usableFromInline
internal var node: _UnmanagedHashNode
@usableFromInline
@safe
internal var slot: _HashSlot
@usableFromInline
@safe
internal var inserted: Bool
@inlinable
@@ -183,7 +196,7 @@ extension _HashNode {
inserted: Bool
) {
self.item = item
self.node = node
unsafe self.node = node
self.slot = slot
self.inserted = inserted
}
@@ -201,51 +214,51 @@ extension _HashNode {
switch r {
case .found(_, let slot):
ensureUnique(isUnique: isUnique)
return DefaultedValueUpdateState(
update { $0.itemPtr(at: slot).move() },
return unsafe DefaultedValueUpdateState(
update { unsafe $0.itemPtr(at: slot).move() },
in: unmanaged,
at: slot,
inserted: false)
case .insert(let bucket, let slot):
ensureUniqueAndInsertItem(
unsafe ensureUniqueAndInsertItem(
isUnique: isUnique, at: bucket, itemSlot: slot
) { _ in }
return DefaultedValueUpdateState(
return unsafe DefaultedValueUpdateState(
(key, defaultValue()),
in: unmanaged,
at: slot,
inserted: true)
case .appendCollision:
let slot = ensureUniqueAndAppendCollision(isUnique: isUnique) { _ in }
return DefaultedValueUpdateState(
let slot = unsafe ensureUniqueAndAppendCollision(isUnique: isUnique) { _ in }
return unsafe DefaultedValueUpdateState(
(key, defaultValue()),
in: unmanaged,
at: slot,
inserted: true)
case .spawnChild(let bucket, let slot):
let r = ensureUniqueAndSpawnChild(
let r = unsafe ensureUniqueAndSpawnChild(
isUnique: isUnique,
level: level,
replacing: bucket,
itemSlot: slot,
newHash: hash) { _ in }
return DefaultedValueUpdateState(
return unsafe DefaultedValueUpdateState(
(key, defaultValue()),
in: r.leaf,
at: r.slot,
inserted: true)
case .expansion:
let r = _HashNode.build(
let r = unsafe _HashNode.build(
level: level,
item1: { _ in }, hash,
child2: self, self.collisionHash
)
self = r.top
return DefaultedValueUpdateState(
self = unsafe r.top
return unsafe DefaultedValueUpdateState(
(key, defaultValue()),
in: r.leaf,
at: r.slot1,
@@ -253,12 +266,12 @@ extension _HashNode {
case .descend(_, let slot):
ensureUnique(isUnique: isUnique)
let res = update {
$0[child: slot].prepareDefaultedValueUpdate(
let res = unsafe update {
unsafe $0[child: slot].prepareDefaultedValueUpdate(
level.descend(), key, defaultValue, hash)
}
if res.inserted { count &+= 1 }
return res
return unsafe res
}
}
@@ -266,8 +279,8 @@ extension _HashNode {
internal mutating func finalizeDefaultedValueUpdate(
_ state: __owned DefaultedValueUpdateState
) {
UnsafeHandle.update(state.node) {
$0.itemPtr(at: state.slot).initialize(to: state.item)
unsafe UnsafeHandle.update(state.node) {
unsafe $0.itemPtr(at: state.slot).initialize(to: state.item)
}
}
}
@@ -20,26 +20,27 @@ extension _HashNode {
/// It is up to the caller to detect this situation & correct it when needed,
/// by inlining the remaining item into the parent node.
@inlinable
@unsafe
internal mutating func remove(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (removed: Element, remainder: Element?)? {
guard self.isUnique() else {
guard let r = removing(level, key, hash) else { return nil }
let remainder = self.applyReplacement(level, r.replacement)
guard let r = unsafe removing(level, key, hash) else { return nil }
let remainder = unsafe self.applyReplacement(level, r.replacement)
return (r.removed, remainder)
}
guard let r = find(level, key, hash) else { return nil }
let bucket = hash[level]
guard r.descend else {
let r = _removeItemFromUniqueLeafNode(level, at: bucket, r.slot) {
$0.move()
let r = unsafe _removeItemFromUniqueLeafNode(level, at: bucket, r.slot) {
unsafe $0.move()
}
return (r.result, r.remainder)
}
let r2 = update { $0[child: r.slot].remove(level.descend(), key, hash) }
let r2 = unsafe update { unsafe $0[child: r.slot].remove(level.descend(), key, hash) }
guard let r2 = r2 else { return nil }
let remainder = _fixupUniqueAncestorAfterItemRemoval(
let remainder = unsafe _fixupUniqueAncestorAfterItemRemoval(
level,
at: { _ in hash[level] },
r.slot,
@@ -50,17 +51,18 @@ extension _HashNode {
extension _HashNode {
@inlinable
@unsafe
internal func removing(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (removed: Element, replacement: Builder)? {
guard let r = find(level, key, hash) else { return nil }
let bucket = hash[level]
guard r.descend else {
return _removingItemFromLeaf(level, at: bucket, r.slot)
return unsafe _removingItemFromLeaf(level, at: bucket, r.slot)
}
let r2 = read { $0[child: r.slot].removing(level.descend(), key, hash) }
let r2 = unsafe read { unsafe $0[child: r.slot].removing(level.descend(), key, hash) }
guard let r2 = r2 else { return nil }
let replacement = self.replacingChild(
let replacement = unsafe self.replacingChild(
level, at: bucket, r.slot, with: r2.replacement)
return (r2.removed, replacement)
}
@@ -68,54 +70,57 @@ extension _HashNode {
extension _HashNode {
@inlinable
@unsafe
internal mutating func remove(
_ level: _HashLevel, at path: _UnsafePath
) -> (removed: Element, remainder: Element?) {
defer { _invariantCheck() }
guard self.isUnique() else {
let r = removing(level, at: path)
let remainder = applyReplacement(level, r.replacement)
let r = unsafe removing(level, at: path)
let remainder = unsafe applyReplacement(level, r.replacement)
return (r.removed, remainder)
}
if level == path.level {
let slot = path.currentItemSlot
let bucket = read { $0.itemBucket(at: slot) }
let r = _removeItemFromUniqueLeafNode(
level, at: bucket, slot, by: { $0.move() })
let slot = unsafe path.currentItemSlot
let bucket = unsafe read { unsafe $0.itemBucket(at: slot) }
let r = unsafe _removeItemFromUniqueLeafNode(
level, at: bucket, slot, by: { unsafe $0.move() })
return (r.result, r.remainder)
}
let slot = path.childSlot(at: level)
let r = update { $0[child: slot].remove(level.descend(), at: path) }
let remainder = _fixupUniqueAncestorAfterItemRemoval(
let slot = unsafe path.childSlot(at: level)
let r = unsafe update { unsafe $0[child: slot].remove(level.descend(), at: path) }
let remainder = unsafe _fixupUniqueAncestorAfterItemRemoval(
level,
at: { $0.childMap.bucket(at: slot) },
at: { unsafe $0.childMap.bucket(at: slot) },
slot,
remainder: r.remainder)
return (r.removed, remainder)
}
@inlinable
@unsafe
internal func removing(
_ level: _HashLevel, at path: _UnsafePath
) -> (removed: Element, replacement: Builder) {
if level == path.level {
let slot = path.currentItemSlot
let bucket = read { $0.itemBucket(at: slot) }
return _removingItemFromLeaf(level, at: bucket, slot)
let slot = unsafe path.currentItemSlot
let bucket = unsafe read { unsafe $0.itemBucket(at: slot) }
return unsafe _removingItemFromLeaf(level, at: bucket, slot)
}
let slot = path.childSlot(at: level)
return read {
let bucket = $0.childMap.bucket(at: slot)
let r = $0[child: slot].removing(level.descend(), at: path)
let slot = unsafe path.childSlot(at: level)
return unsafe read {
let bucket = unsafe $0.childMap.bucket(at: slot)
let r = unsafe $0[child: slot].removing(level.descend(), at: path)
return (
r.removed,
self.replacingChild(level, at: bucket, slot, with: r.replacement))
unsafe self.replacingChild(level, at: bucket, slot, with: r.replacement))
}
}
}
extension _HashNode {
@inlinable
@unsafe
internal mutating func _removeItemFromUniqueLeafNode<R>(
_ level: _HashLevel,
at bucket: _Bucket,
@@ -123,7 +128,7 @@ extension _HashNode {
by remover: (UnsafeMutablePointer<Element>) -> R
) -> (result: R, remainder: Element?) {
assert(isUnique())
let result = removeItem(at: bucket, slot, by: remover)
let result = unsafe removeItem(at: bucket, slot, by: remover)
if isAtrophied {
self = removeSingletonChild()
}
@@ -134,64 +139,65 @@ extension _HashNode {
}
return (result, nil)
}
let item = removeSingletonItem()
let item = unsafe removeSingletonItem()
return (result, item)
}
return (result, nil)
}
@inlinable
@unsafe
internal func _removingItemFromLeaf(
_ level: _HashLevel, at bucket: _Bucket, _ slot: _HashSlot
) -> (removed: Element, replacement: Builder) {
read {
if $0.isCollisionNode {
assert(slot.value < $0.collisionCount )
unsafe read {
if unsafe $0.isCollisionNode {
assert(unsafe slot.value < $0.collisionCount )
if $0.collisionCount == 2 {
if unsafe $0.collisionCount == 2 {
// Node will evaporate
let remainder = _HashSlot(1 &- slot.value)
let bucket = $0.collisionHash[level]
let bucket = unsafe $0.collisionHash[level]
return (
removed: $0[item: slot],
replacement: .item(level, $0[item: remainder], at: bucket))
removed: unsafe $0[item: slot],
replacement: unsafe .item(level, $0[item: remainder], at: bucket))
}
var node = self.copy()
let old = node.removeItem(at: bucket, slot)
let old = unsafe node.removeItem(at: bucket, slot)
node._invariantCheck()
return (old, .collisionNode(level, node))
}
assert($0.itemMap.contains(bucket))
assert(slot == $0.itemMap.slot(of: bucket))
assert(unsafe $0.itemMap.contains(bucket))
assert(unsafe slot == $0.itemMap.slot(of: bucket))
let willAtrophy = (
!$0.isCollisionNode
unsafe !$0.isCollisionNode
&& $0.itemMap.hasExactlyOneMember
&& $0.childMap.hasExactlyOneMember
&& $0[child: .zero].isCollisionNode)
if willAtrophy {
// Compression
let child = $0[child: .zero]
let old = $0[item: .zero]
let child = unsafe $0[child: .zero]
let old = unsafe $0[item: .zero]
return (old, .collisionNode(level, child))
}
if $0.itemMap.count == 2 && $0.childMap.isEmpty {
if unsafe $0.itemMap.count == 2 && $0.childMap.isEmpty {
// Evaporating node
let remainder = _HashSlot(1 &- slot.value)
var map = $0.itemMap
var map = unsafe $0.itemMap
if remainder != .zero { _ = map.popFirst() }
let bucket = map.first!
return (
removed: $0[item: slot],
replacement: .item(level, $0[item: remainder], at: bucket))
removed: unsafe $0[item: slot],
replacement: unsafe .item(level, $0[item: remainder], at: bucket))
}
var node = self.copy()
let old = node.removeItem(at: bucket, slot)
let old = unsafe node.removeItem(at: bucket, slot)
node._invariantCheck()
return (old, .node(level, node))
}
@@ -200,31 +206,32 @@ extension _HashNode {
extension _HashNode {
@inlinable
@unsafe
internal func _removingChild(
_ level: _HashLevel, at bucket: _Bucket, _ slot: _HashSlot
) -> Builder {
read {
assert(!$0.isCollisionNode && $0.childMap.contains(bucket))
let willAtrophy = (
unsafe read {
assert(unsafe !$0.isCollisionNode && $0.childMap.contains(bucket))
let willAtrophy = unsafe (
$0.itemMap.isEmpty
&& $0.childCount == 2
&& $0[child: _HashSlot(1 &- slot.value)].isCollisionNode
)
if willAtrophy {
// Compression
let child = $0[child: _HashSlot(1 &- slot.value)]
let child = unsafe $0[child: _HashSlot(1 &- slot.value)]
return .collisionNode(level, child)
}
if $0.itemMap.hasExactlyOneMember && $0.childMap.hasExactlyOneMember {
return .item(level, $0[item: .zero], at: $0.itemMap.first!)
if unsafe $0.itemMap.hasExactlyOneMember && $0.childMap.hasExactlyOneMember {
return unsafe .item(level, $0[item: .zero], at: $0.itemMap.first!)
}
if $0.hasSingletonChild {
if unsafe $0.hasSingletonChild {
// Evaporate node
return .empty(level)
}
var node = self.copy()
_ = node.removeChild(at: bucket, slot)
_ = unsafe node.removeChild(at: bucket, slot)
node._invariantCheck()
return .node(level, node)
}
@@ -233,6 +240,7 @@ extension _HashNode {
extension _HashNode {
@inlinable
@unsafe
internal mutating func _fixupUniqueAncestorAfterItemRemoval(
_ level: _HashLevel,
at bucket: (UnsafeHandle) -> _Bucket,
@@ -248,12 +256,12 @@ extension _HashNode {
}
// Child to be inlined has already been cleared, so we need to adjust
// the count manually.
assert(read { $0[child: childSlot].count == 0 })
assert(unsafe read { unsafe $0[child: childSlot].count == 0 })
count &-= 1
let bucket = read { bucket($0) }
let bucket = unsafe read { unsafe bucket($0) }
ensureUnique(isUnique: true, withFreeSpace: Self.spaceForInlinedChild)
_ = self.removeChild(at: bucket, childSlot)
insertItem(remainder, at: bucket)
_ = unsafe self.removeChild(at: bucket, childSlot)
unsafe insertItem(remainder, at: bucket)
return nil
}
if isAtrophied {
@@ -268,10 +276,10 @@ extension _HashNode {
internal mutating func _convertToRegularNode() {
assert(isCollisionNode && hasSingletonItem)
assert(isUnique())
update {
$0.itemMap = _Bitmap($0.collisionHash[.top])
$0.childMap = .empty
$0.bytesFree &+= MemoryLayout<_Hash>.stride
unsafe update {
unsafe $0.itemMap = _Bitmap($0.collisionHash[.top])
unsafe $0.childMap = .empty
unsafe $0.bytesFree &+= MemoryLayout<_Hash>.stride
}
}
}
@@ -24,6 +24,7 @@ extension _HashNode {
/// they're called on a read-only view.
@usableFromInline
@frozen
@unsafe
internal struct UnsafeHandle {
@usableFromInline
internal typealias Element = (key: Key, value: Value)
@@ -36,6 +37,7 @@ extension _HashNode {
#if DEBUG
@usableFromInline
@safe
internal let _isMutable: Bool
#endif
@@ -45,8 +47,8 @@ extension _HashNode {
_ memory: UnsafeMutableRawPointer,
isMutable: Bool
) {
self._header = header
self._memory = memory
unsafe self._header = header
unsafe self._memory = memory
#if DEBUG
self._isMutable = isMutable
#endif
@@ -57,6 +59,7 @@ extension _HashNode {
extension _HashNode.UnsafeHandle {
@inlinable
@inline(__always)
@safe
func assertMutable() {
#if DEBUG
assert(_isMutable)
@@ -70,9 +73,9 @@ extension _HashNode.UnsafeHandle {
_ node: _UnmanagedHashNode,
_ body: (Self) throws -> R
) rethrows -> R {
try node.ref._withUnsafeGuaranteedRef { storage in
try storage.withUnsafeMutablePointers { header, elements in
try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: false))
unsafe try node.ref._withUnsafeGuaranteedRef { storage in
unsafe try storage.withUnsafeMutablePointers { header, elements in
unsafe try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: false))
}
}
}
@@ -82,8 +85,8 @@ extension _HashNode.UnsafeHandle {
_ storage: _RawHashStorage,
_ body: (Self) throws -> R
) rethrows -> R {
try storage.withUnsafeMutablePointers { header, elements in
try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: false))
unsafe try storage.withUnsafeMutablePointers { header, elements in
unsafe try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: false))
}
}
@@ -92,9 +95,9 @@ extension _HashNode.UnsafeHandle {
_ node: _UnmanagedHashNode,
_ body: (Self) throws -> R
) rethrows -> R {
try node.ref._withUnsafeGuaranteedRef { storage in
try storage.withUnsafeMutablePointers { header, elements in
try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: true))
unsafe try node.ref._withUnsafeGuaranteedRef { storage in
unsafe try storage.withUnsafeMutablePointers { header, elements in
unsafe try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: true))
}
}
}
@@ -104,8 +107,8 @@ extension _HashNode.UnsafeHandle {
_ storage: _RawHashStorage,
_ body: (Self) throws -> R
) rethrows -> R {
try storage.withUnsafeMutablePointers { header, elements in
try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: true))
unsafe try storage.withUnsafeMutablePointers { header, elements in
unsafe try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: true))
}
}
}
@@ -114,184 +117,188 @@ extension _HashNode.UnsafeHandle {
@inlinable @inline(__always)
internal var itemMap: _Bitmap {
get {
_header.pointee.itemMap
unsafe _header.pointee.itemMap
}
nonmutating set {
assertMutable()
_header.pointee.itemMap = newValue
unsafe _header.pointee.itemMap = newValue
}
}
@inlinable @inline(__always)
internal var childMap: _Bitmap {
get {
_header.pointee.childMap
unsafe _header.pointee.childMap
}
nonmutating set {
assertMutable()
_header.pointee.childMap = newValue
unsafe _header.pointee.childMap = newValue
}
}
@inlinable @inline(__always)
internal var byteCapacity: Int {
_header.pointee.byteCapacity
unsafe _header.pointee.byteCapacity
}
@inlinable @inline(__always)
internal var bytesFree: Int {
get { _header.pointee.bytesFree }
get {
unsafe _header.pointee.bytesFree
}
nonmutating set {
assertMutable()
_header.pointee.bytesFree = newValue
unsafe _header.pointee.bytesFree = newValue
}
}
@inlinable @inline(__always)
internal var isCollisionNode: Bool {
_header.pointee.isCollisionNode
unsafe _header.pointee.isCollisionNode
}
@inlinable @inline(__always)
internal var collisionCount: Int {
get { _header.pointee.collisionCount }
get {
unsafe _header.pointee.collisionCount
}
nonmutating set {
assertMutable()
_header.pointee.collisionCount = newValue
unsafe _header.pointee.collisionCount = newValue
}
}
@inlinable @inline(__always)
internal var collisionHash: _Hash {
get {
assert(isCollisionNode)
return _memory.load(as: _Hash.self)
assert(unsafe isCollisionNode)
return unsafe _memory.load(as: _Hash.self)
}
nonmutating set {
assertMutable()
assert(isCollisionNode)
_memory.storeBytes(of: newValue, as: _Hash.self)
assert(unsafe isCollisionNode)
unsafe _memory.storeBytes(of: newValue, as: _Hash.self)
}
}
@inlinable @inline(__always)
internal var _childrenStart: UnsafeMutablePointer<_HashNode> {
_memory.assumingMemoryBound(to: _HashNode.self)
unsafe _memory.assumingMemoryBound(to: _HashNode.self)
}
@inlinable @inline(__always)
internal var hasChildren: Bool {
_header.pointee.hasChildren
unsafe _header.pointee.hasChildren
}
@inlinable @inline(__always)
internal var childCount: Int {
_header.pointee.childCount
unsafe _header.pointee.childCount
}
@inlinable
internal func childBucket(at slot: _HashSlot) -> _Bucket {
guard !isCollisionNode else { return .invalid }
return childMap.bucket(at: slot)
guard unsafe !isCollisionNode else { return .invalid }
return unsafe childMap.bucket(at: slot)
}
@inlinable @inline(__always)
internal var childrenEndSlot: _HashSlot {
_header.pointee.childrenEndSlot
unsafe _header.pointee.childrenEndSlot
}
@inlinable
internal var children: UnsafeMutableBufferPointer<_HashNode> {
UnsafeMutableBufferPointer(start: _childrenStart, count: childCount)
unsafe UnsafeMutableBufferPointer(start: _childrenStart, count: childCount)
}
@inlinable
internal func childPtr(at slot: _HashSlot) -> UnsafeMutablePointer<_HashNode> {
assert(slot.value < childCount)
return _childrenStart + slot.value
assert(unsafe slot.value < childCount)
return unsafe _childrenStart + slot.value
}
@inlinable
internal subscript(child slot: _HashSlot) -> _HashNode {
unsafeAddress {
UnsafePointer(childPtr(at: slot))
unsafe UnsafePointer(childPtr(at: slot))
}
nonmutating unsafeMutableAddress {
assertMutable()
return childPtr(at: slot)
return unsafe childPtr(at: slot)
}
}
@inlinable
internal var _itemsEnd: UnsafeMutablePointer<Element> {
(_memory + _header.pointee.byteCapacity)
unsafe (_memory + _header.pointee.byteCapacity)
.assumingMemoryBound(to: Element.self)
}
@inlinable @inline(__always)
internal var hasItems: Bool {
_header.pointee.hasItems
unsafe _header.pointee.hasItems
}
@inlinable @inline(__always)
internal var itemCount: Int {
_header.pointee.itemCount
unsafe _header.pointee.itemCount
}
@inlinable
internal func itemBucket(at slot: _HashSlot) -> _Bucket {
guard !isCollisionNode else { return .invalid }
return itemMap.bucket(at: slot)
guard unsafe !isCollisionNode else { return .invalid }
return unsafe itemMap.bucket(at: slot)
}
@inlinable @inline(__always)
internal var itemsEndSlot: _HashSlot {
_header.pointee.itemsEndSlot
unsafe _header.pointee.itemsEndSlot
}
@inlinable
internal var reverseItems: UnsafeMutableBufferPointer<Element> {
let c = itemCount
return UnsafeMutableBufferPointer(start: _itemsEnd - c, count: c)
let c = unsafe itemCount
return unsafe UnsafeMutableBufferPointer(start: _itemsEnd - c, count: c)
}
@inlinable
internal func itemPtr(at slot: _HashSlot) -> UnsafeMutablePointer<Element> {
assert(slot.value <= itemCount)
return _itemsEnd.advanced(by: -1 &- slot.value)
assert(unsafe slot.value <= itemCount)
return unsafe _itemsEnd.advanced(by: -1 &- slot.value)
}
@inlinable
internal subscript(item slot: _HashSlot) -> Element {
unsafeAddress {
UnsafePointer(itemPtr(at: slot))
unsafe UnsafePointer(itemPtr(at: slot))
}
nonmutating unsafeMutableAddress {
assertMutable()
return itemPtr(at: slot)
return unsafe itemPtr(at: slot)
}
}
@inlinable
internal func clear() {
assertMutable()
_header.pointee.clear()
unsafe _header.pointee.clear()
}
}
extension _HashNode.UnsafeHandle {
@inlinable
internal var hasSingletonItem: Bool {
_header.pointee.hasSingletonItem
unsafe _header.pointee.hasSingletonItem
}
@inlinable
internal var hasSingletonChild: Bool {
_header.pointee.hasSingletonChild
unsafe _header.pointee.hasSingletonChild
}
@inlinable
internal var isAtrophiedNode: Bool {
hasSingletonChild && self[child: .zero].isCollisionNode
unsafe hasSingletonChild && self[child: .zero].isCollisionNode
}
}
@@ -38,6 +38,7 @@
/// items map.
@usableFromInline
@frozen
@safe
internal struct _HashNode<Key: Hashable, Value> {
// Warning: This struct must be kept layout-compatible with _RawHashNode.
// Do not add any new stored properties to this type.
@@ -72,29 +73,33 @@ extension _HashNode {
extension _HashNode {
@inlinable @inline(__always)
@unsafe
internal var unmanaged: _UnmanagedHashNode {
_UnmanagedHashNode(raw.storage)
unsafe _UnmanagedHashNode(raw.storage)
}
@inlinable @inline(__always)
@unsafe
internal func isIdentical(to other: _UnmanagedHashNode) -> Bool {
raw.isIdentical(to: other)
unsafe raw.isIdentical(to: other)
}
}
extension _HashNode {
@inlinable @inline(__always)
@unsafe
internal func read<R>(
_ body: (UnsafeHandle) throws -> R
) rethrows -> R {
try UnsafeHandle.read(raw.storage, body)
unsafe try UnsafeHandle.read(raw.storage, body)
}
@inlinable @inline(__always)
@unsafe
internal mutating func update<R>(
_ body: (UnsafeHandle) throws -> R
) rethrows -> R {
try UnsafeHandle.update(raw.storage, body)
unsafe try UnsafeHandle.update(raw.storage, body)
}
}
@@ -103,27 +108,27 @@ extension _HashNode {
extension _HashNode {
@inlinable
internal var isCollisionNode: Bool {
self.read { $0.isCollisionNode }
unsafe self.read { unsafe $0.isCollisionNode }
}
@inlinable
internal var collisionHash: _Hash {
self.read { $0.collisionHash }
unsafe self.read { unsafe $0.collisionHash }
}
@inlinable
internal var hasSingletonItem: Bool {
self.read { $0.hasSingletonItem }
unsafe self.read { unsafe $0.hasSingletonItem }
}
@inlinable
internal var hasSingletonChild: Bool {
self.read { $0.hasSingletonChild }
unsafe self.read { unsafe $0.hasSingletonChild }
}
@inlinable
internal var isAtrophied: Bool {
self.read { $0.isAtrophiedNode }
unsafe self.read { unsafe $0.isAtrophiedNode }
}
}
@@ -134,7 +139,7 @@ extension _HashNode {
// memory address of the root node is a reasonable substitute.
// Alternatively, we could use a per-thread counter along with a thread
// id, or some sort of global banks of atomic integer counters.
let address = Unmanaged.passUnretained(raw.storage).toOpaque()
let address = unsafe Unmanaged.passUnretained(raw.storage).toOpaque()
return UInt(bitPattern: address)
}
}
@@ -86,16 +86,16 @@ internal struct _HashStack<Element> {
assert(level < _count)
return withUnsafeBytes(of: &_contents) { buffer in
// Homogeneous tuples are layout compatible with their element type
let start = buffer.baseAddress!.assumingMemoryBound(to: Element.self)
return start[Int(truncatingIfNeeded: level)]
let start = unsafe buffer.baseAddress!.assumingMemoryBound(to: Element.self)
return unsafe start[Int(truncatingIfNeeded: level)]
}
}
set {
assert(level < capacity)
withUnsafeMutableBytes(of: &_contents) { buffer in
// Homogeneous tuples are layout compatible with their element type
let start = buffer.baseAddress!.assumingMemoryBound(to: Element.self)
start[Int(truncatingIfNeeded: level)] = newValue
let start = unsafe buffer.baseAddress!.assumingMemoryBound(to: Element.self)
unsafe start[Int(truncatingIfNeeded: level)] = newValue
}
}
}
@@ -13,121 +13,132 @@
@usableFromInline
@frozen
@unsafe
internal struct _HashTreeIterator {
@usableFromInline
@unsafe
internal struct _Opaque {
@safe
internal var ancestorSlots: _AncestorHashSlots
@unsafe
internal var ancestorNodes: _HashStack<_UnmanagedHashNode>
@safe
internal var level: _HashLevel
@safe
internal var isAtEnd: Bool
@usableFromInline
@_effects(releasenone)
internal init(_ root: _UnmanagedHashNode) {
self.ancestorSlots = .empty
self.ancestorNodes = _HashStack(filledWith: root)
unsafe self.ancestorNodes = _HashStack(filledWith: root)
self.level = .top
self.isAtEnd = false
}
}
@usableFromInline
@unsafe
internal let root: _RawHashStorage
@usableFromInline
@unsafe
internal var node: _UnmanagedHashNode
@usableFromInline
@safe
internal var slot: _HashSlot
@usableFromInline
@safe
internal var endSlot: _HashSlot
@usableFromInline
@unsafe
internal var _o: _Opaque
@usableFromInline
@_effects(releasenone)
internal init(root: __shared _RawHashNode) {
self.root = root.storage
self.node = root.unmanaged
unsafe self.root = root.storage
unsafe self.node = root.unmanaged
self.slot = .zero
self.endSlot = node.itemsEndSlot
self._o = _Opaque(self.node)
self.endSlot = unsafe node.itemsEndSlot
unsafe self._o = _Opaque(self.node)
if node.hasItems { return }
if node.hasChildren {
_descendToLeftmostItem(ofChildAtSlot: .zero)
if unsafe node.hasItems { return }
if unsafe node.hasChildren {
unsafe _descendToLeftmostItem(ofChildAtSlot: .zero)
} else {
self._o.isAtEnd = true
unsafe self._o.isAtEnd = true
}
}
}
extension _HashTreeIterator: IteratorProtocol {
extension _HashTreeIterator: @unsafe IteratorProtocol {
@inlinable
internal mutating func next(
) -> (node: _UnmanagedHashNode, slot: _HashSlot)? {
guard slot < endSlot else {
return _next()
return unsafe _next()
}
defer { slot = slot.next() }
return (node, slot)
return unsafe (node, slot)
}
@usableFromInline
@_effects(releasenone)
internal mutating func _next(
) -> (node: _UnmanagedHashNode, slot: _HashSlot)? {
if _o.isAtEnd { return nil }
if node.hasChildren {
_descendToLeftmostItem(ofChildAtSlot: .zero)
if unsafe _o.isAtEnd { return nil }
if unsafe node.hasChildren {
unsafe _descendToLeftmostItem(ofChildAtSlot: .zero)
slot = slot.next()
return (node, .zero)
return unsafe (node, .zero)
}
while !_o.level.isAtRoot {
let nextChild = _ascend().next()
if nextChild < node.childrenEndSlot {
_descendToLeftmostItem(ofChildAtSlot: nextChild)
while unsafe !_o.level.isAtRoot {
let nextChild = unsafe _ascend().next()
if unsafe nextChild < node.childrenEndSlot {
unsafe _descendToLeftmostItem(ofChildAtSlot: nextChild)
slot = slot.next()
return (node, .zero)
return unsafe (node, .zero)
}
}
// At end
endSlot = node.itemsEndSlot
endSlot = unsafe node.itemsEndSlot
slot = endSlot
_o.isAtEnd = true
unsafe _o.isAtEnd = true
return nil
}
}
extension _HashTreeIterator {
internal mutating func _descend(toChildSlot childSlot: _HashSlot) {
assert(childSlot < node.childrenEndSlot)
_o.ancestorSlots[_o.level] = childSlot
_o.ancestorNodes.push(node)
_o.level = _o.level.descend()
node = node.unmanagedChild(at: childSlot)
assert(unsafe childSlot < node.childrenEndSlot)
unsafe _o.ancestorSlots[_o.level] = childSlot
unsafe _o.ancestorNodes.push(node)
unsafe _o.level = _o.level.descend()
unsafe node = node.unmanagedChild(at: childSlot)
slot = .zero
endSlot = node.itemsEndSlot
unsafe endSlot = node.itemsEndSlot
}
internal mutating func _ascend() -> _HashSlot {
assert(!_o.level.isAtRoot)
node = _o.ancestorNodes.pop()
_o.level = _o.level.ascend()
let childSlot = _o.ancestorSlots[_o.level]
_o.ancestorSlots.clear(_o.level)
assert(unsafe !_o.level.isAtRoot)
unsafe node = _o.ancestorNodes.pop()
unsafe _o.level = _o.level.ascend()
let childSlot = unsafe _o.ancestorSlots[_o.level]
unsafe _o.ancestorSlots.clear(_o.level)
return childSlot
}
internal mutating func _descendToLeftmostItem(
ofChildAtSlot childSlot: _HashSlot
) {
_descend(toChildSlot: childSlot)
unsafe _descend(toChildSlot: childSlot)
while endSlot == .zero {
assert(node.hasChildren)
_descend(toChildSlot: .zero)
assert(unsafe node.hasChildren)
unsafe _descend(toChildSlot: .zero)
}
}
}
@@ -95,35 +95,35 @@ extension _HashNode {
// The empty singleton does not count as a node and occupies no space.
if self.raw.storage === _emptySingleton { return }
read {
unsafe read {
stats.nodeCount += 1
stats.itemCount += $0.itemCount
stats.itemCount += unsafe $0.itemCount
if isCollisionNode {
stats.collisionNodeCount += 1
stats.collisionCount += $0.itemCount
stats._collisionChainCount += $0.itemCount * ($0.itemCount - 1) / 2
stats.collisionCount += unsafe $0.itemCount
stats._collisionChainCount += unsafe $0.itemCount * ($0.itemCount - 1) / 2
}
let keyStride = MemoryLayout<Key>.stride
let valueStride = MemoryLayout<Value>.stride
stats.maxItemDepth = Swift.max(stats.maxItemDepth, level.depth)
stats._sumItemDepth += (level.depth + 1) * $0.itemCount
stats.capacityBytes += $0.byteCapacity
stats.freeBytes += $0.bytesFree
stats.itemBytes += $0.itemCount * (keyStride + valueStride)
stats.childBytes += $0.childCount * MemoryLayout<_RawHashNode>.stride
stats._sumItemDepth += unsafe (level.depth + 1) * $0.itemCount
stats.capacityBytes += unsafe $0.byteCapacity
stats.freeBytes += unsafe $0.bytesFree
stats.itemBytes += unsafe $0.itemCount * (keyStride + valueStride)
stats.childBytes += unsafe $0.childCount * MemoryLayout<_RawHashNode>.stride
let objectHeaderSize = 2 * MemoryLayout<Int>.stride
// Note: for simplicity, we assume that there is no padding between
// the object header and the storage header.
let start = _getUnsafePointerToStoredProperties(self.raw.storage)
let end = $0._memory + $0.byteCapacity
stats.grossBytes += objectHeaderSize + (end - start)
let start = unsafe _getUnsafePointerToStoredProperties(self.raw.storage)
let end = unsafe $0._memory + $0.byteCapacity
stats.grossBytes += unsafe objectHeaderSize + (end - start)
for child in $0.children {
for unsafe child in unsafe $0.children {
child.gatherStatistics(level.descend(), &stats)
}
}
@@ -26,6 +26,7 @@ extension _RawHashNode {
/// by them) do not escape the closure call that received them.
@usableFromInline
@frozen
@unsafe
internal struct UnsafeHandle {
@usableFromInline
internal let _header: UnsafePointer<_HashNodeHeader>
@@ -38,8 +39,8 @@ extension _RawHashNode {
_ header: UnsafePointer<_HashNodeHeader>,
_ memory: UnsafeRawPointer
) {
self._header = header
self._memory = memory
unsafe self._header = header
unsafe self._memory = memory
}
}
}
@@ -50,9 +51,9 @@ extension _RawHashNode.UnsafeHandle {
_ node: _UnmanagedHashNode,
_ body: (Self) throws -> R
) rethrows -> R {
try node.ref._withUnsafeGuaranteedRef { storage in
try storage.withUnsafeMutablePointers { header, elements in
try body(Self(header, UnsafeRawPointer(elements)))
unsafe try node.ref._withUnsafeGuaranteedRef { storage in
unsafe try storage.withUnsafeMutablePointers { header, elements in
unsafe try body(Self(header, UnsafeRawPointer(elements)))
}
}
}
@@ -61,58 +62,58 @@ extension _RawHashNode.UnsafeHandle {
extension _RawHashNode.UnsafeHandle {
@inline(__always)
internal var isCollisionNode: Bool {
_header.pointee.isCollisionNode
unsafe _header.pointee.isCollisionNode
}
@inline(__always)
internal var collisionHash: _Hash {
assert(isCollisionNode)
return _memory.load(as: _Hash.self)
assert(unsafe isCollisionNode)
return unsafe _memory.load(as: _Hash.self)
}
@inline(__always)
internal var hasChildren: Bool {
_header.pointee.hasChildren
unsafe _header.pointee.hasChildren
}
@inline(__always)
internal var childCount: Int {
_header.pointee.childCount
unsafe _header.pointee.childCount
}
@inline(__always)
internal var childrenEndSlot: _HashSlot {
_header.pointee.childrenEndSlot
unsafe _header.pointee.childrenEndSlot
}
@inline(__always)
internal var hasItems: Bool {
_header.pointee.hasItems
unsafe _header.pointee.hasItems
}
@inline(__always)
internal var itemCount: Int {
_header.pointee.itemCount
unsafe _header.pointee.itemCount
}
@inline(__always)
internal var itemsEndSlot: _HashSlot {
_header.pointee.itemsEndSlot
unsafe _header.pointee.itemsEndSlot
}
@inline(__always)
internal var _childrenStart: UnsafePointer<_RawHashNode> {
_memory.assumingMemoryBound(to: _RawHashNode.self)
unsafe _memory.assumingMemoryBound(to: _RawHashNode.self)
}
internal subscript(child slot: _HashSlot) -> _RawHashNode {
unsafeAddress {
assert(slot < childrenEndSlot)
return _childrenStart + slot.value
assert(unsafe slot < childrenEndSlot)
return unsafe _childrenStart + slot.value
}
}
internal var children: UnsafeBufferPointer<_RawHashNode> {
UnsafeBufferPointer(start: _childrenStart, count: childCount)
unsafe UnsafeBufferPointer(start: _childrenStart, count: childCount)
}
}
@@ -19,6 +19,7 @@
/// `distance(from:to:)`, `index(_:offsetBy:)` in non-generic code.
@usableFromInline
@frozen
@safe
internal struct _RawHashNode {
@usableFromInline
internal var storage: _RawHashStorage
@@ -35,22 +36,24 @@ internal struct _RawHashNode {
extension _RawHashNode {
@inline(__always)
@unsafe
internal func read<R>(_ body: (UnsafeHandle) -> R) -> R {
storage.withUnsafeMutablePointers { header, elements in
body(UnsafeHandle(header, UnsafeRawPointer(elements)))
unsafe storage.withUnsafeMutablePointers { header, elements in
unsafe body(UnsafeHandle(header, UnsafeRawPointer(elements)))
}
}
}
extension _RawHashNode {
@inlinable @inline(__always)
@unsafe
internal var unmanaged: _UnmanagedHashNode {
_UnmanagedHashNode(storage)
unsafe _UnmanagedHashNode(storage)
}
@inlinable @inline(__always)
internal func isIdentical(to other: _UnmanagedHashNode) -> Bool {
other.ref.toOpaque() == Unmanaged.passUnretained(storage).toOpaque()
unsafe other.ref.toOpaque() == Unmanaged.passUnretained(storage).toOpaque()
}
}
@@ -58,18 +61,18 @@ extension _RawHashNode {
@usableFromInline
internal func validatePath(_ path: _UnsafePath) {
var l = _HashLevel.top
var n = self.unmanaged
var n = unsafe self.unmanaged
while l < path.level {
let slot = path.ancestors[l]
precondition(slot < n.childrenEndSlot)
n = n.unmanagedChild(at: slot)
precondition(unsafe slot < n.childrenEndSlot)
unsafe n = n.unmanagedChild(at: slot)
l = l.descend()
}
precondition(n == path.node)
precondition(unsafe n == path.node)
if path._isItem {
precondition(path.nodeSlot < n.itemsEndSlot)
precondition(unsafe path.nodeSlot < n.itemsEndSlot)
} else {
precondition(path.nodeSlot <= n.childrenEndSlot)
precondition(unsafe path.nodeSlot <= n.childrenEndSlot)
}
}
}
@@ -23,13 +23,14 @@ import InternalCollectionsUtilities
/// `_UnmanagedHashNode`. Doing so results in undefined behavior.
@usableFromInline
@frozen
@unsafe
internal struct _UnmanagedHashNode {
@usableFromInline
internal var ref: Unmanaged<_RawHashStorage>
@inlinable @inline(__always)
internal init(_ storage: _RawHashStorage) {
self.ref = .passUnretained(storage)
unsafe self.ref = .passUnretained(storage)
}
}
@@ -42,68 +43,69 @@ extension _UnmanagedHashNode: Equatable {
/// a newly created node.)
@inlinable
internal static func ==(left: Self, right: Self) -> Bool {
left.ref.toOpaque() == right.ref.toOpaque()
unsafe left.ref.toOpaque() == right.ref.toOpaque()
}
}
extension _UnmanagedHashNode: CustomStringConvertible {
@usableFromInline
internal var description: String {
_addressString(for: ref.toOpaque())
_addressString(for: unsafe ref.toOpaque())
}
}
extension _UnmanagedHashNode {
@inlinable @inline(__always)
@unsafe
internal func withRaw<R>(_ body: (_RawHashStorage) -> R) -> R {
ref._withUnsafeGuaranteedRef(body)
unsafe ref._withUnsafeGuaranteedRef(body)
}
@inline(__always)
internal func read<R>(_ body: (_RawHashNode.UnsafeHandle) -> R) -> R {
ref._withUnsafeGuaranteedRef { storage in
storage.withUnsafeMutablePointers { header, elements in
body(_RawHashNode.UnsafeHandle(header, UnsafeRawPointer(elements)))
unsafe ref._withUnsafeGuaranteedRef { storage in
unsafe storage.withUnsafeMutablePointers { header, elements in
unsafe body(_RawHashNode.UnsafeHandle(header, UnsafeRawPointer(elements)))
}
}
}
@inlinable
internal var hasItems: Bool {
withRaw { $0.header.hasItems }
unsafe withRaw { $0.header.hasItems }
}
@inlinable
internal var hasChildren: Bool {
withRaw { $0.header.hasChildren }
unsafe withRaw { $0.header.hasChildren }
}
@inlinable
internal var itemCount: Int {
withRaw { $0.header.itemCount }
unsafe withRaw { $0.header.itemCount }
}
@inlinable
internal var childCount: Int {
withRaw { $0.header.childCount }
unsafe withRaw { $0.header.childCount }
}
@inlinable
internal var itemsEndSlot: _HashSlot {
withRaw { _HashSlot($0.header.itemCount) }
unsafe withRaw { _HashSlot($0.header.itemCount) }
}
@inlinable
internal var childrenEndSlot: _HashSlot {
withRaw { _HashSlot($0.header.childCount) }
unsafe withRaw { _HashSlot($0.header.childCount) }
}
@inlinable
internal func unmanagedChild(at slot: _HashSlot) -> Self {
withRaw { raw in
unsafe withRaw { raw in
assert(slot.value < raw.header.childCount)
return raw.withUnsafeMutablePointerToElements { p in
Self(p[slot.value].storage)
return unsafe raw.withUnsafeMutablePointerToElements { p in
unsafe Self(p[slot.value].storage)
}
}
}
@@ -37,27 +37,32 @@
/// would considerably embiggen the size of the path construct.)
@usableFromInline
@frozen
@unsafe
internal struct _UnsafePath {
@usableFromInline
@safe
internal var ancestors: _AncestorHashSlots
@usableFromInline
internal var node: _UnmanagedHashNode
@usableFromInline
@safe
internal var nodeSlot: _HashSlot
@usableFromInline
@safe
internal var level: _HashLevel
@usableFromInline
@safe
internal var _isItem: Bool
@inlinable
internal init(root: __shared _RawHashNode) {
self.level = .top
self.ancestors = .empty
self.node = root.unmanaged
unsafe self.node = root.unmanaged
self.nodeSlot = .zero
self._isItem = root.storage.header.hasItems
}
@@ -70,10 +75,10 @@ extension _UnsafePath {
_ node: _UnmanagedHashNode,
childSlot: _HashSlot
) {
assert(childSlot < node.childrenEndSlot)
assert(unsafe childSlot < node.childrenEndSlot)
self.level = level
self.ancestors = ancestors
self.node = node
unsafe self.node = node
self.nodeSlot = childSlot
self._isItem = false
}
@@ -85,10 +90,10 @@ extension _UnsafePath {
_ node: _UnmanagedHashNode,
itemSlot: _HashSlot
) {
assert(itemSlot < node.itemsEndSlot)
assert(unsafe itemSlot < node.itemsEndSlot)
self.level = level
self.ancestors = ancestors
self.node = node
unsafe self.node = node
self.nodeSlot = itemSlot
self._isItem = true
}
@@ -163,13 +168,13 @@ extension _UnsafePath: CustomStringConvertible {
d += ".\(self.ancestors[l])"
l = l.descend()
}
if isPlaceholder {
if unsafe isPlaceholder {
d += ".end[\(self.nodeSlot)]"
} else if isOnItem {
d += "[\(self.nodeSlot)]"
} else if isOnChild {
} else if unsafe isOnChild {
d += ".\(self.nodeSlot)"
} else if isOnNodeEnd {
} else if unsafe isOnNodeEnd {
d += ".end(\(self.nodeSlot))"
}
return d
@@ -183,6 +188,7 @@ extension _UnsafePath {
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable @inline(__always)
@safe
internal var isOnItem: Bool {
// Note: this may be true even if nodeSlot == itemCount (insertion paths).
_isItem
@@ -197,7 +203,7 @@ extension _UnsafePath {
/// valid.
@inlinable
internal var isPlaceholder: Bool {
_isItem && nodeSlot.value == node.itemCount
unsafe _isItem && nodeSlot.value == node.itemCount
}
/// Returns true if this path addresses a node in the tree; otherwise returns
@@ -207,7 +213,7 @@ extension _UnsafePath {
/// valid.
@inlinable
internal var isOnChild: Bool {
!_isItem && nodeSlot.value < node.childCount
unsafe !_isItem && nodeSlot.value < node.childCount
}
/// Returns true if this path addresses an empty slot within a node in a tree;
@@ -217,7 +223,7 @@ extension _UnsafePath {
/// valid.
@inlinable
internal var isOnNodeEnd: Bool {
!_isItem && nodeSlot.value == node.childCount
unsafe !_isItem && nodeSlot.value == node.childCount
}
}
@@ -229,8 +235,8 @@ extension _UnsafePath {
/// valid.
@inlinable
internal var currentChild: _UnmanagedHashNode {
assert(isOnChild)
return node.unmanagedChild(at: nodeSlot)
assert(unsafe isOnChild)
return unsafe node.unmanagedChild(at: nodeSlot)
}
/// Returns the chid slot in this path corresponding to the specified level.
@@ -264,7 +270,7 @@ extension _UnsafePath {
// As a special exception, this allows slot to equal the item count.
// This can happen for paths that address the position a new item might be
// inserted later.
assert(slot <= node.itemsEndSlot)
assert(unsafe slot <= node.itemsEndSlot)
nodeSlot = slot
_isItem = true
}
@@ -278,7 +284,7 @@ extension _UnsafePath {
internal mutating func selectChild(at slot: _HashSlot) {
// As a special exception, this allows slot to equal the child count.
// This is equivalent to a call to `selectEnd()`.
assert(slot <= node.childrenEndSlot)
assert(unsafe slot <= node.childrenEndSlot)
nodeSlot = slot
_isItem = false
}
@@ -290,7 +296,7 @@ extension _UnsafePath {
@usableFromInline
@_effects(releasenone)
internal mutating func selectEnd() {
nodeSlot = node.childrenEndSlot
nodeSlot = unsafe node.childrenEndSlot
_isItem = false
}
@@ -303,10 +309,10 @@ extension _UnsafePath {
/// valid.
@inlinable
internal mutating func descend() {
self.node = currentChild
unsafe self.node = currentChild
self.ancestors[level] = nodeSlot
self.nodeSlot = .zero
self._isItem = node.hasItems
self._isItem = unsafe node.hasItems
self.level = level.descend()
}
@@ -321,12 +327,12 @@ extension _UnsafePath {
internal mutating func descendToChild(
_ child: _UnmanagedHashNode, at slot: _HashSlot
) {
assert(slot < node.childrenEndSlot)
assert(child == node.unmanagedChild(at: slot))
self.node = child
assert(unsafe slot < node.childrenEndSlot)
assert(unsafe child == node.unmanagedChild(at: slot))
unsafe self.node = child
self.ancestors[level] = slot
self.nodeSlot = .zero
self._isItem = node.hasItems
self._isItem = unsafe node.hasItems
self.level = level.descend()
}
@@ -336,7 +342,7 @@ extension _UnsafePath {
guard level != self.level else { return }
assert(level < self.level)
self.level = level
self.node = ancestor
unsafe self.node = ancestor
self.nodeSlot = ancestors[level]
self.ancestors.clear(atOrBelow: level)
self._isItem = false
@@ -356,19 +362,19 @@ extension _UnsafePath {
) -> Bool {
if self.level.isAtRoot { return false }
var best: _UnsafePath? = nil
var n = root.unmanaged
var n = unsafe root.unmanaged
var l: _HashLevel = .top
while l < self.level {
let slot = self.ancestors[l]
if test(n, slot) {
best = _UnsafePath(
if unsafe test(n, slot) {
unsafe best = _UnsafePath(
l, self.ancestors.truncating(to: l), n, childSlot: slot)
}
n = n.unmanagedChild(at: slot)
unsafe n = n.unmanagedChild(at: slot)
l = l.descend()
}
guard let best = best else { return false }
self = best
guard let best = unsafe best else { return false }
unsafe self = best
return true
}
}
@@ -384,7 +390,7 @@ extension _UnsafePath {
mutating func selectNextItem() -> Bool {
assert(isOnItem)
nodeSlot = nodeSlot.next()
if nodeSlot < node.itemsEndSlot { return true }
if unsafe nodeSlot < node.itemsEndSlot { return true }
nodeSlot = .zero
_isItem = false
return false
@@ -398,7 +404,7 @@ extension _UnsafePath {
/// valid.
mutating func selectNextChild() -> Bool {
assert(!isOnItem)
let childrenEndSlot = node.childrenEndSlot
let childrenEndSlot = unsafe node.childrenEndSlot
guard nodeSlot < childrenEndSlot else { return false }
nodeSlot = nodeSlot.next()
return nodeSlot < childrenEndSlot
@@ -416,8 +422,8 @@ extension _UnsafePath {
@usableFromInline
@_effects(releasenone)
internal mutating func descendToLeftMostItem() {
while isOnChild {
descend()
while unsafe isOnChild {
unsafe descend()
}
}
@@ -429,16 +435,16 @@ extension _UnsafePath {
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
internal mutating func descendToRightMostItem() {
assert(isOnChild)
assert(unsafe isOnChild)
while true {
descend()
let childrenEndSlot = node.childrenEndSlot
unsafe descend()
let childrenEndSlot = unsafe node.childrenEndSlot
guard childrenEndSlot > .zero else { break }
selectChild(at: childrenEndSlot.previous())
unsafe selectChild(at: childrenEndSlot.previous())
}
let itemsEndSlot = node.itemsEndSlot
let itemsEndSlot = unsafe node.itemsEndSlot
assert(itemsEndSlot > .zero)
selectItem(at: itemsEndSlot.previous())
unsafe selectItem(at: itemsEndSlot.previous())
}
/// Find the next item in a preorder walk in the tree following the currently
@@ -448,23 +454,23 @@ extension _UnsafePath {
@_effects(releasenone)
internal mutating func findSuccessorItem(under root: _RawHashNode) -> Bool {
guard isOnItem else { return false }
if selectNextItem() { return true }
if node.hasChildren {
descendToLeftMostItem()
if unsafe selectNextItem() { return true }
if unsafe node.hasChildren {
unsafe descendToLeftMostItem()
assert(isOnItem)
return true
}
if ascendToNearestAncestor(
under: root, where: { $1.next() < $0.childrenEndSlot }
if unsafe ascendToNearestAncestor(
under: root, where: { unsafe $1.next() < $0.childrenEndSlot }
) {
let r = selectNextChild()
let r = unsafe selectNextChild()
assert(r)
descendToLeftMostItem()
unsafe descendToLeftMostItem()
assert(isOnItem)
return true
}
self = _UnsafePath(root: root)
self.selectEnd()
unsafe self = _UnsafePath(root: root)
unsafe self.selectEnd()
return true
}
@@ -476,33 +482,33 @@ extension _UnsafePath {
internal mutating func findPredecessorItem(under root: _RawHashNode) -> Bool {
switch (isOnItem, nodeSlot > .zero) {
case (true, true):
selectItem(at: nodeSlot.previous())
unsafe selectItem(at: nodeSlot.previous())
return true
case (false, true):
selectChild(at: nodeSlot.previous())
descendToRightMostItem()
unsafe selectChild(at: nodeSlot.previous())
unsafe descendToRightMostItem()
return true
case (false, false):
if node.hasItems {
selectItem(at: node.itemsEndSlot.previous())
if unsafe node.hasItems {
unsafe selectItem(at: node.itemsEndSlot.previous())
return true
}
case (true, false):
break
}
guard
ascendToNearestAncestor(
unsafe ascendToNearestAncestor(
under: root,
where: { $0.hasItems || $1 > .zero })
where: { unsafe $0.hasItems || $1 > .zero })
else { return false }
if nodeSlot > .zero {
selectChild(at: nodeSlot.previous())
descendToRightMostItem()
unsafe selectChild(at: nodeSlot.previous())
unsafe descendToRightMostItem()
return true
}
if node.hasItems {
selectItem(at: node.itemsEndSlot.previous())
if unsafe node.hasItems {
unsafe selectItem(at: node.itemsEndSlot.previous())
return true
}
return false
@@ -518,14 +524,14 @@ extension _RawHashNode {
internal func preorderPosition(
_ level: _HashLevel, of path: _UnsafePath
) -> Int {
if path.isOnNodeEnd { return count }
if unsafe path.isOnNodeEnd { return count }
assert(path.isOnItem)
if level < path.level {
let childSlot = path.childSlot(at: level)
return read {
let prefix = $0.children[..<childSlot.value]
let childSlot = unsafe path.childSlot(at: level)
return unsafe read {
let prefix = unsafe $0.children[..<childSlot.value]
.reduce($0.itemCount) { $0 + $1.count }
let positionWithinChild = $0[child: childSlot]
let positionWithinChild = unsafe $0[child: childSlot]
.preorderPosition(level.descend(), of: path)
return prefix + positionWithinChild
}
@@ -548,23 +554,23 @@ extension _UnsafePath {
_ position: Int
) -> (found: Bool, remaining: Int) {
assert(position >= 0)
let top = node
let top = unsafe node
let topLevel = level
var stop = false
var remaining = position
while !stop {
let itemCount = node.itemCount
let itemCount = unsafe node.itemCount
if remaining < itemCount {
selectItem(at: _HashSlot(remaining))
unsafe selectItem(at: _HashSlot(remaining))
return (true, 0)
}
remaining -= itemCount
node.read {
let children = $0.children
unsafe node.read {
let children = unsafe $0.children
for i in children.indices {
let c = children[i].count
let c = unsafe children[i].count
if remaining < c {
descendToChild(children[i].unmanaged, at: _HashSlot(i))
unsafe descendToChild(children[i].unmanaged, at: _HashSlot(i))
return
}
remaining &-= c
@@ -572,8 +578,8 @@ extension _UnsafePath {
stop = true
}
}
ascend(to: top, at: topLevel)
selectEnd()
unsafe ascend(to: top, at: topLevel)
unsafe selectEnd()
return (false, remaining)
}
}
@@ -589,65 +595,65 @@ extension _RawHashNode {
_ level: _HashLevel, from start: _UnsafePath, to end: _UnsafePath
) -> Int {
assert(level.isAtRoot)
if start.isOnNodeEnd {
if unsafe start.isOnNodeEnd {
// Shortcut: distance from end.
return preorderPosition(level, of: end) - count
return unsafe preorderPosition(level, of: end) - count
}
if end.isOnNodeEnd {
if unsafe end.isOnNodeEnd {
// Shortcut: distance to end.
return count - preorderPosition(level, of: start)
return unsafe count - preorderPosition(level, of: start)
}
assert(start.isOnItem)
assert(end.isOnItem)
if start.level == end.level, start.ancestors == end.ancestors {
// Shortcut: the paths are under the same node.
precondition(start.node == end.node, "Internal index validation error")
return start.currentItemSlot.distance(to: end.currentItemSlot)
precondition(unsafe start.node == end.node, "Internal index validation error")
return unsafe start.currentItemSlot.distance(to: end.currentItemSlot)
}
if
start.level < end.level,
start.ancestors.isEqual(to: end.ancestors, upTo: start.level)
{
// Shortcut: start's node is an ancestor of end's position.
return start.node._distance(
return unsafe start.node._distance(
start.level, fromItemAt: start.currentItemSlot, to: end)
}
if start.ancestors.isEqual(to: end.ancestors, upTo: end.level) {
// Shortcut: end's node is an ancestor of start's position.
return -end.node._distance(
return unsafe -end.node._distance(
end.level, fromItemAt: end.currentItemSlot, to: start)
}
// No shortcuts -- the two paths are in different subtrees.
// Start descending from the root to look for the closest common
// ancestor.
if start < end {
return _distance(level, from: start, to: end)
if unsafe start < end {
return unsafe _distance(level, from: start, to: end)
}
return -_distance(level, from: end, to: start)
return unsafe -_distance(level, from: end, to: start)
}
internal func _distance(
_ level: _HashLevel, from start: _UnsafePath, to end: _UnsafePath
) -> Int {
assert(start < end)
assert(unsafe start < end)
assert(level < start.level)
assert(level < end.level)
let slot1 = start.childSlot(at: level)
let slot2 = end.childSlot(at: level)
let slot1 = unsafe start.childSlot(at: level)
let slot2 = unsafe end.childSlot(at: level)
if slot1 == slot2 {
return read {
$0[child: slot1]._distance(level.descend(), from: start, to: end)
return unsafe read {
unsafe $0[child: slot1]._distance(level.descend(), from: start, to: end)
}
}
return read {
let children = $0.children
let d1 = children[slot1.value]
return unsafe read {
let children = unsafe $0.children
let d1 = unsafe children[slot1.value]
.preorderPosition(level.descend(), of: start)
let d2 = children[slot1.value &+ 1 ..< slot2.value]
let d2 = unsafe children[slot1.value &+ 1 ..< slot2.value]
.reduce(0) { $0 + $1.count }
let d3 = children[slot2.value]
let d3 = unsafe children[slot2.value]
.preorderPosition(level.descend(), of: end)
return (children[slot1.value].count - d1) + d2 + d3
return unsafe (children[slot1.value].count - d1) + d2 + d3
}
}
}
@@ -656,14 +662,14 @@ extension _UnmanagedHashNode {
internal func _distance(
_ level: _HashLevel, fromItemAt start: _HashSlot, to end: _UnsafePath
) -> Int {
read {
assert(start < $0.itemsEndSlot)
unsafe read {
assert(unsafe start < $0.itemsEndSlot)
assert(level < end.level)
let childSlot = end.childSlot(at: level)
let children = $0.children
let prefix = children[..<childSlot.value]
let childSlot = unsafe end.childSlot(at: level)
let children = unsafe $0.children
let prefix = unsafe children[..<childSlot.value]
.reduce($0.itemCount - start.value) { $0 + $1.count }
let positionWithinChild = children[childSlot.value]
let positionWithinChild = unsafe children[childSlot.value]
.preorderPosition(level.descend(), of: end)
return prefix + positionWithinChild
}
@@ -677,16 +683,16 @@ extension _HashNode {
internal func path(
to key: Key, _ hash: _Hash
) -> _UnsafePath? {
var node = unmanaged
var node = unsafe unmanaged
var level: _HashLevel = .top
var ancestors: _AncestorHashSlots = .empty
while true {
let r = UnsafeHandle.read(node) { $0.find(level, key, hash) }
let r = unsafe UnsafeHandle.read(node) { unsafe $0.find(level, key, hash) }
guard let r = r else { break }
guard r.descend else {
return _UnsafePath(level, ancestors, node, itemSlot: r.slot)
return unsafe _UnsafePath(level, ancestors, node, itemSlot: r.slot)
}
node = node.unmanagedChild(at: r.slot)
unsafe node = node.unmanagedChild(at: r.slot)
ancestors[level] = r.slot
level = level.descend()
}
@@ -704,15 +710,15 @@ extension _RawHashNode {
limitedBy limit: _UnsafePath
) -> (found: Bool, limited: Bool) {
assert(level.isAtRoot)
if (distance > 0 && limit < path) || (distance < 0 && limit > path) {
return (seek(level, &path, offsetBy: distance), false)
if unsafe (distance > 0 && limit < path) || (distance < 0 && limit > path) {
return unsafe (seek(level, &path, offsetBy: distance), false)
}
var d = distance
guard self._seek(level, &path, offsetBy: &d) else {
path = limit
return (distance >= 0 && d == 0 && limit.isOnNodeEnd, true)
guard unsafe self._seek(level, &path, offsetBy: &d) else {
unsafe path = limit
return unsafe (distance >= 0 && d == 0 && limit.isOnNodeEnd, true)
}
let found = (
let found = unsafe (
distance == 0
|| (distance > 0 && path <= limit)
|| (distance < 0 && path >= limit))
@@ -727,7 +733,7 @@ extension _RawHashNode {
offsetBy distance: Int
) -> Bool {
var d = distance
if self._seek(level, &path, offsetBy: &d) {
if unsafe self._seek(level, &path, offsetBy: &d) {
return true
}
if distance > 0, d == 0 { // endIndex
@@ -747,13 +753,13 @@ extension _RawHashNode {
// subtree. So we first figure out the subtree situation, and only start the
// recursion if the target is outside of it.
assert(level.isAtRoot)
assert(path.isOnItem || path.isOnNodeEnd)
assert(unsafe path.isOnItem || path.isOnNodeEnd)
guard distance != 0 else { return true }
if distance > 0 {
if !path.isOnItem { return false }
// Try a local search within the subtree starting at the current node.
let slot = path.currentItemSlot
let r = path.findItemAtPreorderPosition(distance &+ slot.value)
let slot = unsafe path.currentItemSlot
let r = unsafe path.findItemAtPreorderPosition(distance &+ slot.value)
if r.found {
assert(r.remaining == 0)
return true
@@ -762,17 +768,17 @@ extension _RawHashNode {
distance = r.remaining
// Fall back to recursively descending from the root.
return _seekForward(level, by: &distance, fromSubtree: &path)
return unsafe _seekForward(level, by: &distance, fromSubtree: &path)
}
// distance < 0
if !path.isOnNodeEnd {
if unsafe !path.isOnNodeEnd {
// Shortcut: see if the destination item is within the same node.
// (Doing this here allows us to avoid having to descend from the root
// down only to figure this out.)
let slot = path.nodeSlot
distance &+= slot.value
if distance >= 0 {
path.selectItem(at: _HashSlot(distance))
unsafe path.selectItem(at: _HashSlot(distance))
distance = 0
return true
}
@@ -780,7 +786,7 @@ extension _RawHashNode {
// Otherwise we need to visit ancestor nodes to find the item at the right
// position. We also do this when we start from the end index -- there
// will be no recursion in that case anyway.
return _seekBackward(level, by: &distance, fromSubtree: &path)
return unsafe _seekBackward(level, by: &distance, fromSubtree: &path)
}
/// Find the item at the given positive distance from the last item within the
@@ -793,25 +799,25 @@ extension _RawHashNode {
assert(distance >= 0)
assert(level <= path.level)
guard level < path.level else {
path.selectEnd()
unsafe path.selectEnd()
return false
}
return read {
let children = $0.children
var i = path.childSlot(at: level).value
if children[i]._seekForward(
return unsafe read {
let children = unsafe $0.children
var i = unsafe path.childSlot(at: level).value
if unsafe children[i]._seekForward(
level.descend(), by: &distance, fromSubtree: &path
) {
assert(distance == 0)
return true
}
path.ascend(to: unmanaged, at: level)
unsafe path.ascend(to: unmanaged, at: level)
i &+= 1
while i < children.endIndex {
let c = children[i].count
let c = unsafe children[i].count
if distance < c {
path.descendToChild(children[i].unmanaged, at: _HashSlot(i))
let r = path.findItemAtPreorderPosition(distance)
unsafe path.descendToChild(children[i].unmanaged, at: _HashSlot(i))
let r = unsafe path.findItemAtPreorderPosition(distance)
precondition(r.found, "Internal inconsistency: invalid node counts")
assert(r.remaining == 0)
distance = 0
@@ -820,7 +826,7 @@ extension _RawHashNode {
distance &-= c
i &+= 1
}
path.selectEnd()
unsafe path.selectEnd()
return false
}
}
@@ -835,14 +841,14 @@ extension _RawHashNode {
assert(distance < 0)
assert(level <= path.level)
return read {
let children = $0.children
return unsafe read {
let children = unsafe $0.children
var slot: _HashSlot
if level < path.level {
// We need to descend to the end of the path before we can start the
// search for real.
slot = path.childSlot(at: level)
if children[slot.value]._seekBackward(
slot = unsafe path.childSlot(at: level)
if unsafe children[slot.value]._seekBackward(
level.descend(), by: &distance, fromSubtree: &path
) {
// A deeper level has found the target item.
@@ -850,12 +856,12 @@ extension _RawHashNode {
return true
}
// No luck yet -- ascend to this node and look through preceding data.
path.ascend(to: unmanaged, at: level)
} else if path.isOnNodeEnd {
unsafe path.ascend(to: unmanaged, at: level)
} else if unsafe path.isOnNodeEnd {
// When we start from the root's end (the end index), we don't need
// to descend before starting to look at previous children.
assert(level.isAtRoot && path.node == self.unmanaged)
slot = path.node.childrenEndSlot
assert(unsafe level.isAtRoot && path.node == self.unmanaged)
slot = unsafe path.node.childrenEndSlot
} else { // level == path.level
// The outermost caller has already gone as far back as possible
// within the original subtree. Return a level higher to actually
@@ -866,10 +872,10 @@ extension _RawHashNode {
// Look through all preceding children for the target item.
while slot > .zero {
slot = slot.previous()
let c = children[slot.value].count
let c = unsafe children[slot.value].count
if c + distance >= 0 {
path.descendToChild(children[slot.value].unmanaged, at: slot)
let r = path.findItemAtPreorderPosition(c + distance)
unsafe path.descendToChild(children[slot.value].unmanaged, at: slot)
let r = unsafe path.findItemAtPreorderPosition(c + distance)
precondition(r.found, "Internal inconsistency: invalid node counts")
distance = 0
return true
@@ -877,9 +883,9 @@ extension _RawHashNode {
distance += c
}
// See if the target is hiding somewhere in our immediate items.
distance &+= $0.itemCount
distance &+= unsafe $0.itemCount
if distance >= 0 {
path.selectItem(at: _HashSlot(distance))
unsafe path.selectItem(at: _HashSlot(distance))
distance = 0
return true
}