HashTreeCollections: Qualify internal type names with “Hash”

This makes them unique throughout the package, allowing this code to be built as a single, huge module.
This commit is contained in:
Karoy Lorentey committed 2023-03-21 16:37:22 -07:00
1 parent 9151af9fa8
commit 424c8ece98
56 files changed
+653 -645

No files matched your search

+39 -39
View File
@@ -8,45 +8,45 @@ See https://swift.org/LICENSE.txt for license information
#]]
add_library(HashTreeCollections
"Node/_AncestorSlots.swift"
"Node/_Bitmap.swift"
"Node/_Bucket.swift"
"Node/_Hash.swift"
"Node/_HashTreeIterator.swift"
"Node/_HashTreeStatistics.swift"
"Node/_Level.swift"
"Node/_Node+Builder.swift"
"Node/_Node+Debugging.swift"
"Node/_Node+Initializers.swift"
"Node/_Node+Invariants.swift"
"Node/_Node+Lookups.swift"
"Node/_Node+Primitive Insertions.swift"
"Node/_Node+Primitive Removals.swift"
"Node/_Node+Primitive Replacement.swift"
"Node/_Node+Storage.swift"
"Node/_Node+Structural compactMapValues.swift"
"Node/_Node+Structural filter.swift"
"Node/_Node+Structural intersection.swift"
"Node/_Node+Structural isDisjoint.swift"
"Node/_Node+Structural isEqualSet.swift"
"Node/_Node+Structural isSubset.swift"
"Node/_Node+Structural mapValues.swift"
"Node/_Node+Structural merge.swift"
"Node/_Node+Structural subtracting.swift"
"Node/_Node+Structural symmetricDifference.swift"
"Node/_Node+Structural union.swift"
"Node/_Node+Subtree Insertions.swift"
"Node/_Node+Subtree Modify.swift"
"Node/_Node+Subtree Removals.swift"
"Node/_Node+UnsafeHandle.swift"
"Node/_Node.swift"
"Node/_RawNode+UnsafeHandle.swift"
"Node/_RawNode.swift"
"Node/_Slot.swift"
"Node/_Stack.swift"
"Node/_StorageHeader.swift"
"Node/_UnmanagedNode.swift"
"Node/_UnsafePath.swift"
"HashNode/_AncestorHashSlots.swift"
"HashNode/_Bitmap.swift"
"HashNode/_Bucket.swift"
"HashNode/_Hash.swift"
"HashNode/_HashTreeIterator.swift"
"HashNode/_HashTreeStatistics.swift"
"HashNode/_HashLevel.swift"
"HashNode/_HashNode+Builder.swift"
"HashNode/_HashNode+Debugging.swift"
"HashNode/_HashNode+Initializers.swift"
"HashNode/_HashNode+Invariants.swift"
"HashNode/_HashNode+Lookups.swift"
"HashNode/_HashNode+Primitive Insertions.swift"
"HashNode/_HashNode+Primitive Removals.swift"
"HashNode/_HashNode+Primitive Replacement.swift"
"HashNode/_HashNode+Storage.swift"
"HashNode/_HashNode+Structural compactMapValues.swift"
"HashNode/_HashNode+Structural filter.swift"
"HashNode/_HashNode+Structural intersection.swift"
"HashNode/_HashNode+Structural isDisjoint.swift"
"HashNode/_HashNode+Structural isEqualSet.swift"
"HashNode/_HashNode+Structural isSubset.swift"
"HashNode/_HashNode+Structural mapValues.swift"
"HashNode/_HashNode+Structural merge.swift"
"HashNode/_HashNode+Structural subtracting.swift"
"HashNode/_HashNode+Structural symmetricDifference.swift"
"HashNode/_HashNode+Structural union.swift"
"HashNode/_HashNode+Subtree Insertions.swift"
"HashNode/_HashNode+Subtree Modify.swift"
"HashNode/_HashNode+Subtree Removals.swift"
"HashNode/_HashNode+UnsafeHandle.swift"
"HashNode/_HashNode.swift"
"HashNode/_RawHashNode+UnsafeHandle.swift"
"HashNode/_RawHashNode.swift"
"HashNode/_HashSlot.swift"
"HashNode/_HashStack.swift"
"HashNode/_HashNodeHeader.swift"
"HashNode/_UnmanagedHashNode.swift"
"HashNode/_UnsafePath.swift"
"TreeDictionary/TreeDictionary+Codable.swift"
"TreeDictionary/TreeDictionary+Collection.swift"
"TreeDictionary/TreeDictionary+CustomReflectable.swift"
@@ -12,14 +12,14 @@
/// A collection of slot values logically addressing a particular node in a
/// hash tree. The collection is (logically) extended with zero slots up to
/// the maximum depth of the tree -- to unambiguously address a single node,
/// this therefore needs to be augmented with a `_Level` value.
/// this therefore needs to be augmented with a `_HashLevel` value.
///
/// This construct can only be used to identify a particular node in the tree;
/// it does not necessarily have room to include an item offset in the addressed
/// node. (See `_Path` if you need to address a particular item.)
@usableFromInline
@frozen
struct _AncestorSlots {
struct _AncestorHashSlots {
@usableFromInline
internal var path: UInt
@@ -29,27 +29,27 @@ struct _AncestorSlots {
}
}
extension _AncestorSlots: Equatable {
extension _AncestorHashSlots: Equatable {
@inlinable @inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left.path == right.path
}
}
extension _AncestorSlots {
extension _AncestorHashSlots {
@inlinable @inline(__always)
internal static var empty: Self { Self(0) }
}
extension _AncestorSlots {
extension _AncestorHashSlots {
/// Return or set the slot value at the specified level.
/// If this is used to mutate the collection, then the original value
/// on the given level must be zero.
@inlinable @inline(__always)
internal subscript(_ level: _Level) -> _Slot {
internal subscript(_ level: _HashLevel) -> _HashSlot {
get {
assert(level.shift < UInt.bitWidth)
return _Slot((path &>> level.shift) & _Bucket.bitMask)
return _HashSlot((path &>> level.shift) & _Bucket.bitMask)
}
set {
assert(newValue._value < _Bitmap.capacity)
@@ -59,7 +59,7 @@ extension _AncestorSlots {
}
@inlinable @inline(__always)
internal func appending(_ slot: _Slot, at level: _Level) -> Self {
internal func appending(_ slot: _HashSlot, at level: _HashLevel) -> Self {
var result = self
result[level] = slot
return result
@@ -67,14 +67,14 @@ extension _AncestorSlots {
/// Clear the slot at the specified level, by setting it to zero.
@inlinable
internal mutating func clear(_ level: _Level) {
internal mutating func clear(_ level: _HashLevel) {
guard level.shift < UInt.bitWidth else { return }
path &= ~(_Bucket.bitMask &<< level.shift)
}
/// Clear all slots at or below the specified level, by setting them to zero.
@inlinable
internal mutating func clear(atOrBelow level: _Level) {
internal mutating func clear(atOrBelow level: _HashLevel) {
guard level.shift < UInt.bitWidth else { return }
path &= ~(UInt.max &<< level.shift)
}
@@ -82,16 +82,16 @@ extension _AncestorSlots {
/// Truncate this path to the specified level.
/// Slots at or beyond the specified level are cleared.
@inlinable
internal func truncating(to level: _Level) -> _AncestorSlots {
internal func truncating(to level: _HashLevel) -> _AncestorHashSlots {
assert(level.shift <= UInt.bitWidth)
guard level.shift < UInt.bitWidth else { return self }
return _AncestorSlots(path & ((1 &<< level.shift) &- 1))
return _AncestorHashSlots(path & ((1 &<< level.shift) &- 1))
}
/// Returns true if this path contains non-zero slots at or beyond the
/// specified level, otherwise returns false.
@inlinable
internal func hasDataBelow(_ level: _Level) -> Bool {
internal func hasDataBelow(_ level: _HashLevel) -> Bool {
guard level.shift < UInt.bitWidth else { return false }
return (path &>> level.shift) != 0
}
@@ -99,7 +99,7 @@ extension _AncestorSlots {
/// Compares this path to `other` up to but not including the specified level.
/// Returns true if the path prefixes compare equal, otherwise returns false.
@inlinable
internal func isEqual(to other: Self, upTo level: _Level) -> Bool {
internal func isEqual(to other: Self, upTo level: _HashLevel) -> Bool {
if level.isAtRoot { return true }
if level.isAtBottom { return self == other }
let s = UInt(UInt.bitWidth) - level.shift
@@ -138,12 +138,12 @@ extension _Bitmap {
}
@inlinable @inline(__always)
internal func slot(of bucket: _Bucket) -> _Slot {
_Slot(_value._rank(ofBit: bucket.value))
internal func slot(of bucket: _Bucket) -> _HashSlot {
_HashSlot(_value._rank(ofBit: bucket.value))
}
@inlinable @inline(__always)
internal func bucket(at slot: _Slot) -> _Bucket {
internal func bucket(at slot: _HashSlot) -> _Bucket {
_Bucket(_value._bit(ranked: slot.value)!)
}
}
@@ -182,7 +182,7 @@ extension _Bitmap {
extension _Bitmap: Sequence {
@usableFromInline
internal typealias Element = (bucket: _Bucket, slot: _Slot)
internal typealias Element = (bucket: _Bucket, slot: _HashSlot)
@usableFromInline
@frozen
@@ -191,7 +191,7 @@ extension _Bitmap: Sequence {
internal var bitmap: _Bitmap
@usableFromInline
internal var slot: _Slot
internal var slot: _HashSlot
@inlinable
internal init(_ bitmap: _Bitmap) {
@@ -41,7 +41,7 @@ extension _Hash: CustomStringConvertible {
// Print hash values in radix 32 & reversed, so that the path in the hash
// tree is readily visible.
let p = String(value, radix: _Bitmap.capacity, uppercase: true)
let c = _Level.limit
let c = _HashLevel.limit
let path = String(repeating: "0", count: Swift.max(0, c - p.count)) + p
return String(path.reversed())
}
@@ -55,7 +55,7 @@ extension _Hash {
extension _Hash {
@inlinable
internal subscript(_ level: _Level) -> _Bucket {
internal subscript(_ level: _HashLevel) -> _Bucket {
get {
assert(!level.isAtBottom)
return _Bucket((value &>> level.shift) & _Bucket.bitMask)
@@ -75,7 +75,7 @@ extension _Hash {
}
@inlinable
internal func appending(_ bucket: _Bucket, at level: _Level) -> Self {
internal func appending(_ bucket: _Bucket, at level: _HashLevel) -> Self {
assert(value >> level.shift == 0)
var copy = self
copy[level] = bucket
@@ -83,7 +83,7 @@ extension _Hash {
}
@inlinable
internal func isEqual(to other: _Hash, upTo level: _Level) -> Bool {
internal func isEqual(to other: _Hash, upTo level: _HashLevel) -> Bool {
if level.isAtRoot { return true }
if level.isAtBottom { return self == other }
let s = UInt(UInt.bitWidth) - level.shift
@@ -15,7 +15,7 @@
/// the level always fits in an `UInt8` value.
@usableFromInline
@frozen
internal struct _Level {
internal struct _HashLevel {
/// The bit position within a hash value that begins the hash slice that is
/// associated with this level. For collision nodes, this can be larger than
/// `UInt.bitWidth`.
@@ -35,12 +35,12 @@ internal struct _Level {
@inlinable @inline(__always)
init(depth: Int) {
assert(depth > 0 && depth < _Level.limit)
assert(depth > 0 && depth < _HashLevel.limit)
self.init(shift: UInt(bitPattern: depth * _Bitmap.bitWidth))
}
}
extension _Level {
extension _HashLevel {
@inlinable @inline(__always)
internal static var limit: Int {
(_Hash.bitWidth + _Bitmap.bitWidth - 1) / _Bitmap.bitWidth
@@ -52,8 +52,8 @@ extension _Level {
}
@inlinable @inline(__always)
internal static var top: _Level {
_Level(shift: 0)
internal static var top: _HashLevel {
_HashLevel(shift: 0)
}
/// The bit position within a hash value that begins the hash slice that is
@@ -74,26 +74,26 @@ extension _Level {
}
@inlinable @inline(__always)
internal func descend() -> _Level {
internal func descend() -> _HashLevel {
// FIXME: Consider returning nil when we run out of bits
_Level(_shift: _shift &+ Self._step)
_HashLevel(_shift: _shift &+ Self._step)
}
@inlinable @inline(__always)
internal func ascend() -> _Level {
internal func ascend() -> _HashLevel {
assert(!isAtRoot)
return _Level(_shift: _shift &- Self._step)
return _HashLevel(_shift: _shift &- Self._step)
}
}
extension _Level: Equatable {
extension _HashLevel: Equatable {
@inlinable @inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left._shift == right._shift
}
}
extension _Level: Comparable {
extension _HashLevel: Comparable {
@inlinable @inline(__always)
internal static func <(left: Self, right: Self) -> Bool {
left._shift < right._shift
@@ -9,36 +9,36 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
@usableFromInline
@frozen
internal struct Builder {
@usableFromInline typealias Element = _Node.Element
@usableFromInline typealias Element = _HashNode.Element
@usableFromInline
@frozen
internal enum Kind {
case empty
case item(Element, at: _Bucket)
case node(_Node)
case collisionNode(_Node)
case node(_HashNode)
case collisionNode(_HashNode)
}
@usableFromInline
internal var level: _Level
internal var level: _HashLevel
@usableFromInline
internal var kind: Kind
@inlinable
internal init(_ level: _Level, _ kind: Kind) {
internal init(_ level: _HashLevel, _ kind: Kind) {
self.level = level
self.kind = kind
}
}
}
extension _Node.Builder {
extension _HashNode.Builder {
@usableFromInline
internal func dump() {
let head = "Builder(level: \(level.depth), kind: "
@@ -46,7 +46,7 @@ extension _Node.Builder {
case .empty:
print(head + "empty)")
case .item(let item, at: let bucket):
print(head + "item(\(_Node._itemString(for: item)), at: \(bucket))")
print(head + "item(\(_HashNode._itemString(for: item)), at: \(bucket))")
case .node(let node):
print(head + "node)")
node.dump()
@@ -57,22 +57,22 @@ extension _Node.Builder {
}
}
extension _Node.Builder {
extension _HashNode.Builder {
@inlinable @inline(__always)
internal static func empty(_ level: _Level) -> Self {
internal static func empty(_ level: _HashLevel) -> Self {
Self(level, .empty)
}
@inlinable @inline(__always)
internal static func item(
_ level: _Level, _ item: __owned Element, at bucket: _Bucket
_ level: _HashLevel, _ item: __owned Element, at bucket: _Bucket
) -> Self {
Self(level, .item(item, at: bucket))
}
@inlinable @inline(__always)
internal static func node(
_ level: _Level, _ node: __owned _Node
_ level: _HashLevel, _ node: __owned _HashNode
) -> Self {
assert(!node.isCollisionNode)
return Self(level, .node(node))
@@ -80,14 +80,14 @@ extension _Node.Builder {
@inlinable @inline(__always)
internal static func collisionNode(
_ level: _Level, _ node: __owned _Node
_ level: _HashLevel, _ node: __owned _HashNode
) -> Self {
assert(node.isCollisionNode)
return Self(level, .collisionNode(node))
}
}
extension _Node.Builder {
extension _HashNode.Builder {
@inlinable
internal var count: Int {
switch kind {
@@ -109,9 +109,9 @@ extension _Node.Builder {
}
}
extension _Node.Builder {
extension _HashNode.Builder {
@inlinable
internal init(_ level: _Level, _ node: _Node) {
internal init(_ level: _HashLevel, _ node: _HashNode) {
self.level = level
if node.count == 0 {
kind = .empty
@@ -126,7 +126,7 @@ extension _Node.Builder {
}
@inlinable
internal __consuming func finalize(_ level: _Level) -> _Node {
internal __consuming func finalize(_ level: _HashLevel) -> _HashNode {
assert(level.isAtRoot && self.level.isAtRoot)
switch kind {
case .empty:
@@ -141,10 +141,10 @@ extension _Node.Builder {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal mutating func applyReplacement(
_ level: _Level,
_ level: _HashLevel,
_ replacement: Builder
) -> Element? {
assert(level == replacement.level)
@@ -164,10 +164,10 @@ extension _Node {
}
}
extension _Node.Builder {
extension _HashNode.Builder {
@inlinable
internal mutating func addNewCollision(
_ level: _Level, _ newItem: __owned Element, _ hash: _Hash
_ level: _HashLevel, _ newItem: __owned Element, _ hash: _Hash
) {
assert(level == self.level)
switch kind {
@@ -175,7 +175,7 @@ extension _Node.Builder {
kind = .item(newItem, at: hash[level])
case .item(let oldItem, at: let bucket):
assert(hash[level] == bucket)
let node = _Node._collisionNode(hash, oldItem, newItem)
let node = _HashNode._collisionNode(hash, oldItem, newItem)
kind = .collisionNode(node)
case .collisionNode(var node):
kind = .empty
@@ -190,7 +190,7 @@ extension _Node.Builder {
@inlinable
internal mutating func addNewItem(
_ level: _Level, _ newItem: __owned Element, at newBucket: _Bucket
_ level: _HashLevel, _ newItem: __owned Element, at newBucket: _Bucket
) {
assert(level == self.level)
switch kind {
@@ -198,7 +198,7 @@ extension _Node.Builder {
kind = .item(newItem, at: newBucket)
case .item(let oldItem, let oldBucket):
assert(oldBucket != newBucket)
let node = _Node._regularNode(oldItem, oldBucket, newItem, newBucket)
let node = _HashNode._regularNode(oldItem, oldBucket, newItem, newBucket)
kind = .node(node)
case .node(var node):
kind = .empty
@@ -209,7 +209,7 @@ extension _Node.Builder {
// Expansion
assert(!level.isAtBottom)
self.kind = .empty
node = _Node._regularNode(
node = _HashNode._regularNode(
newItem, newBucket, node, node.collisionHash[level])
kind = .node(node)
}
@@ -217,7 +217,7 @@ extension _Node.Builder {
@inlinable
internal mutating func addNewChildNode(
_ level: _Level, _ newChild: __owned _Node, at newBucket: _Bucket
_ level: _HashLevel, _ newChild: __owned _HashNode, at newBucket: _Bucket
) {
assert(level == self.level)
switch self.kind {
@@ -230,20 +230,20 @@ extension _Node.Builder {
self.kind = .node(._regularNode(newChild, newBucket))
}
case let .item(oldItem, oldBucket):
let node = _Node._regularNode(oldItem, oldBucket, newChild, newBucket)
let node = _HashNode._regularNode(oldItem, oldBucket, newChild, newBucket)
self.kind = .node(node)
case .node(var node):
self.kind = .empty
let isUnique = node.isUnique()
node.ensureUnique(
isUnique: isUnique, withFreeSpace: _Node.spaceForNewChild)
isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild)
node.insertChild(newChild, newBucket)
self.kind = .node(node)
case .collisionNode(var node):
// Expansion
self.kind = .empty
assert(!level.isAtBottom)
node = _Node._regularNode(
node = _HashNode._regularNode(
node, node.collisionHash[level], newChild, newBucket)
self.kind = .node(node)
}
@@ -251,7 +251,7 @@ extension _Node.Builder {
@inlinable
internal mutating func addNewChildBranch(
_ level: _Level, _ newChild: __owned Self, at newBucket: _Bucket
_ level: _HashLevel, _ newChild: __owned Self, at newBucket: _Bucket
) {
assert(level == self.level)
assert(newChild.level == self.level.descend())
@@ -267,7 +267,7 @@ extension _Node.Builder {
@inlinable
internal static func childBranch(
_ level: _Level, _ child: Self, at bucket: _Bucket
_ level: _HashLevel, _ child: Self, at bucket: _Bucket
) -> Self {
assert(child.level == level.descend())
switch child.kind {
@@ -285,25 +285,25 @@ extension _Node.Builder {
}
}
extension _Node.Builder {
extension _HashNode.Builder {
@inlinable
internal mutating func copyCollisions(
from source: _Node.UnsafeHandle,
upTo end: _Slot
from source: _HashNode.UnsafeHandle,
upTo end: _HashSlot
) {
assert(isEmpty)
assert(source.isCollisionNode)
assert(end < source.itemsEndSlot)
let h = source.collisionHash
for slot: _Slot in stride(from: .zero, to: end, by: 1) {
for slot: _HashSlot in stride(from: .zero, to: end, by: 1) {
self.addNewCollision(self.level, source[item: slot], h)
}
}
@inlinable
internal mutating func copyItems(
_ level: _Level,
from source: _Node.UnsafeHandle,
_ level: _HashLevel,
from source: _HashNode.UnsafeHandle,
upTo end: _Bucket
) {
assert(level == self.level)
@@ -316,8 +316,8 @@ extension _Node.Builder {
@inlinable
internal mutating func copyItemsAndChildren(
_ level: _Level,
from source: _Node.UnsafeHandle,
_ level: _HashLevel,
from source: _HashNode.UnsafeHandle,
upTo end: _Bucket
) {
assert(level == self.level)
@@ -332,11 +332,11 @@ extension _Node.Builder {
}
}
extension _Node.Builder {
extension _HashNode.Builder {
@inlinable
internal func mapValues<Value2>(
_ transform: (Element) -> Value2
) -> _Node<Key, Value2>.Builder {
) -> _HashNode<Key, Value2>.Builder {
switch kind {
case .empty:
return .empty(level)
@@ -351,9 +351,9 @@ extension _Node.Builder {
}
@inlinable
internal func mapValuesToVoid() -> _Node<Key, Void>.Builder {
internal func mapValuesToVoid() -> _HashNode<Key, Void>.Builder {
if Value.self == Void.self {
return unsafeBitCast(self, to: _Node<Key, Void>.Builder.self)
return unsafeBitCast(self, to: _HashNode<Key, Void>.Builder.self)
}
return mapValues { _ in () }
}
@@ -11,7 +11,7 @@
import _CollectionsUtilities
extension _Node {
extension _HashNode {
@usableFromInline
internal func dump(
iterationOrder: Bool = false,
@@ -32,23 +32,23 @@ extension _Node {
}
}
extension _Node.Storage {
extension _HashNode.Storage {
@usableFromInline
final internal func dump(iterationOrder: Bool = false) {
UnsafeHandle.read(self) { $0.dump(iterationOrder: iterationOrder) }
}
}
extension _Node {
extension _HashNode {
internal static func _itemString(for item: Element) -> String {
let hash = _Hash(item.key).description
return "hash: \(hash), key: \(item.key), value: \(item.value)"
}
}
extension _Node.UnsafeHandle {
internal func _itemString(at slot: _Slot) -> String {
extension _HashNode.UnsafeHandle {
internal func _itemString(at slot: _HashSlot) -> String {
let item = self[item: slot]
return _Node._itemString(for: item)
return _HashNode._itemString(for: item)
}
@usableFromInline
@@ -96,8 +96,8 @@ extension _Node.UnsafeHandle {
print("\(restPrefix)[\(slot)] \(_itemString(at: slot))")
}
} else {
var itemSlot: _Slot = .zero
var childSlot: _Slot = .zero
var itemSlot: _HashSlot = .zero
var childSlot: _HashSlot = .zero
for b in 0 ..< UInt(_Bitmap.capacity) {
let bucket = _Bucket(b)
let bucketStr = "#\(String(b, radix: _Bitmap.capacity, uppercase: true))"
@@ -11,10 +11,10 @@
import _CollectionsUtilities
extension _Node {
extension _HashNode {
@inlinable @inline(__always)
internal static func _emptyNode() -> _Node {
_Node(storage: _emptySingleton, count: 0)
internal static func _emptyNode() -> _HashNode {
_HashNode(storage: _emptySingleton, count: 0)
}
@inlinable
@@ -22,8 +22,8 @@ extension _Node {
_ hash: _Hash,
_ item1: __owned Element,
_ item2: __owned Element
) -> _Node {
let node = _Node.allocateCollision(count: 2, hash) { items in
) -> _HashNode {
let node = _HashNode.allocateCollision(count: 2, hash) { items in
items.initializeElement(at: 1, to: item1)
items.initializeElement(at: 0, to: item2)
}.node
@@ -36,8 +36,8 @@ extension _Node {
_ hash: _Hash,
_ item1: __owned Element,
_ inserter2: (UnsafeMutablePointer<Element>) -> Void
) -> _Node {
let node = _Node.allocateCollision(count: 2, hash) { items in
) -> _HashNode {
let node = _HashNode.allocateCollision(count: 2, hash) { items in
items.initializeElement(at: 1, to: item1)
inserter2(items.baseAddress.unsafelyUnwrapped)
}.node
@@ -49,8 +49,8 @@ extension _Node {
internal static func _regularNode(
_ item: __owned Element,
_ bucket: _Bucket
) -> _Node {
let r = _Node.allocate(
) -> _HashNode {
let r = _HashNode.allocate(
itemMap: _Bitmap(bucket),
childMap: .empty,
count: 1
@@ -68,7 +68,7 @@ extension _Node {
_ bucket1: _Bucket,
_ item2: __owned Element,
_ bucket2: _Bucket
) -> _Node {
) -> _HashNode {
_regularNode(
item1, bucket1,
{ $0.initialize(to: item2) }, bucket2).node
@@ -80,19 +80,19 @@ extension _Node {
_ bucket1: _Bucket,
_ inserter2: (UnsafeMutablePointer<Element>) -> Void,
_ bucket2: _Bucket
) -> (node: _Node, slot1: _Slot, slot2: _Slot) {
) -> (node: _HashNode, slot1: _HashSlot, slot2: _HashSlot) {
assert(bucket1 != bucket2)
let r = _Node.allocate(
let r = _HashNode.allocate(
itemMap: _Bitmap(bucket1, bucket2),
childMap: .empty,
count: 2
) { children, items -> (_Slot, _Slot) in
) { children, items -> (_HashSlot, _HashSlot) in
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)
return (_Slot(i2), _Slot(i1)) // Note: swapped
return (_HashSlot(i2), _HashSlot(i1)) // Note: swapped
}
r.node._invariantCheck()
return (r.node, r.result.0, r.result.1)
@@ -100,10 +100,10 @@ extension _Node {
@inlinable
internal static func _regularNode(
_ child: __owned _Node,
_ child: __owned _HashNode,
_ bucket: _Bucket
) -> _Node {
let r = _Node.allocate(
) -> _HashNode {
let r = _HashNode.allocate(
itemMap: .empty,
childMap: _Bitmap(bucket),
count: child.count
@@ -119,9 +119,9 @@ extension _Node {
internal static func _regularNode(
_ item: __owned Element,
_ itemBucket: _Bucket,
_ child: __owned _Node,
_ child: __owned _HashNode,
_ childBucket: _Bucket
) -> _Node {
) -> _HashNode {
_regularNode(
{ $0.initialize(to: item) }, itemBucket,
child, childBucket)
@@ -131,11 +131,11 @@ extension _Node {
internal static func _regularNode(
_ inserter: (UnsafeMutablePointer<Element>) -> Void,
_ itemBucket: _Bucket,
_ child: __owned _Node,
_ child: __owned _HashNode,
_ childBucket: _Bucket
) -> _Node {
) -> _HashNode {
assert(itemBucket != childBucket)
let r = _Node.allocate(
let r = _HashNode.allocate(
itemMap: _Bitmap(itemBucket),
childMap: _Bitmap(childBucket),
count: child.count &+ 1
@@ -150,13 +150,13 @@ extension _Node {
@inlinable
internal static func _regularNode(
_ child1: __owned _Node,
_ child1: __owned _HashNode,
_ child1Bucket: _Bucket,
_ child2: __owned _Node,
_ child2: __owned _HashNode,
_ child2Bucket: _Bucket
) -> _Node {
) -> _HashNode {
assert(child1Bucket != child2Bucket)
let r = _Node.allocate(
let r = _HashNode.allocate(
itemMap: .empty,
childMap: _Bitmap(child1Bucket, child2Bucket),
count: child1.count &+ child2.count
@@ -170,19 +170,19 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal static func build(
level: _Level,
level: _HashLevel,
item1: __owned Element,
_ hash1: _Hash,
item2 inserter2: (UnsafeMutablePointer<Element>) -> Void,
_ hash2: _Hash
) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) {
) -> (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, _Slot(0), _Slot(1))
return (top, top.unmanaged, _HashSlot(0), _HashSlot(1))
}
let r = _build(
level: level, item1: item1, hash1, item2: inserter2, hash2)
@@ -191,12 +191,12 @@ extension _Node {
@inlinable
internal static func _build(
level: _Level,
level: _HashLevel,
item1: __owned Element,
_ hash1: _Hash,
item2 inserter2: (UnsafeMutablePointer<Element>) -> Void,
_ hash2: _Hash
) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) {
) -> (top: _HashNode, leaf: _UnmanagedHashNode, slot1: _HashSlot, slot2: _HashSlot) {
assert(hash1 != hash2)
let b1 = hash1[level]
let b2 = hash2[level]
@@ -213,12 +213,12 @@ extension _Node {
@inlinable
internal static func build(
level: _Level,
level: _HashLevel,
item1 inserter1: (UnsafeMutablePointer<Element>) -> Void,
_ hash1: _Hash,
child2: __owned _Node,
child2: __owned _HashNode,
_ hash2: _Hash
) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) {
) -> (top: _HashNode, leaf: _UnmanagedHashNode, slot1: _HashSlot, slot2: _HashSlot) {
assert(child2.isCollisionNode)
assert(hash1 != hash2)
let b1 = hash1[level]
@@ -236,12 +236,12 @@ extension _Node {
@inlinable
internal static func build(
level: _Level,
child1: __owned _Node,
level: _HashLevel,
child1: __owned _HashNode,
_ hash1: _Hash,
child2: __owned _Node,
child2: __owned _HashNode,
_ hash2: _Hash
) -> _Node {
) -> _HashNode {
assert(child1.isCollisionNode)
assert(child2.isCollisionNode)
assert(hash1 != hash2)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
extension _StorageHeader {
extension _HashNodeHeader {
#if COLLECTIONS_INTERNAL_CHECKS
@usableFromInline @inline(never)
internal func _invariantCheck() {
@@ -27,7 +27,7 @@ extension _StorageHeader {
#endif
}
extension _Node {
extension _HashNode {
#if COLLECTIONS_INTERNAL_CHECKS
@usableFromInline @inline(never)
internal func _invariantCheck() {
@@ -43,7 +43,7 @@ extension _Node {
assert($0.collisionHash == _Hash($0[item: .zero].key))
} else {
let childBytes = $0.childCount * MemoryLayout<_Node>.stride
let childBytes = $0.childCount * MemoryLayout<_HashNode>.stride
assert(itemBytes + $0.bytesFree + childBytes == $0.byteCapacity)
}
@@ -63,7 +63,7 @@ extension _Node {
#if COLLECTIONS_INTERNAL_CHECKS
@inlinable @inline(never)
internal func _fullInvariantCheck(_ level: _Level, _ path: _Hash) {
internal func _fullInvariantCheck(_ level: _HashLevel, _ path: _Hash) {
_invariantCheck()
read {
precondition(level.isAtRoot || !hasSingletonItem)
@@ -79,8 +79,8 @@ extension _Node {
precondition(_Hash(item.key) == hash)
}
}
var itemSlot: _Slot = .zero
var childSlot: _Slot = .zero
var itemSlot: _HashSlot = .zero
var childSlot: _HashSlot = .zero
for b in 0 ..< UInt(_Bitmap.capacity) {
let bucket = _Bucket(b)
let path = path.appending(bucket, at: level)
@@ -101,7 +101,7 @@ extension _Node {
}
#else
@inlinable @inline(__always)
internal func _fullInvariantCheck(_ level: _Level, _ path: _Hash) {}
internal func _fullInvariantCheck(_ level: _HashLevel, _ path: _Hash) {}
#endif
}
@@ -11,20 +11,20 @@
// MARK: Node-level lookup operations
extension _Node {
extension _HashNode {
@inlinable
internal func find(
_ level: _Level, _ key: Key, _ hash: _Hash
) -> (descend: Bool, slot: _Slot)? {
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (descend: Bool, slot: _HashSlot)? {
read { $0.find(level, key, hash) }
}
}
extension _Node.UnsafeHandle {
extension _HashNode.UnsafeHandle {
@inlinable
internal func find(
_ level: _Level, _ key: Key, _ hash: _Hash
) -> (descend: Bool, slot: _Slot)? {
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (descend: Bool, slot: _HashSlot)? {
guard !isCollisionNode else {
let r = _findInCollision(level, key, hash)
guard r.code == 0 else { return nil }
@@ -45,8 +45,8 @@ extension _Node.UnsafeHandle {
@inlinable @inline(never)
internal func _findInCollision(
_ level: _Level, _ key: Key, _ hash: _Hash
) -> (code: Int, slot: _Slot) {
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (code: Int, slot: _HashSlot) {
assert(isCollisionNode)
if !level.isAtBottom {
if hash != self.collisionHash { return (2, .zero) }
@@ -54,7 +54,7 @@ extension _Node.UnsafeHandle {
// 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, _Slot(itemCount &- 1 &- slot))
return (0, _HashSlot(itemCount &- 1 &- slot))
}
}
@@ -75,7 +75,7 @@ internal enum _FindResult {
///
/// If the current node is a collision node, then the bucket value is
/// set to `_Bucket.invalid`.
case found(_Bucket, _Slot)
case found(_Bucket, _HashSlot)
/// The item we're looking for is not currently inside the subtree rooted at
/// this node.
@@ -85,7 +85,7 @@ internal enum _FindResult {
///
/// When the node is a collision node, the `insertCollision` case is returned
/// instead of this one.
case insert(_Bucket, _Slot)
case insert(_Bucket, _HashSlot)
/// The item we're looking for is not currently inside the subtree rooted at
/// this collision node.
@@ -103,7 +103,7 @@ internal enum _FindResult {
/// it with a new child node.
///
/// (This case is never returned if the current node is a collision node.)
case spawnChild(_Bucket, _Slot)
case spawnChild(_Bucket, _HashSlot)
/// The item we're looking for is not in this subtree.
///
@@ -125,22 +125,22 @@ internal enum _FindResult {
/// bucket & slot.
///
/// (This case is never returned if the current node is a collision node.)
case descend(_Bucket, _Slot)
case descend(_Bucket, _HashSlot)
}
extension _Node {
extension _HashNode {
@inlinable
internal func findForInsertion(
_ level: _Level, _ key: Key, _ hash: _Hash
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> _FindResult {
read { $0.findForInsertion(level, key, hash) }
}
}
extension _Node.UnsafeHandle {
extension _HashNode.UnsafeHandle {
@inlinable
internal func findForInsertion(
_ level: _Level, _ key: Key, _ hash: _Hash
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> _FindResult {
guard !isCollisionNode else {
let r = _findInCollision(level, key, hash)
@@ -172,9 +172,9 @@ extension _Node.UnsafeHandle {
// MARK: Subtree-level lookup operations
extension _Node {
extension _HashNode {
@inlinable
internal func get(_ level: _Level, _ key: Key, _ hash: _Hash) -> Value? {
internal func get(_ level: _HashLevel, _ key: Key, _ hash: _Hash) -> Value? {
var node = unmanaged
var level = level
while true {
@@ -191,10 +191,10 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal func containsKey(
_ level: _Level, _ key: Key, _ hash: _Hash
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> Bool {
var node = unmanaged
var level = level
@@ -208,11 +208,11 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal func lookup(
_ level: _Level, _ key: Key, _ hash: _Hash
) -> (node: _UnmanagedNode, slot: _Slot)? {
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (node: _UnmanagedHashNode, slot: _HashSlot)? {
var node = unmanaged
var level = level
while true {
@@ -229,10 +229,10 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal func position(
forKey key: Key, _ level: _Level, _ hash: _Hash
forKey key: Key, _ level: _HashLevel, _ hash: _Hash
) -> Int? {
guard let r = find(level, key, hash) else { return nil }
guard r.descend else { return r.slot.value }
@@ -253,7 +253,7 @@ extension _Node {
var itemsToSkip = position
let itemCount = $0.itemCount
if itemsToSkip < itemCount {
return $0[item: _Slot(itemsToSkip)]
return $0[item: _HashSlot(itemsToSkip)]
}
itemsToSkip -= itemCount
let children = $0.children
@@ -11,7 +11,7 @@
// MARK: Node-level insertion operations
extension _Node.UnsafeHandle {
extension _HashNode.UnsafeHandle {
/// Make room for a new item at `slot` corresponding to `bucket`.
/// There must be enough free space in the node to fit the new item.
///
@@ -23,7 +23,7 @@ extension _Node.UnsafeHandle {
/// initialize this memory.
@inlinable
internal func _makeRoomForNewItem(
at slot: _Slot, _ bucket: _Bucket
at slot: _HashSlot, _ bucket: _Bucket
) -> UnsafeMutablePointer<Element> {
assertMutable()
let c = itemCount
@@ -59,25 +59,25 @@ extension _Node.UnsafeHandle {
/// `childMap` must not yet reflect the insertion at the time this
/// function is called. This method does not update `childMap`.
@inlinable
internal func _insertChild(_ child: __owned _Node, at slot: _Slot) {
internal func _insertChild(_ child: __owned _HashNode, at slot: _HashSlot) {
assertMutable()
assert(!isCollisionNode)
let c = childMap.count
assert(slot.value <= c)
let stride = MemoryLayout<_Node>.stride
let stride = MemoryLayout<_HashNode>.stride
assert(bytesFree >= stride)
bytesFree &-= stride
_memory.bindMemory(to: _Node.self, capacity: c &+ 1)
_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)
}
}
extension _Node {
extension _HashNode {
@inlinable @inline(__always)
internal mutating func insertItem(
_ item: __owned Element, at bucket: _Bucket
@@ -88,7 +88,7 @@ extension _Node {
@inlinable @inline(__always)
internal mutating func insertItem(
_ item: __owned Element, at slot: _Slot, _ bucket: _Bucket
_ item: __owned Element, at slot: _HashSlot, _ bucket: _Bucket
) {
self.count &+= 1
update {
@@ -101,7 +101,7 @@ extension _Node {
/// node to fit the new child.
@inlinable
internal mutating func insertChild(
_ child: __owned _Node, _ bucket: _Bucket
_ child: __owned _HashNode, _ bucket: _Bucket
) {
count &+= child.count
update {
@@ -11,7 +11,7 @@
// MARK: Node-level removal operations
extension _Node.UnsafeHandle {
extension _HashNode.UnsafeHandle {
/// Remove and return the item at `slot`, increasing the amount of free
/// space available in the node.
///
@@ -19,7 +19,7 @@ extension _Node.UnsafeHandle {
/// function is called. This method does not update `itemMap`.
@inlinable
internal func _removeItem<R>(
at slot: _Slot,
at slot: _HashSlot,
by remover: (UnsafeMutablePointer<Element>) -> R
) -> R {
assertMutable()
@@ -46,13 +46,13 @@ extension _Node.UnsafeHandle {
/// `childMap` must not yet reflect the removal at the time this
/// function is called. This method does not update `childMap`.
@inlinable
internal func _removeChild(at slot: _Slot) -> _Node {
internal func _removeChild(at slot: _HashSlot) -> _HashNode {
assertMutable()
assert(!isCollisionNode)
let count = childCount
assert(slot.value < count)
bytesFree &+= MemoryLayout<_Node>.stride
bytesFree &+= MemoryLayout<_HashNode>.stride
let q = _childrenStart + slot.value
let child = q.move()
@@ -61,7 +61,7 @@ extension _Node.UnsafeHandle {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal mutating func removeItem(
at bucket: _Bucket
@@ -72,7 +72,7 @@ extension _Node {
@inlinable
internal mutating func removeItem(
at bucket: _Bucket, _ slot: _Slot
at bucket: _Bucket, _ slot: _HashSlot
) -> Element {
removeItem(at: bucket, slot, by: { $0.move() })
}
@@ -84,7 +84,7 @@ extension _Node {
/// storage slot corresponding to the item to be removed.
@inlinable
internal mutating func removeItem<R>(
at bucket: _Bucket, _ slot: _Slot,
at bucket: _Bucket, _ slot: _HashSlot,
by remover: (UnsafeMutablePointer<Element>) -> R
) -> R {
defer { _invariantCheck() }
@@ -106,10 +106,10 @@ extension _Node {
@inlinable
internal mutating func removeChild(
at bucket: _Bucket, _ slot: _Slot
) -> _Node {
at bucket: _Bucket, _ slot: _HashSlot
) -> _HashNode {
assert(!isCollisionNode)
let child: _Node = update {
let child: _HashNode = update {
assert($0.childMap.contains(bucket))
assert($0.childMap.slot(of: bucket) == slot)
let child = $0._removeChild(at: slot)
@@ -135,9 +135,9 @@ extension _Node {
}
@inlinable
internal mutating func removeSingletonChild() -> _Node {
internal mutating func removeSingletonChild() -> _HashNode {
defer { _invariantCheck() }
let child: _Node = update {
let child: _HashNode = update {
assert($0.hasSingletonChild)
let child = $0._removeChild(at: .zero)
$0.childMap = .empty
@@ -9,10 +9,10 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
@inlinable
internal mutating func replaceItem(
at bucket: _Bucket, _ slot: _Slot, with item: __owned Element
at bucket: _Bucket, _ slot: _HashSlot, with item: __owned Element
) {
update {
assert($0.isCollisionNode || $0.itemMap.contains(bucket))
@@ -24,7 +24,7 @@ extension _Node {
@inlinable
internal mutating func replaceChild(
at bucket: _Bucket, with child: __owned _Node
at bucket: _Bucket, with child: __owned _HashNode
) -> Int {
let slot = read { $0.childMap.slot(of: bucket) }
return replaceChild(at: bucket, slot, with: child)
@@ -32,7 +32,7 @@ extension _Node {
@inlinable
internal mutating func replaceChild(
at bucket: _Bucket, _ slot: _Slot, with child: __owned _Node
at bucket: _Bucket, _ slot: _HashSlot, with child: __owned _HashNode
) -> Int {
let delta: Int = update {
assert(!$0.isCollisionNode)
@@ -49,9 +49,9 @@ extension _Node {
@inlinable
internal func replacingChild(
_ level: _Level,
_ level: _HashLevel,
at bucket: _Bucket,
_ slot: _Slot,
_ slot: _HashSlot,
with child: __owned Builder
) -> Builder {
assert(child.level == level.descend())
@@ -67,7 +67,7 @@ extension _Node {
if hasSingletonChild {
return .item(level, item, at: bucket)
}
var node = self.copy(withFreeSpace: _Node.spaceForInlinedChild)
var node = self.copy(withFreeSpace: _HashNode.spaceForInlinedChild)
_ = node.removeChild(at: bucket, slot)
node.insertItem(item, at: bucket)
node._invariantCheck()
@@ -14,30 +14,30 @@ import _CollectionsUtilities
/// A base representation of a hash tree node, capturing functionality
/// independent of the `Key` and `Value` types.
@usableFromInline
internal typealias _RawStorage = ManagedBuffer<_StorageHeader, _RawNode>
internal typealias _RawHashStorage = ManagedBuffer<_HashNodeHeader, _RawHashNode>
/// Type-punned storage for the singleton root node used in empty hash trees
/// (of all `Key` and `Value` types).
///
/// `_Node` is carefully defined to use a `_RawStorage` reference as its
/// `_HashNode` is carefully defined to use a `_RawHashStorage` reference as its
/// storage variable, so that this can work. (The only reason we need the
/// `_Node.Storage` subclass is to allow storage instances to properly clean up
/// after themselves in their `deinit` method.)
/// `_HashNode.Storage` subclass is to allow storage instances to properly
/// clean up after themselves in their `deinit` method.)
@usableFromInline
internal let _emptySingleton: _RawStorage = _RawStorage.create(
internal let _emptySingleton: _RawHashStorage = _RawHashStorage.create(
minimumCapacity: 0,
makingHeaderWith: { _ in _StorageHeader(byteCapacity: 0) })
makingHeaderWith: { _ in _HashNodeHeader(byteCapacity: 0) })
extension _Node {
extension _HashNode {
/// Instances of this class hold (tail-allocated) storage for individual
/// nodes in a hash tree.
@usableFromInline
internal final class Storage: _RawStorage {
internal final class Storage: _RawHashStorage {
@usableFromInline
internal typealias Element = (key: Key, value: Value)
@usableFromInline
internal typealias UnsafeHandle = _Node<Key, Value>.UnsafeHandle
internal typealias UnsafeHandle = _HashNode<Key, Value>.UnsafeHandle
deinit {
UnsafeHandle.update(self) { handle in
@@ -48,13 +48,13 @@ extension _Node {
}
}
extension _Node.Storage {
extension _HashNode.Storage {
@inlinable
internal static func allocate(byteCapacity: Int) -> _Node.Storage {
internal static func allocate(byteCapacity: Int) -> _HashNode.Storage {
assert(byteCapacity >= 0)
let itemStride = MemoryLayout<Element>.stride
let childStride = MemoryLayout<_Node>.stride
let childStride = MemoryLayout<_HashNode>.stride
let unit = Swift.max(itemStride, childStride)
// Round up request to nearest power-of-two number of units.
@@ -69,16 +69,16 @@ extension _Node.Storage {
var bytes = unit * capacityInUnits._roundUpToPowerOfTwo()
let itemAlignment = MemoryLayout<Element>.alignment
let childAlignment = MemoryLayout<_Node>.alignment
let childAlignment = MemoryLayout<_HashNode>.alignment
if itemAlignment > childAlignment {
// Make sure we always have enough room to properly align trailing items.
bytes += itemAlignment - childAlignment
}
let object = _Node.Storage.create(
let object = _HashNode.Storage.create(
minimumCapacity: (bytes &+ childStride &- 1) / childStride
) { buffer in
_StorageHeader(byteCapacity: buffer.capacity * childStride)
_HashNodeHeader(byteCapacity: buffer.capacity * childStride)
}
object.withUnsafeMutablePointers { header, elements in
@@ -90,11 +90,11 @@ extension _Node.Storage {
header.pointee._bytesFree = header.pointee._byteCapacity
assert(byteCapacity <= header.pointee.byteCapacity)
}
return unsafeDowncast(object, to: _Node.Storage.self)
return unsafeDowncast(object, to: _HashNode.Storage.self)
}
}
extension _Node {
extension _HashNode {
@inlinable @inline(__always)
internal static var spaceForNewItem: Int {
MemoryLayout<Element>.stride
@@ -102,7 +102,7 @@ extension _Node {
@inlinable @inline(__always)
internal static var spaceForNewChild: Int {
MemoryLayout<_Node>.stride
MemoryLayout<_HashNode>.stride
}
@inlinable @inline(__always)
@@ -151,23 +151,23 @@ extension _Node {
count: Int,
extraBytes: Int = 0,
initializingWith initializer: (
UnsafeMutableBufferPointer<_Node>, UnsafeMutableBufferPointer<Element>
UnsafeMutableBufferPointer<_HashNode>, UnsafeMutableBufferPointer<Element>
) -> R
) -> (node: _Node, result: R) {
) -> (node: _HashNode, result: R) {
assert(extraBytes >= 0)
assert(itemMap.isDisjoint(with: childMap)) // No collisions
let itemCount = itemMap.count
let childCount = childMap.count
let itemStride = MemoryLayout<Element>.stride
let childStride = MemoryLayout<_Node>.stride
let childStride = MemoryLayout<_HashNode>.stride
let itemBytes = itemCount * itemStride
let childBytes = childCount * childStride
let occupiedBytes = itemBytes &+ childBytes
let storage = Storage.allocate(
byteCapacity: occupiedBytes &+ extraBytes)
var node = _Node(storage: storage, count: count)
var node = _HashNode(storage: storage, count: count)
let result: R = node.update {
$0.itemMap = itemMap
$0.childMap = childMap
@@ -176,7 +176,7 @@ extension _Node {
$0.bytesFree &-= occupiedBytes
let childStart = $0._memory
.bindMemory(to: _Node.self, capacity: childCount)
.bindMemory(to: _HashNode.self, capacity: childCount)
let itemStart = ($0._memory + ($0.byteCapacity - itemBytes))
.bindMemory(to: Element.self, capacity: itemCount)
@@ -193,15 +193,15 @@ extension _Node {
_ hash: _Hash,
extraBytes: Int = 0,
initializingWith initializer: (UnsafeMutableBufferPointer<Element>) -> R
) -> (node: _Node, result: R) {
) -> (node: _HashNode, result: R) {
assert(count >= 2)
assert(extraBytes >= 0)
let itemBytes = count * MemoryLayout<Element>.stride
let hashBytes = MemoryLayout<_Hash>.stride
let bytes = itemBytes &+ hashBytes
assert(MemoryLayout<_Hash>.alignment <= MemoryLayout<_RawNode>.alignment)
assert(MemoryLayout<_Hash>.alignment <= MemoryLayout<_RawHashNode>.alignment)
let storage = Storage.allocate(byteCapacity: bytes &+ extraBytes)
var node = _Node(storage: storage, count: count)
var node = _HashNode(storage: storage, count: count)
let result: R = node.update {
$0.itemMap = _Bitmap(bitPattern: count)
$0.childMap = $0.itemMap
@@ -221,7 +221,7 @@ extension _Node {
@inlinable @inline(never)
internal func copy(withFreeSpace space: Int = 0) -> _Node {
internal func copy(withFreeSpace space: Int = 0) -> _HashNode {
assert(space >= 0)
if isCollisionNode {
@@ -9,14 +9,14 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
@inlinable
internal func compactMapValues<T>(
_ level: _Level,
_ level: _HashLevel,
_ transform: (Value) throws -> T?
) rethrows -> _Node<Key, T>.Builder {
) rethrows -> _HashNode<Key, T>.Builder {
return try self.read {
var result: _Node<Key, T>.Builder = .empty(level)
var result: _HashNode<Key, T>.Builder = .empty(level)
if isCollisionNode {
let items = $0.reverseItems
@@ -9,10 +9,10 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
@inlinable
internal func filter(
_ level: _Level,
_ level: _HashLevel,
_ isIncluded: (Element) throws -> Bool
) rethrows -> Builder? {
guard !isCollisionNode else {
@@ -57,14 +57,14 @@ extension _Node {
@inlinable @inline(never)
internal func _filter_slow(
_ level: _Level,
_ level: _HashLevel,
_ isIncluded: (Element) throws -> Bool
) rethrows -> Builder? {
try self.read {
var result: Builder = .empty(level)
var removing = false
for slot: _Slot in stride(from: .zero, to: $0.itemsEndSlot, by: 1) {
for slot: _HashSlot in stride(from: .zero, to: $0.itemsEndSlot, by: 1) {
let p = $0.itemPtr(at: slot)
let include = try isIncluded(p.pointee)
if include, removing {
@@ -9,12 +9,12 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
@inlinable
internal func intersection<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> _Node? {
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> _HashNode? {
assert(level.isAtRoot)
let builder = _intersection(level, other)
guard let builder = builder else { return nil }
@@ -25,8 +25,8 @@ extension _Node {
@inlinable
internal func _intersection<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> Builder? {
if self.raw.storage === other.raw.storage { return nil }
@@ -106,8 +106,8 @@ extension _Node {
@inlinable @inline(never)
internal func _intersection_slow<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> Builder? {
let lc = self.isCollisionNode
let rc = other.isCollisionNode
@@ -119,7 +119,7 @@ extension _Node {
var removing = false
let ritems = r.reverseItems
for lslot: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) {
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 }
if include, removing {
@@ -9,13 +9,13 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
/// Returns true if `self` contains a disjoint set of keys than `other`.
/// Otherwise, returns false.
@inlinable @inline(never)
internal func isDisjoint<Value2>(
_ level: _Level,
with other: _Node<Key, Value2>
_ level: _HashLevel,
with other: _HashNode<Key, Value2>
) -> Bool {
if self.count == 0 || other.count == 0 { return true }
if self.raw.storage === other.raw.storage { return false }
@@ -72,8 +72,8 @@ extension _Node {
@inlinable @inline(never)
internal func _isDisjointCollision<Value2>(
_ level: _Level,
with other: _Node<Key, Value2>
_ level: _HashLevel,
with other: _HashNode<Key, Value2>
) -> Bool {
assert(isCollisionNode)
if other.isCollisionNode {
@@ -10,10 +10,10 @@
//===----------------------------------------------------------------------===//
// TODO: `Equatable` needs more test coverage, apart from hash-collision smoke test
extension _Node {
extension _HashNode {
@inlinable
internal func isEqualSet<Value2>(
to other: _Node<Key, Value2>,
to other: _HashNode<Key, Value2>,
by areEquivalent: (Value, Value2) -> Bool
) -> Bool {
if self.raw.storage === other.raw.storage { return true }
@@ -9,13 +9,13 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
/// Returns true if `self` contains a subset of the keys in `other`.
/// Otherwise, returns false.
@inlinable @inline(never)
internal func isSubset<Value2>(
_ level: _Level,
of other: _Node<Key, Value2>
_ level: _HashLevel,
of other: _HashNode<Key, Value2>
) -> Bool {
guard self.count > 0 else { return true }
if self.raw.storage === other.raw.storage { return true }
@@ -11,21 +11,21 @@
import _CollectionsUtilities
extension _Node {
extension _HashNode {
@inlinable
internal func mapValues<T>(
_ transform: (Element) throws -> T
) rethrows -> _Node<Key, T> {
) rethrows -> _HashNode<Key, T> {
let c = self.count
return try read { source in
var result: _Node<Key, T>
var result: _HashNode<Key, T>
if isCollisionNode {
result = _Node<Key, T>.allocateCollision(
result = _HashNode<Key, T>.allocateCollision(
count: c, source.collisionHash,
initializingWith: { _ in }
).node
} else {
result = _Node<Key, T>.allocate(
result = _HashNode<Key, T>.allocate(
itemMap: source.itemMap,
childMap: source.childMap,
count: c,
@@ -75,9 +75,9 @@ extension _Node {
@inlinable
internal func mapValuesToVoid(
copy: Bool = false, extraBytes: Int = 0
) -> _Node<Key, Void> {
) -> _HashNode<Key, Void> {
if Value.self == Void.self {
let node = unsafeBitCast(self, to: _Node<Key, Void>.self)
let node = unsafeBitCast(self, to: _HashNode<Key, Void>.self)
guard copy || !node.hasFreeSpace(extraBytes) else { return node }
return node.copy(withFreeSpace: extraBytes)
}
@@ -9,12 +9,12 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
/// - Returns: The number of new items added to `self`.
@inlinable
internal mutating func merge(
_ level: _Level,
_ other: _Node,
_ level: _HashLevel,
_ other: _HashNode,
_ combine: (Value, Value) throws -> Value
) rethrows -> Int {
guard other.count > 0 else { return 0 }
@@ -52,8 +52,8 @@ extension _Node {
@inlinable
internal mutating func _merge(
_ level: _Level,
_ other: _Node,
_ level: _HashLevel,
_ other: _HashNode,
_ combine: (Value, Value) throws -> Value
) rethrows -> Int {
// Note: don't check storage identities -- we do need to merge the contents
@@ -105,7 +105,7 @@ extension _Node {
let rp = r.childPtr(at: rslot)
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _Node.spaceForSpawningChild)
isUnique: isUnique, withFreeSpace: _HashNode.spaceForSpawningChild)
let item = self.removeItem(at: bucket)
delta &-= 1
var child = rp.pointee
@@ -182,7 +182,7 @@ extension _Node {
for (bucket, _) in r.childMap.subtracting(seen) {
let rslot = r.childMap.slot(of: bucket)
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _Node.spaceForNewChild)
isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild)
self.insertChild(r[child: rslot], bucket)
delta &+= r[child: rslot].count
isUnique = true
@@ -195,15 +195,15 @@ extension _Node {
@inlinable @inline(never)
internal mutating func _merge_slow(
_ level: _Level,
_ other: _Node,
_ level: _HashLevel,
_ other: _HashNode,
_ combine: (Value, Value) throws -> Value
) rethrows -> Int {
let lc = self.isCollisionNode
let rc = other.isCollisionNode
if lc && rc {
guard self.collisionHash == other.collisionHash else {
self = _Node.build(
self = _HashNode.build(
level: level,
child1: self, self.collisionHash,
child2: other, other.collisionHash)
@@ -213,14 +213,14 @@ extension _Node {
var isUnique = self.isUnique()
var delta = 0
let originalItemCount = self.count
for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) {
for rs: _HashSlot in stride(from: .zero, to: r.itemsEndSlot, by: 1) {
let rp = r.itemPtr(at: rs)
let lslot: _Slot? = self.read { l in
let lslot: _HashSlot? = self.read { l in
let litems = l.reverseItems
return litems
.suffix(originalItemCount)
.firstIndex { $0.key == rp.pointee.key }
.map { _Slot(litems.count &- 1 &- $0) }
.map { _HashSlot(litems.count &- 1 &- $0) }
}
if let lslot = lslot {
self.ensureUnique(isUnique: isUnique)
@@ -278,7 +278,7 @@ extension _Node {
return self.count - originalCount
}
var node = other.copy(withFreeSpace: _Node.spaceForNewChild)
var node = other.copy(withFreeSpace: _HashNode.spaceForNewChild)
node.insertChild(self, bucket)
self = node
return other.count
@@ -292,7 +292,7 @@ extension _Node {
let bucket = r.collisionHash[level]
if self.read({ $0.itemMap.contains(bucket) }) {
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _Node.spaceForSpawningChild)
isUnique: isUnique, withFreeSpace: _HashNode.spaceForSpawningChild)
let item = self.removeItem(at: bucket)
let h = _Hash(item.key)
var copy = other
@@ -321,7 +321,7 @@ extension _Node {
return delta
}
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _Node.spaceForNewChild)
isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild)
self.insertChild(other, bucket)
return other.count
}
@@ -9,12 +9,12 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
@inlinable
internal func subtracting<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> _Node? {
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> _HashNode? {
assert(level.isAtRoot)
let builder = _subtracting(level, other)
guard let builder = builder else { return nil }
@@ -25,8 +25,8 @@ extension _Node {
@inlinable
internal func _subtracting<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> Builder? {
if self.raw.storage === other.raw.storage { return .empty(level) }
@@ -109,8 +109,8 @@ extension _Node {
@inlinable @inline(never)
internal func _subtracting_slow<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> Builder? {
let lc = self.isCollisionNode
let rc = other.isCollisionNode
@@ -124,7 +124,7 @@ extension _Node {
var removing = false
let ritems = r.reverseItems
for lslot: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) {
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 }
if include, removing {
@@ -9,12 +9,12 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
@inlinable
internal func symmetricDifference<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> _Node<Key, Void>.Builder? {
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> _HashNode<Key, Void>.Builder? {
guard self.count > 0 else {
return .init(level, other.mapValuesToVoid())
}
@@ -24,10 +24,10 @@ extension _Node {
@inlinable
internal func _symmetricDifference<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> _Node<Key, Void>.Builder {
typealias VoidNode = _Node<Key, Void>
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> _HashNode<Key, Void>.Builder {
typealias VoidNode = _HashNode<Key, Void>
assert(self.count > 0 && other.count > 0)
@@ -130,9 +130,9 @@ extension _Node {
@inlinable @inline(never)
internal func _symmetricDifference_slow<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> _Node<Key, Void>.Builder {
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> _HashNode<Key, Void>.Builder {
switch (self.isCollisionNode, other.isCollisionNode) {
case (true, true):
return self._symmetricDifference_slow_both(level, other)
@@ -145,10 +145,10 @@ extension _Node {
@inlinable
internal func _symmetricDifference_slow_both<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> _Node<Key, Void>.Builder {
typealias VoidNode = _Node<Key, Void>
_ level: _HashLevel,
_ 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 {
@@ -160,7 +160,7 @@ extension _Node {
}
var result: VoidNode.Builder = .empty(level)
let ritems = r.reverseItems
for ls: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) {
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 })
if include {
@@ -170,7 +170,7 @@ extension _Node {
// FIXME: Consider remembering slots of shared items in r by
// caching them in a bitset.
let litems = l.reverseItems
for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) {
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 })
if include {
@@ -184,10 +184,10 @@ extension _Node {
@inlinable
internal func _symmetricDifference_slow_left<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> _Node<Key, Void>.Builder {
typealias VoidNode = _Node<Key, Void>
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> _HashNode<Key, Void>.Builder {
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
@@ -218,7 +218,7 @@ extension _Node {
with: (litems[1 &- li].key, ()))
return .node(level, node)
}
let lslot = _Slot(litems.count &- 1 &- li)
let lslot = _HashSlot(litems.count &- 1 &- li)
var child = self.mapValuesToVoid(copy: true)
_ = child.removeItem(at: .invalid, lslot)
if other.hasSingletonItem {
@@ -9,12 +9,12 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
@inlinable
internal func union<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> (copied: Bool, node: _Node<Key, Void>) {
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> (copied: Bool, node: _HashNode<Key, Void>) {
guard self.count > 0 else { return (true, other.mapValuesToVoid()) }
guard other.count > 0 else { return (false, self.mapValuesToVoid()) }
if level.isAtRoot, self.hasSingletonItem {
@@ -42,9 +42,9 @@ extension _Node {
@inlinable
internal func _union<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> (copied: Bool, node: _Node<Key, Void>) {
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> (copied: Bool, node: _HashNode<Key, Void>) {
if self.raw.storage === other.raw.storage {
return (false, self.mapValuesToVoid())
}
@@ -88,7 +88,7 @@ extension _Node {
let rp = r.childPtr(at: rslot)
node.ensureUnique(
isUnique: copied, withFreeSpace: _Node.spaceForSpawningChild)
isUnique: copied, withFreeSpace: _HashNode.spaceForSpawningChild)
let item = node.removeItem(at: bucket)
let r = rp.pointee.mapValuesToVoid()
.inserting(level.descend(), (item.key, ()), _Hash(item.key))
@@ -142,7 +142,7 @@ extension _Node {
for (bucket, _) in r.childMap.subtracting(seen) {
let rslot = r.childMap.slot(of: bucket)
node.ensureUnique(
isUnique: copied, withFreeSpace: _Node.spaceForNewChild)
isUnique: copied, withFreeSpace: _HashNode.spaceForNewChild)
copied = true
node.insertChild(r[child: rslot].mapValuesToVoid(), bucket)
}
@@ -154,16 +154,16 @@ extension _Node {
@inlinable @inline(never)
internal func _union_slow<Value2>(
_ level: _Level,
_ other: _Node<Key, Value2>
) -> (copied: Bool, node: _Node<Key, Void>) {
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> (copied: Bool, node: _HashNode<Key, Void>) {
let lc = self.isCollisionNode
let rc = other.isCollisionNode
if lc && rc {
return read { l in
other.read { r in
guard l.collisionHash == r.collisionHash else {
let node = _Node<Key, Void>.build(
let node = _HashNode<Key, Void>.build(
level: level,
child1: self.mapValuesToVoid(), l.collisionHash,
child2: other.mapValuesToVoid(), r.collisionHash)
@@ -172,7 +172,7 @@ extension _Node {
var copied = false
var node = self.mapValuesToVoid()
let litems = l.reverseItems
for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) {
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(
@@ -218,7 +218,7 @@ extension _Node {
}
var node = other.mapValuesToVoid(
copy: true, extraBytes: _Node<Key, Void>.spaceForNewChild)
copy: true, extraBytes: _HashNode<Key, Void>.spaceForNewChild)
node.insertChild(self.mapValuesToVoid(), bucket)
return (true, node)
}
@@ -227,8 +227,8 @@ extension _Node {
assert(rc)
// `other` is a collision node on a compressed path.
return read { l -> (copied: Bool, node: _Node<Key, Void>) in
other.read { r -> (copied: Bool, node: _Node<Key, Void>) in
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)
@@ -248,7 +248,7 @@ extension _Node {
}
var node = self.mapValuesToVoid(
copy: true, extraBytes: _Node.spaceForNewChild)
copy: true, extraBytes: _HashNode.spaceForNewChild)
node.insertChild(other.mapValuesToVoid(), bucket)
return (true, node)
}
@@ -11,23 +11,23 @@
import _CollectionsUtilities
extension _Node {
extension _HashNode {
@inlinable
internal mutating func insert(
_ level: _Level,
_ level: _HashLevel,
_ item: Element,
_ hash: _Hash
) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) {
) -> (inserted: Bool, leaf: _UnmanagedHashNode, slot: _HashSlot) {
insert(level, item.key, hash) { $0.initialize(to: item) }
}
@inlinable
internal mutating func insert(
_ level: _Level,
_ level: _HashLevel,
_ key: Key,
_ hash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) {
) -> (inserted: Bool, leaf: _UnmanagedHashNode, slot: _HashSlot) {
defer { _invariantCheck() }
let isUnique = self.isUnique()
if !isUnique {
@@ -56,7 +56,7 @@ extension _Node {
inserter)
return (true, r.leaf, r.slot)
case .expansion:
let r = _Node.build(
let r = _HashNode.build(
level: level,
item1: inserter, hash,
child2: self, self.collisionHash)
@@ -73,20 +73,24 @@ extension _Node {
@inlinable
internal func inserting(
_ level: _Level,
_ level: _HashLevel,
_ item: __owned Element,
_ hash: _Hash
) -> (inserted: Bool, node: _Node, leaf: _UnmanagedNode, slot: _Slot) {
) -> (
inserted: Bool, node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot
) {
inserting(level, item.key, hash, { $0.initialize(to: item) })
}
@inlinable
internal func inserting(
_ level: _Level,
_ level: _HashLevel,
_ key: Key,
_ hash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (inserted: Bool, node: _Node, leaf: _UnmanagedNode, slot: _Slot) {
) -> (
inserted: Bool, node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot
) {
defer { _invariantCheck() }
let r = findForInsertion(level, key, hash)
switch r {
@@ -109,7 +113,7 @@ extension _Node {
inserter)
return (true, r.node, r.leaf, r.slot)
case .expansion:
let r = _Node.build(
let r = _HashNode.build(
level: level,
item1: inserter, hash,
child2: self, self.collisionHash)
@@ -130,11 +134,11 @@ extension _Node {
@inlinable
internal mutating func updateValue(
_ level: _Level,
_ level: _HashLevel,
forKey key: Key,
_ hash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) {
) -> (inserted: Bool, leaf: _UnmanagedHashNode, slot: _HashSlot) {
defer { _invariantCheck() }
let isUnique = self.isUnique()
let r = findForInsertion(level, key, hash)
@@ -159,7 +163,7 @@ extension _Node {
inserter)
return (true, r.leaf, r.slot)
case .expansion:
let r = _Node.build(
let r = _HashNode.build(
level: level,
item1: inserter, hash,
child2: self, self.collisionHash)
@@ -177,7 +181,7 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal mutating func ensureUniqueAndInsertItem(
isUnique: Bool,
@@ -198,7 +202,7 @@ extension _Node {
internal mutating func ensureUniqueAndInsertItem(
isUnique: Bool,
at bucket: _Bucket,
itemSlot slot: _Slot,
itemSlot slot: _HashSlot,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) {
assert(!isCollisionNode)
@@ -222,9 +226,9 @@ extension _Node {
@inlinable @inline(never)
internal func copyNodeAndInsertItem(
at bucket: _Bucket,
itemSlot slot: _Slot,
itemSlot slot: _HashSlot,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> _Node {
) -> _HashNode {
assert(!isCollisionNode)
let c = self.count
return read { src in
@@ -253,7 +257,7 @@ extension _Node {
@inlinable @inline(never)
internal mutating func resizeNodeAndInsertItem(
at bucket: _Bucket,
itemSlot slot: _Slot,
itemSlot slot: _HashSlot,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) {
assert(!isCollisionNode)
@@ -284,12 +288,12 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal mutating func ensureUniqueAndAppendCollision(
isUnique: Bool,
_ item: Element
) -> _Slot {
) -> _HashSlot {
ensureUniqueAndAppendCollision(isUnique: isUnique) {
$0.initialize(to: item)
}
@@ -299,7 +303,7 @@ extension _Node {
internal mutating func ensureUniqueAndAppendCollision(
isUnique: Bool,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> _Slot {
) -> _HashSlot {
assert(isCollisionNode)
if !isUnique {
let r = copyNodeAndAppendCollision(inserter)
@@ -315,13 +319,13 @@ extension _Node {
inserter(p)
}
self.count &+= 1
return _Slot(self.count &- 1)
return _HashSlot(self.count &- 1)
}
@inlinable @inline(never)
internal func copyNodeAndAppendCollision(
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (node: _Node, slot: _Slot) {
) -> (node: _HashNode, slot: _HashSlot) {
assert(isCollisionNode)
assert(self.count == read { $0.collisionCount })
let c = self.count
@@ -333,13 +337,13 @@ extension _Node {
inserter(dstItems.baseAddress!)
}.node
}
return (node, _Slot(c))
return (node, _HashSlot(c))
}
@inlinable @inline(never)
internal mutating func resizeNodeAndAppendCollision(
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> _Slot {
) -> _HashSlot {
assert(isCollisionNode)
assert(self.count == read { $0.collisionCount })
let c = self.count
@@ -353,18 +357,18 @@ extension _Node {
src.clear()
}.node
}
return _Slot(c)
return _HashSlot(c)
}
}
extension _Node {
extension _HashNode {
@inlinable
internal func _copyNodeAndReplaceItemWithNewChild(
level: _Level,
_ newChild: __owned _Node,
level: _HashLevel,
_ newChild: __owned _HashNode,
at bucket: _Bucket,
itemSlot: _Slot
) -> _Node {
itemSlot: _HashSlot
) -> _HashNode {
let c = self.count
return read { src in
assert(!src.isCollisionNode)
@@ -409,13 +413,13 @@ extension _Node {
/// this function is called.
@inlinable
internal mutating func _resizeNodeAndReplaceItemWithNewChild(
level: _Level,
_ newChild: __owned _Node,
level: _HashLevel,
_ newChild: __owned _HashNode,
at bucket: _Bucket,
itemSlot: _Slot
itemSlot: _HashSlot
) {
let c = self.count
let node: _Node = update { src in
let node: _HashNode = update { src in
assert(!src.isCollisionNode)
assert(src.itemMap.contains(bucket))
assert(!src.childMap.contains(bucket))
@@ -453,14 +457,14 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable @inline(never)
internal func copyNodeAndPushItemIntoNewChild(
level: _Level,
_ newChild: __owned _Node,
level: _HashLevel,
_ newChild: __owned _HashNode,
at bucket: _Bucket,
itemSlot: _Slot
) -> _Node {
itemSlot: _HashSlot
) -> _HashNode {
assert(!isCollisionNode)
let item = read { $0[item: itemSlot] }
let hash = _Hash(item.key)
@@ -473,22 +477,22 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal mutating func ensureUniqueAndSpawnChild(
isUnique: Bool,
level: _Level,
level: _HashLevel,
replacing bucket: _Bucket,
itemSlot: _Slot,
itemSlot: _HashSlot,
newHash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (leaf: _UnmanagedNode, slot: _Slot) {
) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) {
let existingHash = read { _Hash($0[item: itemSlot].key) }
assert(existingHash.isEqual(to: newHash, upTo: level))
if newHash == existingHash, hasSingletonItem {
// Convert current node to a collision node.
self = _Node._collisionNode(newHash, read { $0[item: .zero] }, inserter)
return (unmanaged, _Slot(1))
self = _HashNode._collisionNode(newHash, read { $0[item: .zero] }, inserter)
return (unmanaged, _HashSlot(1))
}
if !isUnique {
@@ -513,7 +517,7 @@ extension _Node {
}
let existing = removeItem(at: bucket, itemSlot)
let r = _Node.build(
let r = _HashNode.build(
level: level.descend(),
item1: existing, existingHash,
item2: inserter, newHash)
@@ -523,15 +527,15 @@ extension _Node {
@inlinable @inline(never)
internal func copyNodeAndSpawnChild(
level: _Level,
level: _HashLevel,
replacing bucket: _Bucket,
itemSlot: _Slot,
itemSlot: _HashSlot,
existingHash: _Hash,
newHash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (node: _Node, leaf: _UnmanagedNode, slot: _Slot) {
) -> (node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot) {
let r = read {
_Node.build(
_HashNode.build(
level: level.descend(),
item1: $0[item: itemSlot], existingHash,
item2: inserter, newHash)
@@ -547,15 +551,15 @@ extension _Node {
@inlinable @inline(never)
internal mutating func resizeNodeAndSpawnChild(
level: _Level,
level: _HashLevel,
replacing bucket: _Bucket,
itemSlot: _Slot,
itemSlot: _HashSlot,
existingHash: _Hash,
newHash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (leaf: _UnmanagedNode, slot: _Slot) {
) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) {
let r = update {
_Node.build(
_HashNode.build(
level: level.descend(),
item1: $0.itemPtr(at: itemSlot).move(), existingHash,
item2: inserter, newHash)
@@ -11,11 +11,11 @@
// MARK: Subtree-level in-place mutation operations
extension _Node {
extension _HashNode {
@inlinable
internal mutating func ensureUnique(
level: _Level, at path: _UnsafePath
) -> (leaf: _UnmanagedNode, slot: _Slot) {
level: _HashLevel, at path: _UnsafePath
) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) {
ensureUnique(isUnique: isUnique())
guard level < path.level else { return (unmanaged, path.currentItemSlot) }
return update {
@@ -25,7 +25,7 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@usableFromInline
@frozen
internal struct ValueUpdateState {
@@ -93,7 +93,7 @@ extension _Node {
state.path.selectItem(at: slot)
case .appendCollision:
state.path.selectItem(at: _Slot(self.count))
state.path.selectItem(at: _HashSlot(self.count))
case .spawnChild(_, let slot):
state.path.selectItem(at: slot)
@@ -140,7 +140,7 @@ extension _Node {
@inlinable
internal mutating func _finalizeRemoval(
_ level: _Level, _ hash: _Hash, at path: _UnsafePath
_ level: _HashLevel, _ hash: _Hash, at path: _UnsafePath
) -> Element? {
assert(isUnique())
if level == path.level {
@@ -157,7 +157,7 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@usableFromInline
@frozen
internal struct DefaultedValueUpdateState {
@@ -165,10 +165,10 @@ extension _Node {
internal var item: Element
@usableFromInline
internal var node: _UnmanagedNode
internal var node: _UnmanagedHashNode
@usableFromInline
internal var slot: _Slot
internal var slot: _HashSlot
@usableFromInline
internal var inserted: Bool
@@ -176,8 +176,8 @@ extension _Node {
@inlinable
internal init(
_ item: Element,
in node: _UnmanagedNode,
at slot: _Slot,
in node: _UnmanagedHashNode,
at slot: _HashSlot,
inserted: Bool
) {
self.item = item
@@ -189,7 +189,7 @@ extension _Node {
@inlinable
internal mutating func prepareDefaultedValueUpdate(
_ level: _Level,
_ level: _HashLevel,
_ key: Key,
_ defaultValue: () -> Value,
_ hash: _Hash
@@ -237,7 +237,7 @@ extension _Node {
inserted: true)
case .expansion:
let r = _Node.build(
let r = _HashNode.build(
level: level,
item1: { _ in }, hash,
child2: self, self.collisionHash
@@ -11,7 +11,7 @@
// MARK: Subtree-level removal operations
extension _Node {
extension _HashNode {
/// Remove the item with the specified key from this subtree and return it.
///
/// This function may leave `self` containing a singleton item.
@@ -19,7 +19,7 @@ extension _Node {
/// by inlining the remaining item into the parent node.
@inlinable
internal mutating func remove(
_ level: _Level, _ key: Key, _ hash: _Hash
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (removed: Element, remainder: Element?)? {
guard self.isUnique() else {
guard let r = removing(level, key, hash) else { return nil }
@@ -46,10 +46,10 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal func removing(
_ level: _Level, _ key: Key, _ hash: _Hash
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (removed: Element, replacement: Builder)? {
guard let r = find(level, key, hash) else { return nil }
let bucket = hash[level]
@@ -64,10 +64,10 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal mutating func remove(
_ level: _Level, at path: _UnsafePath
_ level: _HashLevel, at path: _UnsafePath
) -> (removed: Element, remainder: Element?) {
defer { _invariantCheck() }
guard self.isUnique() else {
@@ -94,7 +94,7 @@ extension _Node {
@inlinable
internal func removing(
_ level: _Level, at path: _UnsafePath
_ level: _HashLevel, at path: _UnsafePath
) -> (removed: Element, replacement: Builder) {
if level == path.level {
let slot = path.currentItemSlot
@@ -112,12 +112,12 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal mutating func _removeItemFromUniqueLeafNode<R>(
_ level: _Level,
_ level: _HashLevel,
at bucket: _Bucket,
_ slot: _Slot,
_ slot: _HashSlot,
by remover: (UnsafeMutablePointer<Element>) -> R
) -> (result: R, remainder: Element?) {
assert(isUnique())
@@ -140,7 +140,7 @@ extension _Node {
@inlinable
internal func _removingItemFromLeaf(
_ level: _Level, at bucket: _Bucket, _ slot: _Slot
_ level: _HashLevel, at bucket: _Bucket, _ slot: _HashSlot
) -> (removed: Element, replacement: Builder) {
read {
if $0.isCollisionNode {
@@ -148,7 +148,7 @@ extension _Node {
if $0.collisionCount == 2 {
// Node will evaporate
let remainder = _Slot(1 &- slot.value)
let remainder = _HashSlot(1 &- slot.value)
let bucket = $0.collisionHash[level]
return (
removed: $0[item: slot],
@@ -178,7 +178,7 @@ extension _Node {
if $0.itemMap.count == 2 && $0.childMap.isEmpty {
// Evaporating node
let remainder = _Slot(1 &- slot.value)
let remainder = _HashSlot(1 &- slot.value)
var map = $0.itemMap
if remainder != .zero { _ = map.popFirst() }
@@ -196,21 +196,21 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal func _removingChild(
_ level: _Level, at bucket: _Bucket, _ slot: _Slot
_ level: _HashLevel, at bucket: _Bucket, _ slot: _HashSlot
) -> Builder {
read {
assert(!$0.isCollisionNode && $0.childMap.contains(bucket))
let willAtrophy = (
$0.itemMap.isEmpty
&& $0.childCount == 2
&& $0[child: _Slot(1 &- slot.value)].isCollisionNode
&& $0[child: _HashSlot(1 &- slot.value)].isCollisionNode
)
if willAtrophy {
// Compression
let child = $0[child: _Slot(1 &- slot.value)]
let child = $0[child: _HashSlot(1 &- slot.value)]
return .collisionNode(level, child)
}
if $0.itemMap.hasExactlyOneMember && $0.childMap.hasExactlyOneMember {
@@ -229,12 +229,12 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal mutating func _fixupUniqueAncestorAfterItemRemoval(
_ level: _Level,
_ level: _HashLevel,
at bucket: (UnsafeHandle) -> _Bucket,
_ childSlot: _Slot,
_ childSlot: _HashSlot,
remainder: Element?
) -> Element? {
assert(isUnique())
@@ -261,7 +261,7 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal mutating func _convertToRegularNode() {
assert(isCollisionNode && hasSingletonItem)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
extension _Node {
extension _HashNode {
/// An unsafe view of the data stored inside a node in the hash tree, hiding
/// the mechanics of accessing storage from the code that uses it.
///
@@ -27,7 +27,7 @@ extension _Node {
internal typealias Element = (key: Key, value: Value)
@usableFromInline
internal let _header: UnsafeMutablePointer<_StorageHeader>
internal let _header: UnsafeMutablePointer<_HashNodeHeader>
@usableFromInline
internal let _memory: UnsafeMutableRawPointer
@@ -39,7 +39,7 @@ extension _Node {
@inlinable
internal init(
_ header: UnsafeMutablePointer<_StorageHeader>,
_ header: UnsafeMutablePointer<_HashNodeHeader>,
_ memory: UnsafeMutableRawPointer,
isMutable: Bool
) {
@@ -52,7 +52,7 @@ extension _Node {
}
}
extension _Node.UnsafeHandle {
extension _HashNode.UnsafeHandle {
@inlinable
@inline(__always)
func assertMutable() {
@@ -62,10 +62,10 @@ extension _Node.UnsafeHandle {
}
}
extension _Node.UnsafeHandle {
extension _HashNode.UnsafeHandle {
@inlinable @inline(__always)
static func read<R>(
_ node: _UnmanagedNode,
_ node: _UnmanagedHashNode,
_ body: (Self) throws -> R
) rethrows -> R {
try node.ref._withUnsafeGuaranteedRef { storage in
@@ -77,7 +77,7 @@ extension _Node.UnsafeHandle {
@inlinable @inline(__always)
static func read<R>(
_ storage: _RawStorage,
_ storage: _RawHashStorage,
_ body: (Self) throws -> R
) rethrows -> R {
try storage.withUnsafeMutablePointers { header, elements in
@@ -87,7 +87,7 @@ extension _Node.UnsafeHandle {
@inlinable @inline(__always)
static func update<R>(
_ node: _UnmanagedNode,
_ node: _UnmanagedHashNode,
_ body: (Self) throws -> R
) rethrows -> R {
try node.ref._withUnsafeGuaranteedRef { storage in
@@ -99,7 +99,7 @@ extension _Node.UnsafeHandle {
@inlinable @inline(__always)
static func update<R>(
_ storage: _RawStorage,
_ storage: _RawHashStorage,
_ body: (Self) throws -> R
) rethrows -> R {
try storage.withUnsafeMutablePointers { header, elements in
@@ -108,7 +108,7 @@ extension _Node.UnsafeHandle {
}
}
extension _Node.UnsafeHandle {
extension _HashNode.UnsafeHandle {
@inlinable @inline(__always)
internal var itemMap: _Bitmap {
get {
@@ -173,8 +173,8 @@ extension _Node.UnsafeHandle {
}
@inlinable @inline(__always)
internal var _childrenStart: UnsafeMutablePointer<_Node> {
_memory.assumingMemoryBound(to: _Node.self)
internal var _childrenStart: UnsafeMutablePointer<_HashNode> {
_memory.assumingMemoryBound(to: _HashNode.self)
}
@inlinable @inline(__always)
@@ -188,29 +188,29 @@ extension _Node.UnsafeHandle {
}
@inlinable
internal func childBucket(at slot: _Slot) -> _Bucket {
internal func childBucket(at slot: _HashSlot) -> _Bucket {
guard !isCollisionNode else { return .invalid }
return childMap.bucket(at: slot)
}
@inlinable @inline(__always)
internal var childrenEndSlot: _Slot {
internal var childrenEndSlot: _HashSlot {
_header.pointee.childrenEndSlot
}
@inlinable
internal var children: UnsafeMutableBufferPointer<_Node> {
internal var children: UnsafeMutableBufferPointer<_HashNode> {
UnsafeMutableBufferPointer(start: _childrenStart, count: childCount)
}
@inlinable
internal func childPtr(at slot: _Slot) -> UnsafeMutablePointer<_Node> {
internal func childPtr(at slot: _HashSlot) -> UnsafeMutablePointer<_HashNode> {
assert(slot.value < childCount)
return _childrenStart + slot.value
}
@inlinable
internal subscript(child slot: _Slot) -> _Node {
internal subscript(child slot: _HashSlot) -> _HashNode {
unsafeAddress {
UnsafePointer(childPtr(at: slot))
}
@@ -237,13 +237,13 @@ extension _Node.UnsafeHandle {
}
@inlinable
internal func itemBucket(at slot: _Slot) -> _Bucket {
internal func itemBucket(at slot: _HashSlot) -> _Bucket {
guard !isCollisionNode else { return .invalid }
return itemMap.bucket(at: slot)
}
@inlinable @inline(__always)
internal var itemsEndSlot: _Slot {
internal var itemsEndSlot: _HashSlot {
_header.pointee.itemsEndSlot
}
@@ -254,13 +254,13 @@ extension _Node.UnsafeHandle {
}
@inlinable
internal func itemPtr(at slot: _Slot) -> UnsafeMutablePointer<Element> {
internal func itemPtr(at slot: _HashSlot) -> UnsafeMutablePointer<Element> {
assert(slot.value <= itemCount)
return _itemsEnd.advanced(by: -1 &- slot.value)
}
@inlinable
internal subscript(item slot: _Slot) -> Element {
internal subscript(item slot: _HashSlot) -> Element {
unsafeAddress {
UnsafePointer(itemPtr(at: slot))
}
@@ -277,7 +277,7 @@ extension _Node.UnsafeHandle {
}
}
extension _Node.UnsafeHandle {
extension _HashNode.UnsafeHandle {
@inlinable
internal var hasSingletonItem: Bool {
_header.pointee.hasSingletonItem
@@ -36,31 +36,31 @@
/// items map.
@usableFromInline
@frozen
internal struct _Node<Key: Hashable, Value> {
// Warning: This struct must be kept layout-compatible with _RawNode.
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.
//
// Swift guarantees that frozen structs with a single stored property will
// be layout-compatible with the type they are wrapping.
//
// (_RawNode is used as the Element type of the ManagedBuffer underlying
// node storage, and the memory is then rebound to `_Node` later.
// This will not work correctly unless `_Node` has the exact same alignment
// (_RawHashNode is used as the Element type of the ManagedBuffer underlying
// node storage, and the memory is then rebound to `_HashNode` later.
// This will not work correctly unless `_HashNode` has the exact same alignment
// and stride as `RawNode`.)
@usableFromInline
internal typealias Element = (key: Key, value: Value)
@usableFromInline
internal var raw: _RawNode
internal var raw: _RawHashNode
@inlinable
internal init(storage: _RawStorage, count: Int) {
self.raw = _RawNode(storage: storage, count: count)
internal init(storage: _RawHashStorage, count: Int) {
self.raw = _RawHashNode(storage: storage, count: count)
}
}
extension _Node {
extension _HashNode {
@inlinable @inline(__always)
internal var count: Int {
get { raw.count }
@@ -68,19 +68,19 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable @inline(__always)
internal var unmanaged: _UnmanagedNode {
_UnmanagedNode(raw.storage)
internal var unmanaged: _UnmanagedHashNode {
_UnmanagedHashNode(raw.storage)
}
@inlinable @inline(__always)
internal func isIdentical(to other: _UnmanagedNode) -> Bool {
internal func isIdentical(to other: _UnmanagedHashNode) -> Bool {
raw.isIdentical(to: other)
}
}
extension _Node {
extension _HashNode {
@inlinable @inline(__always)
internal func read<R>(
_ body: (UnsafeHandle) throws -> R
@@ -98,7 +98,7 @@ extension _Node {
// MARK: Shortcuts to reading header data
extension _Node {
extension _HashNode {
@inlinable
internal var isCollisionNode: Bool {
read { $0.isCollisionNode }
@@ -125,7 +125,7 @@ extension _Node {
}
}
extension _Node {
extension _HashNode {
@inlinable
internal var initialVersionNumber: UInt {
// Ideally we would simply just generate a true random number, but the
@@ -11,14 +11,14 @@
/// Identifies a position within a contiguous storage region within a hash tree
/// node. Hash tree nodes have two storage regions, one for items and one for
/// children; the same `_Slot` type is used to refer to positions within both.
/// children; the same `_HashSlot` type is used to refer to positions within both.
///
/// We use the term "slot" to refer to internal storage entries, to avoid
/// confusion with terms that sometimes appear in public API, such as
/// "index", "position" or "offset".
@usableFromInline
@frozen
internal struct _Slot {
internal struct _HashSlot {
@usableFromInline
internal var _value: UInt32
@@ -40,55 +40,55 @@ internal struct _Slot {
}
}
extension _Slot {
extension _HashSlot {
@inlinable @inline(__always)
internal static var zero: _Slot { _Slot(0) }
internal static var zero: _HashSlot { _HashSlot(0) }
}
extension _Slot {
extension _HashSlot {
@inlinable @inline(__always)
internal var value: Int {
Int(truncatingIfNeeded: _value)
}
}
extension _Slot: Equatable {
extension _HashSlot: Equatable {
@inlinable @inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left._value == right._value
}
}
extension _Slot: Comparable {
extension _HashSlot: Comparable {
@inlinable @inline(__always)
internal static func <(left: Self, right: Self) -> Bool {
left._value < right._value
}
}
extension _Slot: Hashable {
extension _HashSlot: Hashable {
@inlinable
internal func hash(into hasher: inout Hasher) {
hasher.combine(_value)
}
}
extension _Slot: CustomStringConvertible {
extension _HashSlot: CustomStringConvertible {
@usableFromInline
internal var description: String {
"\(_value)"
}
}
extension _Slot: Strideable {
extension _HashSlot: Strideable {
@inlinable @inline(__always)
internal func advanced(by n: Int) -> _Slot {
internal func advanced(by n: Int) -> _HashSlot {
assert(n >= 0 || value + n >= 0)
return _Slot(_value &+ UInt32(truncatingIfNeeded: n))
return _HashSlot(_value &+ UInt32(truncatingIfNeeded: n))
}
@inlinable @inline(__always)
internal func distance(to other: _Slot) -> Int {
internal func distance(to other: _HashSlot) -> Int {
if self < other {
return Int(truncatingIfNeeded: other._value - self._value)
}
@@ -96,16 +96,16 @@ extension _Slot: Strideable {
}
}
extension _Slot {
extension _HashSlot {
@inlinable @inline(__always)
internal func next() -> _Slot {
internal func next() -> _HashSlot {
assert(_value < .max)
return _Slot(_value &+ 1)
return _HashSlot(_value &+ 1)
}
@inlinable @inline(__always)
internal func previous() -> _Slot {
internal func previous() -> _HashSlot {
assert(_value > 0)
return _Slot(_value &- 1)
return _HashSlot(_value &- 1)
}
}
@@ -13,7 +13,7 @@
/// `TreeDictionary`.
@usableFromInline
@frozen
internal struct _Stack<Element> {
internal struct _HashStack<Element> {
#if arch(x86_64) || arch(arm64)
@inlinable
@inline(__always)
@@ -45,7 +45,7 @@ internal struct _Stack<Element> {
@inlinable
internal init(filledWith value: Element) {
assert(Self.capacity == _Level.limit)
assert(Self.capacity == _HashLevel.limit)
#if arch(x86_64) || arch(arm64)
_contents = (
value, value, value, value,
@@ -14,39 +14,39 @@
internal struct _HashTreeIterator {
@usableFromInline
internal struct _Opaque {
internal var ancestorSlots: _AncestorSlots
internal var ancestorNodes: _Stack<_UnmanagedNode>
internal var level: _Level
internal var ancestorSlots: _AncestorHashSlots
internal var ancestorNodes: _HashStack<_UnmanagedHashNode>
internal var level: _HashLevel
internal var isAtEnd: Bool
@usableFromInline
@_effects(releasenone)
internal init(_ root: _UnmanagedNode) {
internal init(_ root: _UnmanagedHashNode) {
self.ancestorSlots = .empty
self.ancestorNodes = _Stack(filledWith: root)
self.ancestorNodes = _HashStack(filledWith: root)
self.level = .top
self.isAtEnd = false
}
}
@usableFromInline
internal let root: _RawStorage
internal let root: _RawHashStorage
@usableFromInline
internal var node: _UnmanagedNode
internal var node: _UnmanagedHashNode
@usableFromInline
internal var slot: _Slot
internal var slot: _HashSlot
@usableFromInline
internal var endSlot: _Slot
internal var endSlot: _HashSlot
@usableFromInline
internal var _o: _Opaque
@usableFromInline
@_effects(releasenone)
internal init(root: __shared _RawNode) {
internal init(root: __shared _RawHashNode) {
self.root = root.storage
self.node = root.unmanaged
self.slot = .zero
@@ -64,7 +64,8 @@ internal struct _HashTreeIterator {
extension _HashTreeIterator: IteratorProtocol {
@inlinable
internal mutating func next() -> (node: _UnmanagedNode, slot: _Slot)? {
internal mutating func next(
) -> (node: _UnmanagedHashNode, slot: _HashSlot)? {
guard slot < endSlot else {
return _next()
}
@@ -74,7 +75,8 @@ extension _HashTreeIterator: IteratorProtocol {
@usableFromInline
@_effects(releasenone)
internal mutating func _next() -> (node: _UnmanagedNode, slot: _Slot)? {
internal mutating func _next(
) -> (node: _UnmanagedHashNode, slot: _HashSlot)? {
if _o.isAtEnd { return nil }
if node.hasChildren {
_descendToLeftmostItem(ofChildAtSlot: .zero)
@@ -98,7 +100,7 @@ extension _HashTreeIterator: IteratorProtocol {
}
extension _HashTreeIterator {
internal mutating func _descend(toChildSlot childSlot: _Slot) {
internal mutating func _descend(toChildSlot childSlot: _HashSlot) {
assert(childSlot < node.childrenEndSlot)
_o.ancestorSlots[_o.level] = childSlot
_o.ancestorNodes.push(node)
@@ -108,7 +110,7 @@ extension _HashTreeIterator {
endSlot = node.itemsEndSlot
}
internal mutating func _ascend() -> _Slot {
internal mutating func _ascend() -> _HashSlot {
assert(!_o.level.isAtRoot)
node = _o.ancestorNodes.pop()
_o.level = _o.level.ascend()
@@ -118,7 +120,7 @@ extension _HashTreeIterator {
}
internal mutating func _descendToLeftmostItem(
ofChildAtSlot childSlot: _Slot
ofChildAtSlot childSlot: _HashSlot
) {
_descend(toChildSlot: childSlot)
while endSlot == .zero {
@@ -86,9 +86,9 @@ public struct _HashTreeStatistics {
}
extension _Node {
extension _HashNode {
internal func gatherStatistics(
_ level: _Level, _ stats: inout _HashTreeStatistics
_ level: _HashLevel, _ stats: inout _HashTreeStatistics
) {
// The empty singleton does not count as a node and occupies no space.
if self.raw.storage === _emptySingleton { return }
@@ -111,7 +111,7 @@ extension _Node {
stats.capacityBytes += $0.byteCapacity
stats.freeBytes += $0.bytesFree
stats.itemBytes += $0.itemCount * (keyStride + valueStride)
stats.childBytes += $0.childCount * MemoryLayout<_RawNode>.stride
stats.childBytes += $0.childCount * MemoryLayout<_RawHashNode>.stride
let objectHeaderSize = 2 * MemoryLayout<Int>.stride
@@ -119,7 +119,7 @@ extension _Node {
// the object header and the storage header.
let start = _getUnsafePointerToStoredProperties(self.raw.storage)
let capacity = self.raw.storage.capacity
let end = $0._memory + capacity * MemoryLayout<_RawNode>.stride
let end = $0._memory + capacity * MemoryLayout<_RawHashNode>.stride
stats.grossBytes += objectHeaderSize + (end - start)
for child in $0.children {
@@ -9,12 +9,12 @@
//
//===----------------------------------------------------------------------===//
extension _RawNode {
extension _RawHashNode {
/// An unsafe, non-generic view of the data stored inside a node in the
/// hash tree, hiding the mechanics of accessing storage from the code that
/// uses it.
///
/// This is the non-generic equivalent of `_Node.UnsafeHandle`, sharing some
/// This is the non-generic equivalent of `_HashNode.UnsafeHandle`, sharing some
/// of its functionality, but it only provides read-only access to the tree
/// structure (incl. subtree counts) -- it doesn't provide any ways to mutate
/// the underlying data or to access user payload.
@@ -26,14 +26,14 @@ extension _RawNode {
@frozen
internal struct UnsafeHandle {
@usableFromInline
internal let _header: UnsafePointer<_StorageHeader>
internal let _header: UnsafePointer<_HashNodeHeader>
@usableFromInline
internal let _memory: UnsafeRawPointer
@inlinable
internal init(
_ header: UnsafePointer<_StorageHeader>,
_ header: UnsafePointer<_HashNodeHeader>,
_ memory: UnsafeRawPointer
) {
self._header = header
@@ -42,10 +42,10 @@ extension _RawNode {
}
}
extension _RawNode.UnsafeHandle {
extension _RawHashNode.UnsafeHandle {
@inlinable @inline(__always)
static func read<R>(
_ node: _UnmanagedNode,
_ node: _UnmanagedHashNode,
_ body: (Self) throws -> R
) rethrows -> R {
try node.ref._withUnsafeGuaranteedRef { storage in
@@ -56,7 +56,7 @@ extension _RawNode.UnsafeHandle {
}
}
extension _RawNode.UnsafeHandle {
extension _RawHashNode.UnsafeHandle {
@inline(__always)
internal var isCollisionNode: Bool {
_header.pointee.isCollisionNode
@@ -79,7 +79,7 @@ extension _RawNode.UnsafeHandle {
}
@inline(__always)
internal var childrenEndSlot: _Slot {
internal var childrenEndSlot: _HashSlot {
_header.pointee.childrenEndSlot
}
@@ -94,23 +94,23 @@ extension _RawNode.UnsafeHandle {
}
@inline(__always)
internal var itemsEndSlot: _Slot {
internal var itemsEndSlot: _HashSlot {
_header.pointee.itemsEndSlot
}
@inline(__always)
internal var _childrenStart: UnsafePointer<_RawNode> {
_memory.assumingMemoryBound(to: _RawNode.self)
internal var _childrenStart: UnsafePointer<_RawHashNode> {
_memory.assumingMemoryBound(to: _RawHashNode.self)
}
internal subscript(child slot: _Slot) -> _RawNode {
internal subscript(child slot: _HashSlot) -> _RawHashNode {
unsafeAddress {
assert(slot < childrenEndSlot)
return _childrenStart + slot.value
}
}
internal var children: UnsafeBufferPointer<_RawNode> {
internal var children: UnsafeBufferPointer<_RawHashNode> {
UnsafeBufferPointer(start: _childrenStart, count: childCount)
}
}
@@ -17,21 +17,21 @@
/// `distance(from:to:)`, `index(_:offsetBy:)` in non-generic code.
@usableFromInline
@frozen
internal struct _RawNode {
internal struct _RawHashNode {
@usableFromInline
internal var storage: _RawStorage
internal var storage: _RawHashStorage
@usableFromInline
internal var count: Int
@inlinable
internal init(storage: _RawStorage, count: Int) {
internal init(storage: _RawHashStorage, count: Int) {
self.storage = storage
self.count = count
}
}
extension _RawNode {
extension _RawHashNode {
@inline(__always)
internal func read<R>(_ body: (UnsafeHandle) -> R) -> R {
storage.withUnsafeMutablePointers { header, elements in
@@ -40,22 +40,22 @@ extension _RawNode {
}
}
extension _RawNode {
extension _RawHashNode {
@inlinable @inline(__always)
internal var unmanaged: _UnmanagedNode {
_UnmanagedNode(storage)
internal var unmanaged: _UnmanagedHashNode {
_UnmanagedHashNode(storage)
}
@inlinable @inline(__always)
internal func isIdentical(to other: _UnmanagedNode) -> Bool {
internal func isIdentical(to other: _UnmanagedHashNode) -> Bool {
other.ref.toOpaque() == Unmanaged.passUnretained(storage).toOpaque()
}
}
extension _RawNode {
extension _RawHashNode {
@usableFromInline
internal func validatePath(_ path: _UnsafePath) {
var l = _Level.top
var l = _HashLevel.top
var n = self.unmanaged
while l < path.level {
let slot = path.ancestors[l]
@@ -14,7 +14,7 @@
/// information about the currently occupied hash table buckets.
@usableFromInline
@frozen
internal struct _StorageHeader {
internal struct _HashNodeHeader {
@usableFromInline
internal var itemMap: _Bitmap
@@ -37,7 +37,7 @@ internal struct _StorageHeader {
}
}
extension _StorageHeader {
extension _HashNodeHeader {
@inlinable @inline(__always)
internal var byteCapacity: Int {
get { Int(truncatingIfNeeded: _byteCapacity) }
@@ -54,7 +54,7 @@ extension _StorageHeader {
}
}
extension _StorageHeader {
extension _HashNodeHeader {
@inlinable @inline(__always)
internal var isEmpty: Bool {
return itemMap.isEmpty && childMap.isEmpty
@@ -101,13 +101,13 @@ extension _StorageHeader {
}
@inlinable @inline(__always)
internal var childrenEndSlot: _Slot {
_Slot(childCount)
internal var childrenEndSlot: _HashSlot {
_HashSlot(childCount)
}
@inlinable @inline(__always)
internal var itemsEndSlot: _Slot {
_Slot(itemCount)
internal var itemsEndSlot: _HashSlot {
_HashSlot(itemCount)
}
@inlinable
@@ -125,7 +125,7 @@ extension _StorageHeader {
}
}
extension _StorageHeader {
extension _HashNodeHeader {
@inlinable
internal mutating func clear() {
itemMap = .empty
@@ -12,24 +12,24 @@
import _CollectionsUtilities
/// An unsafe, unowned, type-erased reference to a hash tree node; essentially
/// just a lightweight wrapper around `Unmanaged<_RawStorage>`.
/// just a lightweight wrapper around `Unmanaged<_RawHashStorage>`.
///
/// Because such a reference may outlive the underlying object, use sites must
/// be extraordinarily careful to never dereference an invalid `_UnmanagedNode`.
/// Doing so results in undefined behavior.
/// be extraordinarily careful to never dereference an invalid
/// `_UnmanagedHashNode`. Doing so results in undefined behavior.
@usableFromInline
@frozen
internal struct _UnmanagedNode {
internal struct _UnmanagedHashNode {
@usableFromInline
internal var ref: Unmanaged<_RawStorage>
internal var ref: Unmanaged<_RawHashStorage>
@inlinable @inline(__always)
internal init(_ storage: _RawStorage) {
internal init(_ storage: _RawHashStorage) {
self.ref = .passUnretained(storage)
}
}
extension _UnmanagedNode: Equatable {
extension _UnmanagedHashNode: Equatable {
/// Indicates whether two unmanaged node references are equal.
///
/// This function is safe to call even if one or both of its arguments are
@@ -42,24 +42,24 @@ extension _UnmanagedNode: Equatable {
}
}
extension _UnmanagedNode: CustomStringConvertible {
extension _UnmanagedHashNode: CustomStringConvertible {
@usableFromInline
internal var description: String {
_addressString(for: ref.toOpaque())
}
}
extension _UnmanagedNode {
extension _UnmanagedHashNode {
@inlinable @inline(__always)
internal func withRaw<R>(_ body: (_RawStorage) -> R) -> R {
internal func withRaw<R>(_ body: (_RawHashStorage) -> R) -> R {
ref._withUnsafeGuaranteedRef(body)
}
@inline(__always)
internal func read<R>(_ body: (_RawNode.UnsafeHandle) -> R) -> R {
internal func read<R>(_ body: (_RawHashNode.UnsafeHandle) -> R) -> R {
ref._withUnsafeGuaranteedRef { storage in
storage.withUnsafeMutablePointers { header, elements in
body(_RawNode.UnsafeHandle(header, UnsafeRawPointer(elements)))
body(_RawHashNode.UnsafeHandle(header, UnsafeRawPointer(elements)))
}
}
}
@@ -85,17 +85,17 @@ extension _UnmanagedNode {
}
@inlinable
internal var itemsEndSlot: _Slot {
withRaw { _Slot($0.header.itemCount) }
internal var itemsEndSlot: _HashSlot {
withRaw { _HashSlot($0.header.itemCount) }
}
@inlinable
internal var childrenEndSlot: _Slot {
withRaw { _Slot($0.header.childCount) }
internal var childrenEndSlot: _HashSlot {
withRaw { _HashSlot($0.header.childCount) }
}
@inlinable
internal func unmanagedChild(at slot: _Slot) -> Self {
internal func unmanagedChild(at slot: _HashSlot) -> Self {
withRaw { raw in
assert(slot.value < raw.header.childCount)
return raw.withUnsafeMutablePointerToElements { p in
@@ -24,7 +24,7 @@
/// including the final node on the path.
///
/// However, to speed up common operations, path values also include a single
/// `_UnmanagedNode` reference to their final node. This reference does not
/// `_UnmanagedHashNode` reference to their final node. This reference does not
/// keep the targeted node alive -- it is the use site's responsibility to
/// ensure that the path is still valid before calling most of its operations.
///
@@ -37,22 +37,22 @@
@frozen
internal struct _UnsafePath {
@usableFromInline
internal var ancestors: _AncestorSlots
internal var ancestors: _AncestorHashSlots
@usableFromInline
internal var node: _UnmanagedNode
internal var node: _UnmanagedHashNode
@usableFromInline
internal var nodeSlot: _Slot
internal var nodeSlot: _HashSlot
@usableFromInline
internal var level: _Level
internal var level: _HashLevel
@usableFromInline
internal var _isItem: Bool
@inlinable
internal init(root: __shared _RawNode) {
internal init(root: __shared _RawHashNode) {
self.level = .top
self.ancestors = .empty
self.node = root.unmanaged
@@ -63,10 +63,10 @@ internal struct _UnsafePath {
extension _UnsafePath {
internal init(
_ level: _Level,
_ ancestors: _AncestorSlots,
_ node: _UnmanagedNode,
childSlot: _Slot
_ level: _HashLevel,
_ ancestors: _AncestorHashSlots,
_ node: _UnmanagedHashNode,
childSlot: _HashSlot
) {
assert(childSlot < node.childrenEndSlot)
self.level = level
@@ -78,10 +78,10 @@ extension _UnsafePath {
@inlinable
internal init(
_ level: _Level,
_ ancestors: _AncestorSlots,
_ node: _UnmanagedNode,
itemSlot: _Slot
_ level: _HashLevel,
_ ancestors: _AncestorHashSlots,
_ node: _UnmanagedHashNode,
itemSlot: _HashSlot
) {
assert(itemSlot < node.itemsEndSlot)
self.level = level
@@ -126,7 +126,7 @@ extension _UnsafePath: Comparable {
// Paths addressing items within a node are ordered before paths addressing
// a child node within the same node.
var level: _Level = .top
var level: _HashLevel = .top
while level < left.level, level < right.level {
let l = left.ancestors[level]
let r = right.ancestors[level]
@@ -156,7 +156,7 @@ extension _UnsafePath: CustomStringConvertible {
@usableFromInline
internal var description: String {
var d = "@"
var l: _Level = .top
var l: _HashLevel = .top
while l < self.level {
d += ".\(self.ancestors[l])"
l = l.descend()
@@ -226,7 +226,7 @@ extension _UnsafePath {
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
internal var currentChild: _UnmanagedNode {
internal var currentChild: _UnmanagedHashNode {
assert(isOnChild)
return node.unmanagedChild(at: nodeSlot)
}
@@ -236,7 +236,7 @@ extension _UnsafePath {
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
internal func childSlot(at level: _Level) -> _Slot {
internal func childSlot(at level: _HashLevel) -> _HashSlot {
assert(level < self.level)
return ancestors[level]
}
@@ -245,7 +245,7 @@ extension _UnsafePath {
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable @inline(__always)
internal var currentItemSlot: _Slot {
internal var currentItemSlot: _HashSlot {
assert(isOnItem)
return nodeSlot
}
@@ -258,7 +258,7 @@ extension _UnsafePath {
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
internal mutating func selectItem(at slot: _Slot) {
internal mutating func selectItem(at slot: _HashSlot) {
// 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.
@@ -273,7 +273,7 @@ extension _UnsafePath {
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
internal mutating func selectChild(at slot: _Slot) {
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)
@@ -317,7 +317,7 @@ extension _UnsafePath {
/// valid.
@inlinable
internal mutating func descendToChild(
_ child: _UnmanagedNode, at slot: _Slot
_ child: _UnmanagedHashNode, at slot: _HashSlot
) {
assert(slot < node.childrenEndSlot)
assert(child == node.unmanagedChild(at: slot))
@@ -328,7 +328,9 @@ extension _UnsafePath {
self.level = level.descend()
}
internal mutating func ascend(to ancestor: _UnmanagedNode, at level: _Level) {
internal mutating func ascend(
to ancestor: _UnmanagedHashNode, at level: _HashLevel
) {
guard level != self.level else { return }
assert(level < self.level)
self.level = level
@@ -347,13 +349,13 @@ extension _UnsafePath {
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
internal mutating func ascendToNearestAncestor(
under root: _RawNode,
where test: (_UnmanagedNode, _Slot) -> Bool
under root: _RawHashNode,
where test: (_UnmanagedHashNode, _HashSlot) -> Bool
) -> Bool {
if self.level.isAtRoot { return false }
var best: _UnsafePath? = nil
var n = root.unmanaged
var l: _Level = .top
var l: _HashLevel = .top
while l < self.level {
let slot = self.ancestors[l]
if test(n, slot) {
@@ -442,7 +444,7 @@ extension _UnsafePath {
/// path does not currently address an item.
@usableFromInline
@_effects(releasenone)
internal mutating func findSuccessorItem(under root: _RawNode) -> Bool {
internal mutating func findSuccessorItem(under root: _RawHashNode) -> Bool {
guard isOnItem else { return false }
if selectNextItem() { return true }
if node.hasChildren {
@@ -469,7 +471,7 @@ extension _UnsafePath {
/// Return false if there is no previous item.
@usableFromInline
@_effects(releasenone)
internal mutating func findPredecessorItem(under root: _RawNode) -> Bool {
internal mutating func findPredecessorItem(under root: _RawHashNode) -> Bool {
switch (isOnItem, nodeSlot > .zero) {
case (true, true):
selectItem(at: nodeSlot.previous())
@@ -505,14 +507,14 @@ extension _UnsafePath {
}
}
extension _RawNode {
extension _RawHashNode {
/// Return the integer position of the item addressed by the given path
/// within a preorder walk of the tree. If the path addresses the end
/// position, then return the number of items in the tree.
///
/// This method must only be called on the root node.
internal func preorderPosition(
_ level: _Level, of path: _UnsafePath
_ level: _HashLevel, of path: _UnsafePath
) -> Int {
if path.isOnNodeEnd { return count }
assert(path.isOnItem)
@@ -551,7 +553,7 @@ extension _UnsafePath {
while !stop {
let itemCount = node.itemCount
if remaining < itemCount {
selectItem(at: _Slot(remaining))
selectItem(at: _HashSlot(remaining))
return (true, 0)
}
remaining -= itemCount
@@ -560,7 +562,7 @@ extension _UnsafePath {
for i in children.indices {
let c = children[i].count
if remaining < c {
descendToChild(children[i].unmanaged, at: _Slot(i))
descendToChild(children[i].unmanaged, at: _HashSlot(i))
return
}
remaining &-= c
@@ -574,7 +576,7 @@ extension _UnsafePath {
}
}
extension _RawNode {
extension _RawHashNode {
/// Return the number of steps between two paths within a preorder walk of the
/// tree. The two paths must not address a child node.
///
@@ -582,7 +584,7 @@ extension _RawNode {
@usableFromInline
@_effects(releasenone)
internal func distance(
_ level: _Level, from start: _UnsafePath, to end: _UnsafePath
_ level: _HashLevel, from start: _UnsafePath, to end: _UnsafePath
) -> Int {
assert(level.isAtRoot)
if start.isOnNodeEnd {
@@ -623,7 +625,7 @@ extension _RawNode {
}
internal func _distance(
_ level: _Level, from start: _UnsafePath, to end: _UnsafePath
_ level: _HashLevel, from start: _UnsafePath, to end: _UnsafePath
) -> Int {
assert(start < end)
assert(level < start.level)
@@ -648,9 +650,9 @@ extension _RawNode {
}
}
extension _UnmanagedNode {
extension _UnmanagedHashNode {
internal func _distance(
_ level: _Level, fromItemAt start: _Slot, to end: _UnsafePath
_ level: _HashLevel, fromItemAt start: _HashSlot, to end: _UnsafePath
) -> Int {
read {
assert(start < $0.itemsEndSlot)
@@ -666,7 +668,7 @@ extension _UnmanagedNode {
}
}
extension _Node {
extension _HashNode {
/// Return the path to the given key in this tree if it exists; otherwise
/// return nil.
@inlinable
@@ -674,8 +676,8 @@ extension _Node {
to key: Key, _ hash: _Hash
) -> _UnsafePath? {
var node = unmanaged
var level: _Level = .top
var ancestors: _AncestorSlots = .empty
var level: _HashLevel = .top
var ancestors: _AncestorHashSlots = .empty
while true {
let r = UnsafeHandle.read(node) { $0.find(level, key, hash) }
guard let r = r else { break }
@@ -690,11 +692,11 @@ extension _Node {
}
}
extension _RawNode {
extension _RawHashNode {
@usableFromInline
@_effects(releasenone)
internal func seek(
_ level: _Level,
_ level: _HashLevel,
_ path: inout _UnsafePath,
offsetBy distance: Int,
limitedBy limit: _UnsafePath
@@ -718,7 +720,7 @@ extension _RawNode {
@usableFromInline
@_effects(releasenone)
internal func seek(
_ level: _Level,
_ level: _HashLevel,
_ path: inout _UnsafePath,
offsetBy distance: Int
) -> Bool {
@@ -733,7 +735,7 @@ extension _RawNode {
}
internal func _seek(
_ level: _Level,
_ level: _HashLevel,
_ path: inout _UnsafePath,
offsetBy distance: inout Int
) -> Bool {
@@ -768,7 +770,7 @@ extension _RawNode {
let slot = path.nodeSlot
distance &+= slot.value
if distance >= 0 {
path.selectItem(at: _Slot(distance))
path.selectItem(at: _HashSlot(distance))
distance = 0
return true
}
@@ -782,7 +784,7 @@ extension _RawNode {
/// Find the item at the given positive distance from the last item within the
/// subtree rooted at the current node in `path`.
internal func _seekForward(
_ level: _Level,
_ level: _HashLevel,
by distance: inout Int,
fromSubtree path: inout _UnsafePath
) -> Bool {
@@ -806,7 +808,7 @@ extension _RawNode {
while i < children.endIndex {
let c = children[i].count
if distance < c {
path.descendToChild(children[i].unmanaged, at: _Slot(i))
path.descendToChild(children[i].unmanaged, at: _HashSlot(i))
let r = path.findItemAtPreorderPosition(distance)
precondition(r.found, "Internal inconsistency: invalid node counts")
assert(r.remaining == 0)
@@ -824,7 +826,7 @@ extension _RawNode {
/// Find the item at the given negative distance from the first item within the
/// subtree rooted at the current node in `path`.
internal func _seekBackward(
_ level: _Level,
_ level: _HashLevel,
by distance: inout Int,
fromSubtree path: inout _UnsafePath
) -> Bool {
@@ -833,7 +835,7 @@ extension _RawNode {
return read {
let children = $0.children
var slot: _Slot
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.
@@ -875,7 +877,7 @@ extension _RawNode {
// See if the target is hiding somwhere in our immediate items.
distance &+= $0.itemCount
if distance >= 0 {
path.selectItem(at: _Slot(distance))
path.selectItem(at: _HashSlot(distance))
distance = 0
return true
}
@@ -19,7 +19,7 @@ extension TreeDictionary {
@frozen
public struct Index {
@usableFromInline
internal let _root: _UnmanagedNode
internal let _root: _UnmanagedHashNode
@usableFromInline
internal var _version: UInt
@@ -29,7 +29,7 @@ extension TreeDictionary {
@inlinable @inline(__always)
internal init(
_root: _UnmanagedNode, version: UInt, path: _UnsafePath
_root: _UnmanagedHashNode, version: UInt, path: _UnsafePath
) {
self._root = _root
self._version = version
@@ -32,7 +32,7 @@ extension TreeDictionary {
}
public static var _maxDepth: Int {
_Level.limit
_HashLevel.limit
}
public var _statistics: _HashTreeStatistics {
@@ -16,7 +16,7 @@ extension TreeDictionary {
@frozen
public struct Keys {
@usableFromInline
internal typealias _Node = HashTreeCollections._Node<Key, Value>
internal typealias _HashNode = HashTreeCollections._HashNode<Key, Value>
@usableFromInline
internal var _base: TreeDictionary
@@ -22,13 +22,13 @@ extension TreeDictionary: Sequence {
// before any items within children.
@usableFromInline
internal typealias _UnsafeHandle = _Node.UnsafeHandle
internal typealias _UnsafeHandle = _HashNode.UnsafeHandle
@usableFromInline
internal var _it: _HashTreeIterator
@inlinable
internal init(_root: _RawNode) {
internal init(_root: _RawHashNode) {
self._it = _HashTreeIterator(root: _root)
}
}
@@ -16,10 +16,10 @@ extension TreeDictionary {
@frozen
public struct Values {
@usableFromInline
internal typealias _Node = HashTreeCollections._Node<Key, Value>
internal typealias _HashNode = HashTreeCollections._HashNode<Key, Value>
@usableFromInline
internal typealias _UnsafeHandle = _Node.UnsafeHandle
internal typealias _UnsafeHandle = _HashNode.UnsafeHandle
@usableFromInline
internal var _base: TreeDictionary
@@ -65,13 +65,13 @@
@frozen // Not really -- this package is not at all ABI stable
public struct TreeDictionary<Key: Hashable, Value> {
@usableFromInline
internal typealias _Node = HashTreeCollections._Node<Key, Value>
internal typealias _HashNode = HashTreeCollections._HashNode<Key, Value>
@usableFromInline
internal typealias _UnsafeHandle = _Node.UnsafeHandle
internal typealias _UnsafeHandle = _HashNode.UnsafeHandle
@usableFromInline
var _root: _Node
var _root: _HashNode
/// The version number of this instance, used for quick index validation.
/// This is initialized to a (very weakly) random value and it gets
@@ -80,13 +80,13 @@ public struct TreeDictionary<Key: Hashable, Value> {
var _version: UInt
@inlinable
internal init(_root: _Node, version: UInt) {
internal init(_root: _HashNode, version: UInt) {
self._root = _root
self._version = version
}
@inlinable
internal init(_new: _Node) {
internal init(_new: _HashNode) {
self.init(_root: _new, version: _new.initialVersionNumber)
}
}
@@ -19,7 +19,7 @@ extension TreeSet {
@frozen
public struct Index {
@usableFromInline
internal let _root: _UnmanagedNode
internal let _root: _UnmanagedHashNode
@usableFromInline
internal var _version: UInt
@@ -29,7 +29,7 @@ extension TreeSet {
@inlinable @inline(__always)
internal init(
_root: _UnmanagedNode, version: UInt, path: _UnsafePath
_root: _UnmanagedHashNode, version: UInt, path: _UnsafePath
) {
self._root = _root
self._version = version
@@ -32,7 +32,7 @@ extension TreeSet {
}
public static var _maxDepth: Int {
_Level.limit
_HashLevel.limit
}
public var _statistics: _HashTreeStatistics {
@@ -14,13 +14,13 @@ extension TreeSet: Sequence {
@frozen
public struct Iterator: IteratorProtocol {
@usableFromInline
internal typealias _UnsafeHandle = _Node.UnsafeHandle
internal typealias _UnsafeHandle = _HashNode.UnsafeHandle
@usableFromInline
internal var _it: _HashTreeIterator
@inlinable
internal init(_root: _RawNode) {
internal init(_root: _RawHashNode) {
_it = _HashTreeIterator(root: _root)
}
@@ -62,7 +62,7 @@ extension TreeSet {
@inlinable
internal func _intersection<V>(
_ other: HashTreeCollections._Node<Element, V>
_ other: HashTreeCollections._HashNode<Element, V>
) -> Self {
guard let r = _root.intersection(.top, other) else { return self }
return Self(_new: r)
@@ -97,7 +97,7 @@ extension TreeSet {
return self.filter { other.contains($0) }
}
var result: _Node = ._emptyNode()
var result: _HashNode = ._emptyNode()
for item in other {
let hash = _Hash(item)
if let r = self._root.lookup(.top, item, hash) {
@@ -102,7 +102,7 @@ extension TreeSet {
}
// FIXME: Would making this a BitSet of seen positions be better?
var seen: _Node? = ._emptyNode()
var seen: _HashNode? = ._emptyNode()
var it = other.makeIterator()
while let item = it.next() {
let hash = _Hash(item)
@@ -111,7 +111,7 @@ extension TreeSet {
}
// FIXME: Would making this a BitSet of seen positions be better?
var seen: _Node = ._emptyNode()
var seen: _HashNode = ._emptyNode()
var doneCollecting = false
var isStrict = false
var it = other.makeIterator()
@@ -108,7 +108,7 @@ extension TreeSet {
}
// FIXME: Would making this a BitSet of seen positions be better?
var seen: _Node = ._emptyNode()
var seen: _HashNode = ._emptyNode()
for item in other {
let hash = _Hash(item)
guard self._root.containsKey(.top, item, hash) else { return false }
@@ -99,7 +99,7 @@ extension TreeSet {
}
// FIXME: Would making this a BitSet of seen positions be better?
var seen: _Node = ._emptyNode()
var seen: _HashNode = ._emptyNode()
for item in other {
let hash = _Hash(item)
guard _root.containsKey(.top, item, hash) else { continue }
@@ -54,7 +54,7 @@ extension TreeSet {
@inlinable
internal __consuming func _subtracting<V>(
_ other: HashTreeCollections._Node<Element, V>
_ other: HashTreeCollections._HashNode<Element, V>
) -> Self {
guard let r = _root.subtracting(.top, other) else { return self }
return Self(_new: r)
@@ -60,25 +60,25 @@
@frozen // Not really -- this package is not at all ABI stable
public struct TreeSet<Element: Hashable> {
@usableFromInline
internal typealias _Node = HashTreeCollections._Node<Element, Void>
internal typealias _HashNode = HashTreeCollections._HashNode<Element, Void>
@usableFromInline
internal typealias _UnsafeHandle = _Node.UnsafeHandle
internal typealias _UnsafeHandle = _HashNode.UnsafeHandle
@usableFromInline
internal var _root: _Node
internal var _root: _HashNode
@usableFromInline
internal var _version: UInt
@inlinable
internal init(_root: _Node, version: UInt) {
internal init(_root: _HashNode, version: UInt) {
self._root = _root
self._version = version
}
@inlinable
internal init(_new: _Node) {
internal init(_new: _HashNode) {
self.init(_root: _new, version: _new.initialVersionNumber)
}
}