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

@@ -0,0 +1,111 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A 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 `_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 _AncestorHashSlots {
@usableFromInline
internal var path: UInt
@inlinable @inline(__always)
internal init(_ path: UInt) {
self.path = path
}
}
extension _AncestorHashSlots: Equatable {
@inlinable @inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left.path == right.path
}
}
extension _AncestorHashSlots {
@inlinable @inline(__always)
internal static var empty: Self { Self(0) }
}
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: _HashLevel) -> _HashSlot {
get {
assert(level.shift < UInt.bitWidth)
return _HashSlot((path &>> level.shift) & _Bucket.bitMask)
}
set {
assert(newValue._value < _Bitmap.capacity)
assert(self[level] == .zero)
path |= (UInt(truncatingIfNeeded: newValue._value) &<< level.shift)
}
}
@inlinable @inline(__always)
internal func appending(_ slot: _HashSlot, at level: _HashLevel) -> Self {
var result = self
result[level] = slot
return result
}
/// Clear the slot at the specified level, by setting it to zero.
@inlinable
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: _HashLevel) {
guard level.shift < UInt.bitWidth else { return }
path &= ~(UInt.max &<< level.shift)
}
/// Truncate this path to the specified level.
/// Slots at or beyond the specified level are cleared.
@inlinable
internal func truncating(to level: _HashLevel) -> _AncestorHashSlots {
assert(level.shift <= UInt.bitWidth)
guard level.shift < UInt.bitWidth else { return self }
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: _HashLevel) -> Bool {
guard level.shift < UInt.bitWidth else { return false }
return (path &>> level.shift) != 0
}
/// 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: _HashLevel) -> Bool {
if level.isAtRoot { return true }
if level.isAtBottom { return self == other }
let s = UInt(UInt.bitWidth) - level.shift
let v1 = self.path &<< s
let v2 = other.path &<< s
return v1 == v2
}
}
@@ -0,0 +1,219 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
/// A set of `_Bucket` values, represented by a 32-bit wide bitset.
@usableFromInline
@frozen
internal struct _Bitmap {
@usableFromInline
internal typealias Value = UInt32
@usableFromInline
internal var _value: Value
@inlinable @inline(__always)
init(_value: Value) {
self._value = _value
}
@inlinable @inline(__always)
init(bitPattern: Int) {
self._value = Value(bitPattern)
}
@inlinable @inline(__always)
internal init(_ bucket: _Bucket) {
assert(bucket.value < Self.capacity)
_value = (1 &<< bucket.value)
}
@inlinable @inline(__always)
internal init(_ bucket1: _Bucket, _ bucket2: _Bucket) {
assert(bucket1.value < Self.capacity && bucket2.value < Self.capacity)
assert(bucket1 != bucket2)
_value = (1 &<< bucket1.value) | (1 &<< bucket2.value)
}
@inlinable
internal init(upTo bucket: _Bucket) {
assert(bucket.value < Self.capacity)
_value = (1 &<< bucket.value) &- 1
}
}
extension _Bitmap: Equatable {
@inlinable @inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left._value == right._value
}
}
extension _Bitmap: CustomStringConvertible {
@usableFromInline
internal var description: String {
let b = String(_value, radix: 2)
let bits = String(repeating: "0", count: _Bitmap.capacity - b.count) + b
return "\(String(bits.reversed())) (\(_value))"
}
}
extension _Bitmap {
@inlinable @inline(__always)
internal static var empty: Self { .init(_value: 0) }
@inlinable @inline(__always)
internal static var capacity: Int { Value.bitWidth }
@inlinable @inline(__always)
internal static var bitWidth: Int { capacity.trailingZeroBitCount }
@inlinable @inline(__always)
internal var count: Int { _value.nonzeroBitCount }
@inlinable @inline(__always)
internal var capacity: Int { Value.bitWidth }
@inlinable @inline(__always)
internal var isEmpty: Bool { _value == 0 }
@inlinable @inline(__always)
internal var hasExactlyOneMember: Bool {
_value != 0 && _value & (_value &- 1) == 0
}
@inlinable @inline(__always)
internal var first: _Bucket? {
guard !isEmpty else { return nil }
return _Bucket(
_value: UInt8(truncatingIfNeeded: _value.trailingZeroBitCount))
}
@inlinable @inline(__always)
internal mutating func popFirst() -> _Bucket? {
guard let bucket = first else { return nil }
_value &= _value &- 1 // Clear lowest nonzero bit.
return bucket
}
}
extension _Bitmap {
@inlinable @inline(__always)
internal func contains(_ bucket: _Bucket) -> Bool {
assert(bucket.value < capacity)
return _value & (1 &<< bucket.value) != 0
}
@inlinable @inline(__always)
internal mutating func insert(_ bucket: _Bucket) {
assert(bucket.value < capacity)
_value |= (1 &<< bucket.value)
}
@inlinable @inline(__always)
internal func inserting(_ bucket: _Bucket) -> _Bitmap {
assert(bucket.value < capacity)
return _Bitmap(_value: _value | (1 &<< bucket.value))
}
@inlinable @inline(__always)
internal mutating func remove(_ bucket: _Bucket) {
assert(bucket.value < capacity)
_value &= ~(1 &<< bucket.value)
}
@inlinable @inline(__always)
internal func removing(_ bucket: _Bucket) -> _Bitmap {
assert(bucket.value < capacity)
return _Bitmap(_value: _value & ~(1 &<< bucket.value))
}
@inlinable @inline(__always)
internal func slot(of bucket: _Bucket) -> _HashSlot {
_HashSlot(_value._rank(ofBit: bucket.value))
}
@inlinable @inline(__always)
internal func bucket(at slot: _HashSlot) -> _Bucket {
_Bucket(_value._bit(ranked: slot.value)!)
}
}
extension _Bitmap {
@inlinable @inline(__always)
internal func isSubset(of other: Self) -> Bool {
_value & ~other._value == 0
}
@inlinable @inline(__always)
internal func isDisjoint(with other: Self) -> Bool {
_value & other._value == 0
}
@inlinable @inline(__always)
internal func union(_ other: Self) -> Self {
Self(_value: _value | other._value)
}
@inlinable @inline(__always)
internal func intersection(_ other: Self) -> Self {
Self(_value: _value & other._value)
}
@inlinable @inline(__always)
internal func symmetricDifference(_ other: Self) -> Self {
Self(_value: _value & other._value)
}
@inlinable @inline(__always)
internal func subtracting(_ other: Self) -> Self {
Self(_value: _value & ~other._value)
}
}
extension _Bitmap: Sequence {
@usableFromInline
internal typealias Element = (bucket: _Bucket, slot: _HashSlot)
@usableFromInline
@frozen
internal struct Iterator: IteratorProtocol {
@usableFromInline
internal var bitmap: _Bitmap
@usableFromInline
internal var slot: _HashSlot
@inlinable
internal init(_ bitmap: _Bitmap) {
self.bitmap = bitmap
self.slot = .zero
}
/// Return the index of the lowest set bit in this word,
/// and also destructively clear it.
@inlinable
internal mutating func next() -> Element? {
guard let bucket = bitmap.popFirst() else { return nil }
defer { slot = slot.next() }
return (bucket, slot)
}
}
@inlinable
internal var underestimatedCount: Int { count }
@inlinable
internal func makeIterator() -> Iterator {
Iterator(self)
}
}
@@ -0,0 +1,71 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// Identifies an entry in the hash table inside a node.
/// (Internally, a number between 0 and 31.)
@usableFromInline
@frozen
internal struct _Bucket {
@usableFromInline
internal var _value: UInt8
@inlinable @inline(__always)
internal init(_value: UInt8) {
assert(_value < _Bitmap.capacity || _value == .max)
self._value = _value
}
}
extension _Bucket {
@inlinable @inline(__always)
internal var value: UInt { UInt(truncatingIfNeeded: _value) }
@inlinable @inline(__always)
internal init(_ value: UInt) {
assert(value < _Bitmap.capacity || value == .max)
self._value = UInt8(truncatingIfNeeded: value)
}
}
extension _Bucket {
@inlinable @inline(__always)
static var bitWidth: Int { _Bitmap.capacity.trailingZeroBitCount }
@inlinable @inline(__always)
static var bitMask: UInt { UInt(bitPattern: _Bitmap.capacity) &- 1 }
@inlinable @inline(__always)
static var invalid: _Bucket { _Bucket(_value: .max) }
@inlinable @inline(__always)
var isInvalid: Bool { _value == .max }
}
extension _Bucket: Equatable {
@inlinable @inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left._value == right._value
}
}
extension _Bucket: Comparable {
@inlinable @inline(__always)
internal static func <(left: Self, right: Self) -> Bool {
left._value < right._value
}
}
extension _Bucket: CustomStringConvertible {
@usableFromInline
internal var description: String {
String(_value, radix: _Bitmap.capacity)
}
}
@@ -0,0 +1,94 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// An abstract representation of a hash value.
@usableFromInline
@frozen
internal struct _Hash {
@usableFromInline
internal var value: UInt
@inlinable
internal init<Key: Hashable>(_ key: Key) {
let hashValue = key._rawHashValue(seed: 0)
self.value = UInt(bitPattern: hashValue)
}
@inlinable
internal init(_value: UInt) {
self.value = _value
}
}
extension _Hash: Equatable {
@inlinable @inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
}
extension _Hash: CustomStringConvertible {
@usableFromInline
internal var description: String {
// 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 = _HashLevel.limit
let path = String(repeating: "0", count: Swift.max(0, c - p.count)) + p
return String(path.reversed())
}
}
extension _Hash {
@inlinable @inline(__always)
internal static var bitWidth: Int { UInt.bitWidth }
}
extension _Hash {
@inlinable
internal subscript(_ level: _HashLevel) -> _Bucket {
get {
assert(!level.isAtBottom)
return _Bucket((value &>> level.shift) & _Bucket.bitMask)
}
set {
let mask = _Bucket.bitMask &<< level.shift
self.value &= ~mask
self.value |= newValue.value &<< level.shift
}
}
}
extension _Hash {
@inlinable
internal static var emptyPath: _Hash {
_Hash(_value: 0)
}
@inlinable
internal func appending(_ bucket: _Bucket, at level: _HashLevel) -> Self {
assert(value >> level.shift == 0)
var copy = self
copy[level] = bucket
return copy
}
@inlinable
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
let v1 = self.value &<< s
let v2 = self.value &<< s
return v1 == v2
}
}
@@ -0,0 +1,101 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// Identifies a particular level within the hash tree.
///
/// Hash trees have a maximum depth of ⎡`UInt.bitWidth / _Bucket.bitWidth`⎤, so
/// the level always fits in an `UInt8` value.
@usableFromInline
@frozen
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`.
@usableFromInline
internal var _shift: UInt8
@inlinable @inline(__always)
init(_shift: UInt8) {
self._shift = _shift
}
@inlinable @inline(__always)
init(shift: UInt) {
assert(shift <= UInt8.max)
self._shift = UInt8(truncatingIfNeeded: shift)
}
@inlinable @inline(__always)
init(depth: Int) {
assert(depth > 0 && depth < _HashLevel.limit)
self.init(shift: UInt(bitPattern: depth * _Bitmap.bitWidth))
}
}
extension _HashLevel {
@inlinable @inline(__always)
internal static var limit: Int {
(_Hash.bitWidth + _Bitmap.bitWidth - 1) / _Bitmap.bitWidth
}
@inlinable @inline(__always)
internal static var _step: UInt8 {
UInt8(truncatingIfNeeded: _Bitmap.bitWidth)
}
@inlinable @inline(__always)
internal static var top: _HashLevel {
_HashLevel(shift: 0)
}
/// 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`.
@inlinable @inline(__always)
internal var shift: UInt { UInt(truncatingIfNeeded: _shift) }
@inlinable @inline(__always)
internal var isAtRoot: Bool { _shift == 0 }
@inlinable @inline(__always)
internal var isAtBottom: Bool { _shift >= UInt.bitWidth }
@inlinable @inline(__always)
internal var depth: Int {
(Int(bitPattern: shift) + _Bitmap.bitWidth - 1) / _Bitmap.bitWidth
}
@inlinable @inline(__always)
internal func descend() -> _HashLevel {
// FIXME: Consider returning nil when we run out of bits
_HashLevel(_shift: _shift &+ Self._step)
}
@inlinable @inline(__always)
internal func ascend() -> _HashLevel {
assert(!isAtRoot)
return _HashLevel(_shift: _shift &- Self._step)
}
}
extension _HashLevel: Equatable {
@inlinable @inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left._shift == right._shift
}
}
extension _HashLevel: Comparable {
@inlinable @inline(__always)
internal static func <(left: Self, right: Self) -> Bool {
left._shift < right._shift
}
}
@@ -0,0 +1,360 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNode {
@usableFromInline
@frozen
internal struct Builder {
@usableFromInline typealias Element = _HashNode.Element
@usableFromInline
@frozen
internal enum Kind {
case empty
case item(Element, at: _Bucket)
case node(_HashNode)
case collisionNode(_HashNode)
}
@usableFromInline
internal var level: _HashLevel
@usableFromInline
internal var kind: Kind
@inlinable
internal init(_ level: _HashLevel, _ kind: Kind) {
self.level = level
self.kind = kind
}
}
}
extension _HashNode.Builder {
@usableFromInline
internal func dump() {
let head = "Builder(level: \(level.depth), kind: "
switch self.kind {
case .empty:
print(head + "empty)")
case .item(let item, at: let bucket):
print(head + "item(\(_HashNode._itemString(for: item)), at: \(bucket))")
case .node(let node):
print(head + "node)")
node.dump()
case .collisionNode(let node):
print(head + "collisionNode)")
node.dump()
}
}
}
extension _HashNode.Builder {
@inlinable @inline(__always)
internal static func empty(_ level: _HashLevel) -> Self {
Self(level, .empty)
}
@inlinable @inline(__always)
internal static func item(
_ level: _HashLevel, _ item: __owned Element, at bucket: _Bucket
) -> Self {
Self(level, .item(item, at: bucket))
}
@inlinable @inline(__always)
internal static func node(
_ level: _HashLevel, _ node: __owned _HashNode
) -> Self {
assert(!node.isCollisionNode)
return Self(level, .node(node))
}
@inlinable @inline(__always)
internal static func collisionNode(
_ level: _HashLevel, _ node: __owned _HashNode
) -> Self {
assert(node.isCollisionNode)
return Self(level, .collisionNode(node))
}
}
extension _HashNode.Builder {
@inlinable
internal var count: Int {
switch kind {
case .empty:
return 0
case .item:
return 1
case .node(let node):
return node.count
case .collisionNode(let node):
return node.count
}
}
@inlinable
internal var isEmpty: Bool {
guard case .empty = kind else { return false }
return true
}
}
extension _HashNode.Builder {
@inlinable
internal init(_ level: _HashLevel, _ node: _HashNode) {
self.level = level
if node.count == 0 {
kind = .empty
} else if node.isCollisionNode {
assert(!node.hasSingletonItem)
kind = .collisionNode(node)
} else if node.hasSingletonItem {
kind = node.read { .item($0[item: .zero], at: $0.itemMap.first!) }
} else {
kind = .node(node)
}
}
@inlinable
internal __consuming func finalize(_ level: _HashLevel) -> _HashNode {
assert(level.isAtRoot && self.level.isAtRoot)
switch kind {
case .empty:
return ._emptyNode()
case .item(let item, let bucket):
return ._regularNode(item, bucket)
case .node(let node):
return node
case .collisionNode(let node):
return node
}
}
}
extension _HashNode {
@inlinable
internal mutating func applyReplacement(
_ level: _HashLevel,
_ replacement: Builder
) -> Element? {
assert(level == replacement.level)
switch replacement.kind {
case .empty:
self = ._emptyNode()
case .node(let n), .collisionNode(let n):
self = n
case .item(let item, let bucket):
guard level.isAtRoot else {
self = ._emptyNode()
return item
}
self = ._regularNode(item, bucket)
}
return nil
}
}
extension _HashNode.Builder {
@inlinable
internal mutating func addNewCollision(
_ level: _HashLevel, _ newItem: __owned Element, _ hash: _Hash
) {
assert(level == self.level)
switch kind {
case .empty:
kind = .item(newItem, at: hash[level])
case .item(let oldItem, at: let bucket):
assert(hash[level] == bucket)
let node = _HashNode._collisionNode(hash, oldItem, newItem)
kind = .collisionNode(node)
case .collisionNode(var node):
kind = .empty
assert(node.isCollisionNode)
assert(hash == node.collisionHash)
_ = node.ensureUniqueAndAppendCollision(isUnique: true, newItem)
kind = .collisionNode(node)
case .node:
fatalError()
}
}
@inlinable
internal mutating func addNewItem(
_ level: _HashLevel, _ newItem: __owned Element, at newBucket: _Bucket
) {
assert(level == self.level)
switch kind {
case .empty:
kind = .item(newItem, at: newBucket)
case .item(let oldItem, let oldBucket):
assert(oldBucket != newBucket)
let node = _HashNode._regularNode(oldItem, oldBucket, newItem, newBucket)
kind = .node(node)
case .node(var node):
kind = .empty
let isUnique = node.isUnique()
node.ensureUniqueAndInsertItem(isUnique: isUnique, newItem, at: newBucket)
kind = .node(node)
case .collisionNode(var node):
// Expansion
assert(!level.isAtBottom)
self.kind = .empty
node = _HashNode._regularNode(
newItem, newBucket, node, node.collisionHash[level])
kind = .node(node)
}
}
@inlinable
internal mutating func addNewChildNode(
_ level: _HashLevel, _ newChild: __owned _HashNode, at newBucket: _Bucket
) {
assert(level == self.level)
switch self.kind {
case .empty:
if newChild.isCollisionNode {
// Compression
assert(!level.isAtBottom)
self.kind = .collisionNode(newChild)
} else {
self.kind = .node(._regularNode(newChild, newBucket))
}
case let .item(oldItem, oldBucket):
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: _HashNode.spaceForNewChild)
node.insertChild(newChild, newBucket)
self.kind = .node(node)
case .collisionNode(var node):
// Expansion
self.kind = .empty
assert(!level.isAtBottom)
node = _HashNode._regularNode(
node, node.collisionHash[level], newChild, newBucket)
self.kind = .node(node)
}
}
@inlinable
internal mutating func addNewChildBranch(
_ level: _HashLevel, _ newChild: __owned Self, at newBucket: _Bucket
) {
assert(level == self.level)
assert(newChild.level == self.level.descend())
switch newChild.kind {
case .empty:
break
case .item(let newItem, _):
self.addNewItem(level, newItem, at: newBucket)
case .node(let newNode), .collisionNode(let newNode):
self.addNewChildNode(level, newNode, at: newBucket)
}
}
@inlinable
internal static func childBranch(
_ level: _HashLevel, _ child: Self, at bucket: _Bucket
) -> Self {
assert(child.level == level.descend())
switch child.kind {
case .empty:
return self.empty(level)
case .item(let item, _):
return self.item(level, item, at: bucket)
case .node(let n):
return self.node(level, ._regularNode(n, bucket))
case .collisionNode(let node):
// Compression
assert(!level.isAtBottom)
return self.collisionNode(level, node)
}
}
}
extension _HashNode.Builder {
@inlinable
internal mutating func copyCollisions(
from source: _HashNode.UnsafeHandle,
upTo end: _HashSlot
) {
assert(isEmpty)
assert(source.isCollisionNode)
assert(end < source.itemsEndSlot)
let h = source.collisionHash
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: _HashLevel,
from source: _HashNode.UnsafeHandle,
upTo end: _Bucket
) {
assert(level == self.level)
assert(isEmpty)
assert(!source.isCollisionNode)
for (b, s) in source.itemMap.intersection(_Bitmap(upTo: end)) {
self.addNewItem(level, source[item: s], at: b)
}
}
@inlinable
internal mutating func copyItemsAndChildren(
_ level: _HashLevel,
from source: _HashNode.UnsafeHandle,
upTo end: _Bucket
) {
assert(level == self.level)
assert(isEmpty)
assert(!source.isCollisionNode)
for (b, s) in source.itemMap {
self.addNewItem(level, source[item: s], at: b)
}
for (b, s) in source.childMap.intersection(_Bitmap(upTo: end)) {
self.addNewChildNode(level, source[child: s], at: b)
}
}
}
extension _HashNode.Builder {
@inlinable
internal func mapValues<Value2>(
_ transform: (Element) -> Value2
) -> _HashNode<Key, Value2>.Builder {
switch kind {
case .empty:
return .empty(level)
case let .item(item, at: bucket):
let value = transform(item)
return .item(level, (item.key, value), at: bucket)
case let .node(node):
return .node(level, node.mapValues(transform))
case let .collisionNode(node):
return .collisionNode(level, node.mapValues(transform))
}
}
@inlinable
internal func mapValuesToVoid() -> _HashNode<Key, Void>.Builder {
if Value.self == Void.self {
return unsafeBitCast(self, to: _HashNode<Key, Void>.Builder.self)
}
return mapValues { _ in () }
}
}
@@ -0,0 +1,119 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
extension _HashNode {
@usableFromInline
internal func dump(
iterationOrder: Bool = false,
limit: Int = Int.max,
firstPrefix: String = "",
restPrefix: String = "",
depth: Int = 0
) {
read {
$0.dump(
iterationOrder: iterationOrder,
limit: limit,
extra: "count: \(count), ",
firstPrefix: firstPrefix,
restPrefix: restPrefix,
depth: depth)
}
}
}
extension _HashNode.Storage {
@usableFromInline
final internal func dump(iterationOrder: Bool = false) {
UnsafeHandle.read(self) { $0.dump(iterationOrder: iterationOrder) }
}
}
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 _HashNode.UnsafeHandle {
internal func _itemString(at slot: _HashSlot) -> String {
let item = self[item: slot]
return _HashNode._itemString(for: item)
}
@usableFromInline
internal func dump(
iterationOrder: Bool = false,
limit: Int = .max,
extra: String = "",
firstPrefix: String = "",
restPrefix: String = "",
depth: Int = 0
) {
var firstPrefix = firstPrefix
var restPrefix = restPrefix
if iterationOrder && depth == 0 {
firstPrefix += "@"
restPrefix += "@"
}
if iterationOrder {
firstPrefix += " "
}
print("""
\(firstPrefix)\(isCollisionNode ? "CollisionNode" : "Node")(\
at: \(_addressString(for: _header)), \
\(isCollisionNode ? "hash: \(collisionHash), " : "")\
\(extra)\
byteCapacity: \(byteCapacity), \
freeBytes: \(bytesFree))
""")
guard limit > 0 else { return }
if iterationOrder {
for slot in stride(from: .zero, to: itemsEndSlot, by: 1) {
print(" \(restPrefix)[\(slot)] \(_itemString(at: slot))")
}
for slot in stride(from: .zero, to: childrenEndSlot, by: 1) {
self[child: slot].dump(
iterationOrder: true,
limit: limit - 1,
firstPrefix: " \(restPrefix).\(slot)",
restPrefix: " \(restPrefix).\(slot)",
depth: depth + 1)
}
}
else if isCollisionNode {
for slot in stride(from: .zero, to: itemsEndSlot, by: 1) {
print("\(restPrefix)[\(slot)] \(_itemString(at: slot))")
}
} else {
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))"
if itemMap.contains(bucket) {
print("\(restPrefix) \(bucketStr) \(_itemString(at: itemSlot))")
itemSlot = itemSlot.next()
} else if childMap.contains(bucket) {
self[child: childSlot].dump(
iterationOrder: false,
limit: limit - 1,
firstPrefix: "\(restPrefix) \(bucketStr) ",
restPrefix: "\(restPrefix) ",
depth: depth + 1)
childSlot = childSlot.next()
}
}
}
}
}
@@ -0,0 +1,259 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
extension _HashNode {
@inlinable @inline(__always)
internal static func _emptyNode() -> _HashNode {
_HashNode(storage: _emptySingleton, count: 0)
}
@inlinable
internal static func _collisionNode(
_ hash: _Hash,
_ item1: __owned Element,
_ item2: __owned Element
) -> _HashNode {
let node = _HashNode.allocateCollision(count: 2, hash) { items in
items.initializeElement(at: 1, to: item1)
items.initializeElement(at: 0, to: item2)
}.node
node._invariantCheck()
return node
}
@inlinable
internal static func _collisionNode(
_ hash: _Hash,
_ item1: __owned Element,
_ inserter2: (UnsafeMutablePointer<Element>) -> Void
) -> _HashNode {
let node = _HashNode.allocateCollision(count: 2, hash) { items in
items.initializeElement(at: 1, to: item1)
inserter2(items.baseAddress.unsafelyUnwrapped)
}.node
node._invariantCheck()
return node
}
@inlinable
internal static func _regularNode(
_ item: __owned Element,
_ bucket: _Bucket
) -> _HashNode {
let r = _HashNode.allocate(
itemMap: _Bitmap(bucket),
childMap: .empty,
count: 1
) { children, items in
assert(items.count == 1 && children.count == 0)
items.initializeElement(at: 0, to: item)
}
r.node._invariantCheck()
return r.node
}
@inlinable
internal static func _regularNode(
_ item1: __owned Element,
_ bucket1: _Bucket,
_ item2: __owned Element,
_ bucket2: _Bucket
) -> _HashNode {
_regularNode(
item1, bucket1,
{ $0.initialize(to: item2) }, bucket2).node
}
@inlinable
internal static func _regularNode(
_ item1: __owned Element,
_ bucket1: _Bucket,
_ inserter2: (UnsafeMutablePointer<Element>) -> Void,
_ bucket2: _Bucket
) -> (node: _HashNode, slot1: _HashSlot, slot2: _HashSlot) {
assert(bucket1 != bucket2)
let r = _HashNode.allocate(
itemMap: _Bitmap(bucket1, bucket2),
childMap: .empty,
count: 2
) { 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 (_HashSlot(i2), _HashSlot(i1)) // Note: swapped
}
r.node._invariantCheck()
return (r.node, r.result.0, r.result.1)
}
@inlinable
internal static func _regularNode(
_ child: __owned _HashNode,
_ bucket: _Bucket
) -> _HashNode {
let r = _HashNode.allocate(
itemMap: .empty,
childMap: _Bitmap(bucket),
count: child.count
) { children, items in
assert(items.count == 0 && children.count == 1)
children.initializeElement(at: 0, to: child)
}
r.node._invariantCheck()
return r.node
}
@inlinable
internal static func _regularNode(
_ item: __owned Element,
_ itemBucket: _Bucket,
_ child: __owned _HashNode,
_ childBucket: _Bucket
) -> _HashNode {
_regularNode(
{ $0.initialize(to: item) }, itemBucket,
child, childBucket)
}
@inlinable
internal static func _regularNode(
_ inserter: (UnsafeMutablePointer<Element>) -> Void,
_ itemBucket: _Bucket,
_ child: __owned _HashNode,
_ childBucket: _Bucket
) -> _HashNode {
assert(itemBucket != childBucket)
let r = _HashNode.allocate(
itemMap: _Bitmap(itemBucket),
childMap: _Bitmap(childBucket),
count: child.count &+ 1
) { children, items in
assert(items.count == 1 && children.count == 1)
inserter(items.baseAddress.unsafelyUnwrapped)
children.initializeElement(at: 0, to: child)
}
r.node._invariantCheck()
return r.node
}
@inlinable
internal static func _regularNode(
_ child1: __owned _HashNode,
_ child1Bucket: _Bucket,
_ child2: __owned _HashNode,
_ child2Bucket: _Bucket
) -> _HashNode {
assert(child1Bucket != child2Bucket)
let r = _HashNode.allocate(
itemMap: .empty,
childMap: _Bitmap(child1Bucket, child2Bucket),
count: child1.count &+ child2.count
) { children, items in
assert(items.count == 0 && children.count == 2)
children.initializeElement(at: 0, to: child1)
children.initializeElement(at: 1, to: child2)
}
r.node._invariantCheck()
return r.node
}
}
extension _HashNode {
@inlinable
internal static func build(
level: _HashLevel,
item1: __owned Element,
_ hash1: _Hash,
item2 inserter2: (UnsafeMutablePointer<Element>) -> Void,
_ hash2: _Hash
) -> (top: _HashNode, leaf: _UnmanagedHashNode, slot1: _HashSlot, slot2: _HashSlot) {
assert(hash1.isEqual(to: hash2, upTo: level.ascend()))
if hash1 == hash2 {
let top = _collisionNode(hash1, item1, inserter2)
return (top, top.unmanaged, _HashSlot(0), _HashSlot(1))
}
let r = _build(
level: level, item1: item1, hash1, item2: inserter2, hash2)
return (r.top, r.leaf, r.slot1, r.slot2)
}
@inlinable
internal static func _build(
level: _HashLevel,
item1: __owned Element,
_ hash1: _Hash,
item2 inserter2: (UnsafeMutablePointer<Element>) -> Void,
_ hash2: _Hash
) -> (top: _HashNode, leaf: _UnmanagedHashNode, slot1: _HashSlot, slot2: _HashSlot) {
assert(hash1 != hash2)
let b1 = hash1[level]
let b2 = hash2[level]
guard b1 == b2 else {
let r = _regularNode(item1, b1, inserter2, b2)
return (r.node, r.node.unmanaged, r.slot1, r.slot2)
}
let r = _build(
level: level.descend(),
item1: item1, hash1,
item2: inserter2, hash2)
return (_regularNode(r.top, b1), r.leaf, r.slot1, r.slot2)
}
@inlinable
internal static func build(
level: _HashLevel,
item1 inserter1: (UnsafeMutablePointer<Element>) -> Void,
_ hash1: _Hash,
child2: __owned _HashNode,
_ hash2: _Hash
) -> (top: _HashNode, leaf: _UnmanagedHashNode, slot1: _HashSlot, slot2: _HashSlot) {
assert(child2.isCollisionNode)
assert(hash1 != hash2)
let b1 = hash1[level]
let b2 = hash2[level]
if b1 == b2 {
let node = build(
level: level.descend(),
item1: inserter1, hash1,
child2: child2, hash2)
return (_regularNode(node.top, b1), node.leaf, node.slot1, node.slot2)
}
let node = _regularNode(inserter1, hash1[level], child2, hash2[level])
return (node, node.unmanaged, .zero, .zero)
}
@inlinable
internal static func build(
level: _HashLevel,
child1: __owned _HashNode,
_ hash1: _Hash,
child2: __owned _HashNode,
_ hash2: _Hash
) -> _HashNode {
assert(child1.isCollisionNode)
assert(child2.isCollisionNode)
assert(hash1 != hash2)
let b1 = hash1[level]
let b2 = hash2[level]
guard b1 == b2 else {
return _regularNode(child1, b1, child2, b2)
}
let node = build(
level: level.descend(),
child1: child1, hash1,
child2: child2, hash2)
return _regularNode(node, b1)
}
}
@@ -0,0 +1,107 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNodeHeader {
#if COLLECTIONS_INTERNAL_CHECKS
@usableFromInline @inline(never)
internal func _invariantCheck() {
precondition(bytesFree <= byteCapacity)
if isCollisionNode {
precondition(itemMap == childMap)
precondition(!itemMap.isEmpty)
} else {
precondition(itemMap.intersection(childMap).isEmpty)
}
}
#else
@inlinable @inline(__always)
internal func _invariantCheck() {}
#endif
}
extension _HashNode {
#if COLLECTIONS_INTERNAL_CHECKS
@usableFromInline @inline(never)
internal func _invariantCheck() {
raw.storage.header._invariantCheck()
read {
let itemBytes = $0.itemCount * MemoryLayout<Element>.stride
if $0.isCollisionNode {
let hashBytes = MemoryLayout<_Hash>.stride
assert($0.itemCount >= 1)
assert($0.childCount == 0)
assert(itemBytes + $0.bytesFree + hashBytes == $0.byteCapacity)
assert($0.collisionHash == _Hash($0[item: .zero].key))
} else {
let childBytes = $0.childCount * MemoryLayout<_HashNode>.stride
assert(itemBytes + $0.bytesFree + childBytes == $0.byteCapacity)
}
let actualCount = $0.children.reduce($0.itemCount, { $0 + $1.count })
assert(actualCount == self.count)
}
}
#else
@inlinable @inline(__always)
internal func _invariantCheck() {}
#endif
@inlinable @inline(__always)
public func _fullInvariantCheck() {
self._fullInvariantCheck(.top, .emptyPath)
}
#if COLLECTIONS_INTERNAL_CHECKS
@inlinable @inline(never)
internal func _fullInvariantCheck(_ level: _HashLevel, _ path: _Hash) {
_invariantCheck()
read {
precondition(level.isAtRoot || !hasSingletonItem)
precondition(!isAtrophied)
if $0.isCollisionNode {
precondition(count == $0.itemCount)
precondition(count > 0)
let hash = $0.collisionHash
precondition(
hash.isEqual(to: path, upTo: level),
"Misplaced collision node: \(path) isn't a prefix of \(hash)")
for item in $0.reverseItems {
precondition(_Hash(item.key) == hash)
}
}
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)
if $0.itemMap.contains(bucket) {
let key = $0[item: itemSlot].key
let hash = _Hash(key)
precondition(
hash.isEqual(to: path, upTo: level.descend()),
"Misplaced key '\(key)': \(path) isn't a prefix of \(hash)")
itemSlot = itemSlot.next()
}
if $0.hasChildren && $0.childMap.contains(bucket) {
$0[child: childSlot]._fullInvariantCheck(level.descend(), path)
childSlot = childSlot.next()
}
}
}
}
#else
@inlinable @inline(__always)
internal func _fullInvariantCheck(_ level: _HashLevel, _ path: _Hash) {}
#endif
}
@@ -0,0 +1,269 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// MARK: Node-level lookup operations
extension _HashNode {
@inlinable
internal func find(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (descend: Bool, slot: _HashSlot)? {
read { $0.find(level, key, hash) }
}
}
extension _HashNode.UnsafeHandle {
@inlinable
internal func find(
_ 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 }
return (false, r.slot)
}
let bucket = hash[level]
if itemMap.contains(bucket) {
let slot = itemMap.slot(of: bucket)
guard self[item: slot].key == key else { return nil }
return (false, slot)
}
if childMap.contains(bucket) {
let slot = childMap.slot(of: bucket)
return (true, slot)
}
return nil
}
@inlinable @inline(never)
internal func _findInCollision(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (code: Int, slot: _HashSlot) {
assert(isCollisionNode)
if !level.isAtBottom {
if hash != self.collisionHash { return (2, .zero) }
}
// Note: this searches the items in reverse insertion order.
guard let slot = reverseItems.firstIndex(where: { $0.key == key })
else { return (1, self.itemsEndSlot) }
return (0, _HashSlot(itemCount &- 1 &- slot))
}
}
/// Represents the results of a lookup operation within a single node of a hash
/// tree. This enumeration captures all of the different cases that need to be
/// covered if we wanted to insert a new item into the tree.
///
/// For simple read-only lookup operations (and removals) some of the cases are
/// equivalent: `.notFound`, .newCollision` and `expansion` all represent the
/// same logical outcome: the key we're looking for is not present in this
/// subtree.
@usableFromInline
@frozen
internal enum _FindResult {
/// The item we're looking for is stored directly in this node, at the
/// bucket / item slot identified in the payload.
///
/// If the current node is a collision node, then the bucket value is
/// set to `_Bucket.invalid`.
case found(_Bucket, _HashSlot)
/// The item we're looking for is not currently inside the subtree rooted at
/// this node.
///
/// If we wanted to insert it, then its correct slot is within this node
/// at the specified bucket / item slot. (Which is currently empty.)
///
/// When the node is a collision node, the `insertCollision` case is returned
/// instead of this one.
case insert(_Bucket, _HashSlot)
/// The item we're looking for is not currently inside the subtree rooted at
/// this collision node.
///
/// If we wanted to insert it, then it needs to be appended to the items
/// buffer.
case appendCollision
/// The item we're looking for is not currently inside the subtree rooted at
/// this node.
///
/// If we wanted to insert it, then it would need to be stored in this node
/// at the specified bucket / item slot. However, that bucket is already
/// occupied by another item, so the insertion would need to involve replacing
/// it with a new child node.
///
/// (This case is never returned if the current node is a collision node.)
case spawnChild(_Bucket, _HashSlot)
/// The item we're looking for is not in this subtree.
///
/// However, the item doesn't belong in this subtree at all. This is an
/// irregular case that can only happen with (compressed) hash collision nodes
/// whose (otherwise empty) ancestors got eliminated, so they appear further
/// up in the tree than what their (logical) level would indicate.
///
/// If we wanted to insert a new item with this key, then we'd need to create
/// (one or more) new parent nodes above this node, pushing this collision
/// node further down the tree. (This undoes the compression by expanding
/// the collision node's path, hence the name of the enum case.)
///
/// (This case is never returned if the current node is a regular node.)
case expansion
/// The item we're looking for is not directly stored in this node, but it
/// might be somewhere in the subtree rooted at the child at the given
/// bucket & slot.
///
/// (This case is never returned if the current node is a collision node.)
case descend(_Bucket, _HashSlot)
}
extension _HashNode {
@inlinable
internal func findForInsertion(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> _FindResult {
read { $0.findForInsertion(level, key, hash) }
}
}
extension _HashNode.UnsafeHandle {
@inlinable
internal func findForInsertion(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> _FindResult {
guard !isCollisionNode else {
let r = _findInCollision(level, key, hash)
if r.code == 0 {
return .found(.invalid, r.slot)
}
if r.code == 1 {
return .appendCollision
}
assert(r.code == 2)
return .expansion
}
let bucket = hash[level]
if itemMap.contains(bucket) {
let slot = itemMap.slot(of: bucket)
if self[item: slot].key == key {
return .found(bucket, slot)
}
return .spawnChild(bucket, slot)
}
if childMap.contains(bucket) {
let slot = childMap.slot(of: bucket)
return .descend(bucket, slot)
}
let slot = itemMap.slot(of: bucket)
return .insert(bucket, slot)
}
}
// MARK: Subtree-level lookup operations
extension _HashNode {
@inlinable
internal func get(_ level: _HashLevel, _ key: Key, _ hash: _Hash) -> Value? {
var node = unmanaged
var level = level
while true {
let r = UnsafeHandle.read(node) { $0.find(level, key, hash) }
guard let r = r else {
return nil
}
guard r.descend else {
return UnsafeHandle.read(node) { $0[item: r.slot].value }
}
node = node.unmanagedChild(at: r.slot)
level = level.descend()
}
}
}
extension _HashNode {
@inlinable
internal func containsKey(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> Bool {
var node = unmanaged
var level = level
while true {
let r = UnsafeHandle.read(node) { $0.find(level, key, hash) }
guard let r = r else { return false }
guard r.descend else { return true }
node = node.unmanagedChild(at: r.slot)
level = level.descend()
}
}
}
extension _HashNode {
@inlinable
internal func lookup(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (node: _UnmanagedHashNode, slot: _HashSlot)? {
var node = unmanaged
var level = level
while true {
let r = UnsafeHandle.read(node) { $0.find(level, key, hash) }
guard let r = r else {
return nil
}
guard r.descend else {
return (node, r.slot)
}
node = node.unmanagedChild(at: r.slot)
level = level.descend()
}
}
}
extension _HashNode {
@inlinable
internal func position(
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 }
return read { h in
let children = h.children
let p = children[r.slot.value]
.position(forKey: key, level.descend(), hash)
guard let p = p else { return nil }
let c = h.itemCount &+ p
return children[..<r.slot.value].reduce(into: c) { $0 &+= $1.count }
}
}
@inlinable
internal func item(position: Int) -> Element {
assert(position >= 0 && position < self.count)
return read {
var itemsToSkip = position
let itemCount = $0.itemCount
if itemsToSkip < itemCount {
return $0[item: _HashSlot(itemsToSkip)]
}
itemsToSkip -= itemCount
let children = $0.children
for i in children.indices {
if itemsToSkip < children[i].count {
return children[i].item(position: itemsToSkip)
}
itemsToSkip -= children[i].count
}
fatalError("Inconsistent tree")
}
}
}
@@ -0,0 +1,117 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// MARK: Node-level insertion operations
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.
///
/// `itemMap` must not already reflect the insertion at the time this
/// function is called. This method does not update `itemMap`.
///
/// - Returns: an unsafe mutable pointer to uninitialized memory that is
/// ready to store the new item. It is the caller's responsibility to
/// initialize this memory.
@inlinable
internal func _makeRoomForNewItem(
at slot: _HashSlot, _ bucket: _Bucket
) -> UnsafeMutablePointer<Element> {
assertMutable()
let c = itemCount
assert(slot.value <= c)
let stride = MemoryLayout<Element>.stride
assert(bytesFree >= stride)
bytesFree &-= stride
let start = _memory
.advanced(by: byteCapacity &- (c &+ 1) &* stride)
.bindMemory(to: Element.self, capacity: 1)
let prefix = c &- slot.value
start.moveInitialize(from: start + 1, count: prefix)
if bucket.isInvalid {
assert(isCollisionNode)
collisionCount &+= 1
} else {
assert(!itemMap.contains(bucket))
assert(!childMap.contains(bucket))
itemMap.insert(bucket)
assert(itemMap.slot(of: bucket) == slot)
}
return start + prefix
}
/// Insert `child` at `slot`. There must be enough free space in the node
/// to fit the new child.
///
/// `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 _HashNode, at slot: _HashSlot) {
assertMutable()
assert(!isCollisionNode)
let c = childMap.count
assert(slot.value <= c)
let stride = MemoryLayout<_HashNode>.stride
assert(bytesFree >= stride)
bytesFree &-= stride
_memory.bindMemory(to: _HashNode.self, capacity: c &+ 1)
let q = _childrenStart + slot.value
(q + 1).moveInitialize(from: q, count: c &- slot.value)
q.initialize(to: child)
}
}
extension _HashNode {
@inlinable @inline(__always)
internal mutating func insertItem(
_ item: __owned Element, at bucket: _Bucket
) {
let slot = read { $0.itemMap.slot(of: bucket) }
self.insertItem(item, at: slot, bucket)
}
@inlinable @inline(__always)
internal mutating func insertItem(
_ item: __owned Element, at slot: _HashSlot, _ bucket: _Bucket
) {
self.count &+= 1
update {
let p = $0._makeRoomForNewItem(at: slot, bucket)
p.initialize(to: item)
}
}
/// Insert `child` in `bucket`. There must be enough free space in the
/// node to fit the new child.
@inlinable
internal mutating func insertChild(
_ child: __owned _HashNode, _ bucket: _Bucket
) {
count &+= child.count
update {
assert(!$0.isCollisionNode)
assert(!$0.itemMap.contains(bucket))
assert(!$0.childMap.contains(bucket))
let slot = $0.childMap.slot(of: bucket)
$0._insertChild(child, at: slot)
$0.childMap.insert(bucket)
}
}
}
@@ -0,0 +1,151 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// MARK: Node-level removal operations
extension _HashNode.UnsafeHandle {
/// Remove and return the item at `slot`, increasing the amount of free
/// space available in the node.
///
/// `itemMap` must not yet reflect the removal at the time this
/// function is called. This method does not update `itemMap`.
@inlinable
internal func _removeItem<R>(
at slot: _HashSlot,
by remover: (UnsafeMutablePointer<Element>) -> R
) -> R {
assertMutable()
let c = itemCount
assert(slot.value < c)
let stride = MemoryLayout<Element>.stride
bytesFree &+= stride
let start = _memory
.advanced(by: byteCapacity &- stride &* c)
.assumingMemoryBound(to: Element.self)
let prefix = c &- 1 &- slot.value
let q = start + prefix
defer {
(start + 1).moveInitialize(from: start, count: prefix)
}
return remover(q)
}
/// Remove and return the child at `slot`, increasing the amount of free
/// space available in the node.
///
/// `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: _HashSlot) -> _HashNode {
assertMutable()
assert(!isCollisionNode)
let count = childCount
assert(slot.value < count)
bytesFree &+= MemoryLayout<_HashNode>.stride
let q = _childrenStart + slot.value
let child = q.move()
q.moveInitialize(from: q + 1, count: count &- 1 &- slot.value)
return child
}
}
extension _HashNode {
@inlinable
internal mutating func removeItem(
at bucket: _Bucket
) -> Element {
let slot = read { $0.itemMap.slot(of: bucket) }
return removeItem(at: bucket, slot, by: { $0.move() })
}
@inlinable
internal mutating func removeItem(
at bucket: _Bucket, _ slot: _HashSlot
) -> Element {
removeItem(at: bucket, slot, by: { $0.move() })
}
/// Remove the item at `slot`, increasing the amount of free
/// space available in the node.
///
/// The closure `remove` is called to perform the deinitialization of the
/// storage slot corresponding to the item to be removed.
@inlinable
internal mutating func removeItem<R>(
at bucket: _Bucket, _ slot: _HashSlot,
by remover: (UnsafeMutablePointer<Element>) -> R
) -> R {
defer { _invariantCheck() }
assert(count > 0)
count &-= 1
return update {
let old = $0._removeItem(at: slot, by: remover)
if $0.isCollisionNode {
assert(slot.value < $0.collisionCount)
$0.collisionCount &-= 1
} else {
assert($0.itemMap.contains(bucket))
assert($0.itemMap.slot(of: bucket) == slot)
$0.itemMap.remove(bucket)
}
return old
}
}
@inlinable
internal mutating func removeChild(
at bucket: _Bucket, _ slot: _HashSlot
) -> _HashNode {
assert(!isCollisionNode)
let child: _HashNode = update {
assert($0.childMap.contains(bucket))
assert($0.childMap.slot(of: bucket) == slot)
let child = $0._removeChild(at: slot)
$0.childMap.remove(bucket)
return child
}
assert(self.count >= child.count)
self.count &-= child.count
return child
}
@inlinable
internal mutating func removeSingletonItem() -> Element {
defer { _invariantCheck() }
assert(count == 1)
count = 0
return update {
assert($0.hasSingletonItem)
let old = $0._removeItem(at: .zero) { $0.move() }
$0.clear()
return old
}
}
@inlinable
internal mutating func removeSingletonChild() -> _HashNode {
defer { _invariantCheck() }
let child: _HashNode = update {
assert($0.hasSingletonChild)
let child = $0._removeChild(at: .zero)
$0.childMap = .empty
return child
}
assert(self.count == child.count)
self.count = 0
return child
}
}
@@ -0,0 +1,90 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNode {
@inlinable
internal mutating func replaceItem(
at bucket: _Bucket, _ slot: _HashSlot, with item: __owned Element
) {
update {
assert($0.isCollisionNode || $0.itemMap.contains(bucket))
assert($0.isCollisionNode || slot == $0.itemMap.slot(of: bucket))
assert(!$0.isCollisionNode || slot.value < $0.collisionCount)
$0[item: slot] = item
}
}
@inlinable
internal mutating func replaceChild(
at bucket: _Bucket, with child: __owned _HashNode
) -> Int {
let slot = read { $0.childMap.slot(of: bucket) }
return replaceChild(at: bucket, slot, with: child)
}
@inlinable
internal mutating func replaceChild(
at bucket: _Bucket, _ slot: _HashSlot, with child: __owned _HashNode
) -> Int {
let delta: Int = update {
assert(!$0.isCollisionNode)
assert($0.childMap.contains(bucket))
assert($0.childMap.slot(of: bucket) == slot)
let p = $0.childPtr(at: slot)
let delta = child.count &- p.pointee.count
p.pointee = child
return delta
}
self.count &+= delta
return delta
}
@inlinable
internal func replacingChild(
_ level: _HashLevel,
at bucket: _Bucket,
_ slot: _HashSlot,
with child: __owned Builder
) -> Builder {
assert(child.level == level.descend())
read {
assert(!$0.isCollisionNode)
assert($0.childMap.contains(bucket))
assert(slot == $0.childMap.slot(of: bucket))
}
switch child.kind {
case .empty:
return _removingChild(level, at: bucket, slot)
case let .item(item, _):
if hasSingletonChild {
return .item(level, item, at: bucket)
}
var node = self.copy(withFreeSpace: _HashNode.spaceForInlinedChild)
_ = node.removeChild(at: bucket, slot)
node.insertItem(item, at: bucket)
node._invariantCheck()
return .node(level, node)
case let .node(node):
var copy = self.copy()
_ = copy.replaceChild(at: bucket, slot, with: node)
return .node(level, copy)
case let .collisionNode(node):
if hasSingletonChild {
// Compression
assert(!level.isAtBottom)
return .collisionNode(level, node)
}
var copy = self.copy()
_ = copy.replaceChild(at: bucket, slot, with: node)
return .node(level, copy)
}
}
}
@@ -0,0 +1,277 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
/// A base representation of a hash tree node, capturing functionality
/// independent of the `Key` and `Value` types.
@usableFromInline
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).
///
/// `_HashNode` is carefully defined to use a `_RawHashStorage` reference as its
/// storage variable, so that this can work. (The only reason we need the
/// `_HashNode.Storage` subclass is to allow storage instances to properly
/// clean up after themselves in their `deinit` method.)
@usableFromInline
internal let _emptySingleton: _RawHashStorage = _RawHashStorage.create(
minimumCapacity: 0,
makingHeaderWith: { _ in _HashNodeHeader(byteCapacity: 0) })
extension _HashNode {
/// Instances of this class hold (tail-allocated) storage for individual
/// nodes in a hash tree.
@usableFromInline
internal final class Storage: _RawHashStorage {
@usableFromInline
internal typealias Element = (key: Key, value: Value)
@usableFromInline
internal typealias UnsafeHandle = _HashNode<Key, Value>.UnsafeHandle
deinit {
UnsafeHandle.update(self) { handle in
handle.children.deinitialize()
handle.reverseItems.deinitialize()
}
}
}
}
extension _HashNode.Storage {
@inlinable
internal static func allocate(byteCapacity: Int) -> _HashNode.Storage {
assert(byteCapacity >= 0)
let itemStride = MemoryLayout<Element>.stride
let childStride = MemoryLayout<_HashNode>.stride
let unit = Swift.max(itemStride, childStride)
// Round up request to nearest power-of-two number of units.
// We'll allow allocations of space that fits 0, 1, 2, 4, 8, 16 or 32
// units.
var capacityInUnits = (byteCapacity &+ unit &- 1) / unit
#if false // Enable to set a larger minimum node size
if capacityInUnits != 0 {
capacityInUnits = Swift.max(capacityInUnits, 4)
}
#endif
var bytes = unit * capacityInUnits._roundUpToPowerOfTwo()
let itemAlignment = MemoryLayout<Element>.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 = _HashNode.Storage.create(
minimumCapacity: (bytes &+ childStride &- 1) / childStride
) { buffer in
_HashNodeHeader(byteCapacity: buffer.capacity * childStride)
}
object.withUnsafeMutablePointers { header, elements in
let start = UnsafeRawPointer(elements)
let end = start
.advanced(by: Int(header.pointee.byteCapacity))
.alignedDown(for: Element.self)
header.pointee._byteCapacity = UInt32(start.distance(to: end))
header.pointee._bytesFree = header.pointee._byteCapacity
assert(byteCapacity <= header.pointee.byteCapacity)
}
return unsafeDowncast(object, to: _HashNode.Storage.self)
}
}
extension _HashNode {
@inlinable @inline(__always)
internal static var spaceForNewItem: Int {
MemoryLayout<Element>.stride
}
@inlinable @inline(__always)
internal static var spaceForNewChild: Int {
MemoryLayout<_HashNode>.stride
}
@inlinable @inline(__always)
internal static var spaceForSpawningChild: Int {
Swift.max(0, spaceForNewChild - spaceForNewItem)
}
@inlinable @inline(__always)
internal static var spaceForInlinedChild: Int {
Swift.max(0, spaceForNewItem - spaceForNewChild)
}
@inlinable
internal mutating func isUnique() -> Bool {
isKnownUniquelyReferenced(&self.raw.storage)
}
@inlinable
internal func hasFreeSpace(_ bytes: Int) -> Bool {
bytes <= self.raw.storage.header.bytesFree
}
@inlinable
internal mutating func ensureUnique(isUnique: Bool) {
if !isUnique {
self = copy()
}
}
@inlinable
internal mutating func ensureUnique(
isUnique: Bool,
withFreeSpace minimumFreeBytes: Int = 0
) {
if !isUnique {
self = copy(withFreeSpace: minimumFreeBytes)
} else if !hasFreeSpace(minimumFreeBytes) {
move(withFreeSpace: minimumFreeBytes)
}
}
@inlinable
internal static func allocate<R>(
itemMap: _Bitmap, childMap: _Bitmap,
count: Int,
extraBytes: Int = 0,
initializingWith initializer: (
UnsafeMutableBufferPointer<_HashNode>, UnsafeMutableBufferPointer<Element>
) -> 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<_HashNode>.stride
let itemBytes = itemCount * itemStride
let childBytes = childCount * childStride
let occupiedBytes = itemBytes &+ childBytes
let storage = Storage.allocate(
byteCapacity: occupiedBytes &+ extraBytes)
var node = _HashNode(storage: storage, count: count)
let result: R = node.update {
$0.itemMap = itemMap
$0.childMap = childMap
assert(occupiedBytes <= $0.bytesFree)
$0.bytesFree &-= occupiedBytes
let childStart = $0._memory
.bindMemory(to: _HashNode.self, capacity: childCount)
let itemStart = ($0._memory + ($0.byteCapacity - itemBytes))
.bindMemory(to: Element.self, capacity: itemCount)
return initializer(
UnsafeMutableBufferPointer(start: childStart, count: childCount),
UnsafeMutableBufferPointer(start: itemStart, count: itemCount))
}
return (node, result)
}
@inlinable
internal static func allocateCollision<R>(
count: Int,
_ hash: _Hash,
extraBytes: Int = 0,
initializingWith initializer: (UnsafeMutableBufferPointer<Element>) -> 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<_RawHashNode>.alignment)
let storage = Storage.allocate(byteCapacity: bytes &+ extraBytes)
var node = _HashNode(storage: storage, count: count)
let result: R = node.update {
$0.itemMap = _Bitmap(bitPattern: count)
$0.childMap = $0.itemMap
assert(bytes <= $0.bytesFree)
$0.bytesFree &-= bytes
$0._memory.storeBytes(of: hash, as: _Hash.self)
let itemStart = ($0._memory + ($0.byteCapacity &- itemBytes))
.bindMemory(to: Element.self, capacity: count)
let items = UnsafeMutableBufferPointer(start: itemStart, count: count)
return initializer(items)
}
return (node, result)
}
@inlinable @inline(never)
internal func copy(withFreeSpace space: Int = 0) -> _HashNode {
assert(space >= 0)
if isCollisionNode {
return read { src in
Self.allocateCollision(
count: self.count, self.collisionHash
) { dstItems in
dstItems.initializeAll(fromContentsOf: src.reverseItems)
}.node
}
}
return read { src in
Self.allocate(
itemMap: src.itemMap,
childMap: src.childMap,
count: self.count,
extraBytes: space
) { dstChildren, dstItems in
dstChildren.initializeAll(fromContentsOf: src.children)
dstItems.initializeAll(fromContentsOf: src.reverseItems)
}.node
}
}
@inlinable @inline(never)
internal mutating func move(withFreeSpace space: Int = 0) {
assert(space >= 0)
let c = self.count
if isCollisionNode {
self = update { src in
Self.allocateCollision(
count: c, src.collisionHash
) { dstItems in
dstItems.moveInitializeAll(fromContentsOf: src.reverseItems)
src.clear()
}.node
}
return
}
self = update { src in
Self.allocate(
itemMap: src.itemMap,
childMap: src.childMap,
count: c,
extraBytes: space
) { dstChildren, dstItems in
dstChildren.moveInitializeAll(fromContentsOf: src.children)
dstItems.moveInitializeAll(fromContentsOf: src.reverseItems)
src.clear()
}.node
}
}
}
@@ -0,0 +1,46 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNode {
@inlinable
internal func compactMapValues<T>(
_ level: _HashLevel,
_ transform: (Value) throws -> T?
) rethrows -> _HashNode<Key, T>.Builder {
return try self.read {
var result: _HashNode<Key, T>.Builder = .empty(level)
if isCollisionNode {
let items = $0.reverseItems
for i in items.indices {
if let v = try transform(items[i].value) {
result.addNewCollision(level, (items[i].key, v), $0.collisionHash)
}
}
return result
}
for (bucket, slot) in $0.itemMap {
let p = $0.itemPtr(at: slot)
if let v = try transform(p.pointee.value) {
result.addNewItem(level, (p.pointee.key, v), at: bucket)
}
}
for (bucket, slot) in $0.childMap {
let branch = try $0[child: slot]
.compactMapValues(level.descend(), transform)
result.addNewChildBranch(level, branch, at: bucket)
}
return result
}
}
}
@@ -0,0 +1,83 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNode {
@inlinable
internal func filter(
_ level: _HashLevel,
_ isIncluded: (Element) throws -> Bool
) rethrows -> Builder? {
guard !isCollisionNode else {
return try _filter_slow(level, isIncluded)
}
return try self.read {
var result: Builder = .empty(level)
var removing = false // true if we need to remove something
for (bucket, slot) in $0.itemMap {
let p = $0.itemPtr(at: slot)
let include = try isIncluded(p.pointee)
switch (include, removing) {
case (true, true):
result.addNewItem(level, p.pointee, at: bucket)
case (false, false):
removing = true
result.copyItems(level, from: $0, upTo: bucket)
default:
break
}
}
for (bucket, slot) in $0.childMap {
let branch = try $0[child: slot].filter(level.descend(), isIncluded)
if let branch = branch {
assert(branch.count < self.count)
if !removing {
removing = true
result.copyItemsAndChildren(level, from: $0, upTo: bucket)
}
result.addNewChildBranch(level, branch, at: bucket)
} else if removing {
result.addNewChildNode(level, $0[child: slot], at: bucket)
}
}
guard removing else { return nil }
return result
}
}
@inlinable @inline(never)
internal func _filter_slow(
_ level: _HashLevel,
_ isIncluded: (Element) throws -> Bool
) rethrows -> Builder? {
try self.read {
var result: Builder = .empty(level)
var removing = false
for slot: _HashSlot in stride(from: .zero, to: $0.itemsEndSlot, by: 1) {
let p = $0.itemPtr(at: slot)
let include = try isIncluded(p.pointee)
if include, removing {
result.addNewCollision(level, p.pointee, $0.collisionHash)
}
else if !include, !removing {
removing = true
result.copyCollisions(from: $0, upTo: slot)
}
}
guard removing else { return nil }
assert(result.count < self.count)
return result
}
}
}
@@ -0,0 +1,195 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNode {
@inlinable
internal func intersection<Value2>(
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> _HashNode? {
assert(level.isAtRoot)
let builder = _intersection(level, other)
guard let builder = builder else { return nil }
let root = builder.finalize(.top)
root._fullInvariantCheck()
return root
}
@inlinable
internal func _intersection<Value2>(
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> Builder? {
if self.raw.storage === other.raw.storage { return nil }
if self.isCollisionNode || other.isCollisionNode {
return _intersection_slow(level, other)
}
return self.read { l in
other.read { r in
var result: Builder = .empty(level)
var removing = false
for (bucket, lslot) in l.itemMap {
let lp = l.itemPtr(at: lslot)
let include: Bool
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
include = (lp.pointee.key == r[item: rslot].key)
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let h = _Hash(lp.pointee.key)
include = r[child: rslot]
.containsKey(level.descend(), lp.pointee.key, h)
}
else { include = false}
if include, removing {
result.addNewItem(level, lp.pointee, at: bucket)
}
else if !include, !removing {
removing = true
result.copyItems(level, from: l, upTo: bucket)
}
}
for (bucket, lslot) in l.childMap {
if r.itemMap.contains(bucket) {
if !removing {
removing = true
result.copyItemsAndChildren(level, from: l, upTo: bucket)
}
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
let h = _Hash(rp.pointee.key)
let res = l[child: lslot].lookup(level.descend(), rp.pointee.key, h)
if let res = res {
let item = UnsafeHandle.read(res.node) { $0[item: res.slot] }
result.addNewItem(level, item, at: bucket)
}
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let branch = l[child: lslot]
._intersection(level.descend(), r[child: rslot])
if let branch = branch {
assert(branch.count < self.count)
if !removing {
removing = true
result.copyItemsAndChildren(level, from: l, upTo: bucket)
}
result.addNewChildBranch(level, branch, at: bucket)
} else if removing {
result.addNewChildNode(level, l[child: lslot], at: bucket)
}
}
else if !removing {
removing = true
result.copyItemsAndChildren(level, from: l, upTo: bucket)
}
}
guard removing else { return nil }
return result
}
}
}
@inlinable @inline(never)
internal func _intersection_slow<Value2>(
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> Builder? {
let lc = self.isCollisionNode
let rc = other.isCollisionNode
if lc && rc {
return read { l in
other.read { r in
var result: Builder = .empty(level)
guard l.collisionHash == r.collisionHash else { return result }
var removing = false
let ritems = r.reverseItems
for lslot: _HashSlot in stride(from: .zero, to: l.itemsEndSlot, by: 1) {
let lp = l.itemPtr(at: lslot)
let include = ritems.contains { $0.key == lp.pointee.key }
if include, removing {
result.addNewCollision(level, lp.pointee, l.collisionHash)
}
else if !include, !removing {
removing = true
result.copyCollisions(from: l, upTo: lslot)
}
}
guard removing else { return nil }
assert(result.count < self.count)
return result
}
}
}
// One of the nodes must be on a compressed path.
assert(!level.isAtBottom)
if lc {
// `self` is a collision node on a compressed path. The other tree might
// have the same set of collisions, just expanded a bit deeper.
return read { l in
other.read { r in
let bucket = l.collisionHash[level]
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let ritem = r.itemPtr(at: rslot)
let litems = l.reverseItems
let i = litems.firstIndex { $0.key == ritem.pointee.key }
guard let i = i else { return .empty(level) }
return .item(level, litems[i], at: l.collisionHash[level])
}
if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
return _intersection(level.descend(), r[child: rslot])
.map { .childBranch(level, $0, at: bucket) }
}
return .empty(level)
}
}
}
assert(rc)
// `other` is a collision node on a compressed path.
return read { l in
other.read { r in
let bucket = r.collisionHash[level]
if l.itemMap.contains(bucket) {
let lslot = l.itemMap.slot(of: bucket)
let litem = l.itemPtr(at: lslot)
let ritems = r.reverseItems
let found = ritems.contains { $0.key == litem.pointee.key }
guard found else { return .empty(level) }
return .item(level, litem.pointee, at: bucket)
}
if l.childMap.contains(bucket) {
let lslot = l.childMap.slot(of: bucket)
let branch = l[child: lslot]._intersection(level.descend(), other)
guard let branch = branch else {
assert(l[child: lslot].isCollisionNode)
assert(l[child: lslot].collisionHash == r.collisionHash)
// Compression
return .collisionNode(level, l[child: lslot])
}
return .childBranch(level, branch, at: bucket)
}
return .empty(level)
}
}
}
}
@@ -0,0 +1,111 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNode {
/// Returns true if `self` contains a disjoint set of keys than `other`.
/// Otherwise, returns false.
@inlinable @inline(never)
internal func isDisjoint<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 }
if self.isCollisionNode {
return _isDisjointCollision(level, with: other)
}
if other.isCollisionNode {
return other._isDisjointCollision(level, with: self)
}
return self.read { l in
other.read { r in
let lmap = l.itemMap.union(l.childMap)
let rmap = r.itemMap.union(r.childMap)
if lmap.isDisjoint(with: rmap) { return true }
for (bucket, _) in l.itemMap.intersection(r.itemMap) {
let lslot = l.itemMap.slot(of: bucket)
let rslot = r.itemMap.slot(of: bucket)
guard l[item: lslot].key != r[item: rslot].key else { return false }
}
for (bucket, _) in l.itemMap.intersection(r.childMap) {
let lslot = l.itemMap.slot(of: bucket)
let hash = _Hash(l[item: lslot].key)
let rslot = r.childMap.slot(of: bucket)
let found = r[child: rslot].containsKey(
level.descend(),
l[item: lslot].key,
hash)
if found { return false }
}
for (bucket, _) in l.childMap.intersection(r.itemMap) {
let lslot = l.childMap.slot(of: bucket)
let rslot = r.itemMap.slot(of: bucket)
let hash = _Hash(r[item: rslot].key)
let found = l[child: lslot].containsKey(
level.descend(),
r[item: rslot].key,
hash)
if found { return false }
}
for (bucket, _) in l.childMap.intersection(r.childMap) {
let lslot = l.childMap.slot(of: bucket)
let rslot = r.childMap.slot(of: bucket)
guard
l[child: lslot].isDisjoint(level.descend(), with: r[child: rslot])
else { return false }
}
return true
}
}
}
@inlinable @inline(never)
internal func _isDisjointCollision<Value2>(
_ level: _HashLevel,
with other: _HashNode<Key, Value2>
) -> Bool {
assert(isCollisionNode)
if other.isCollisionNode {
return read { l in
other.read { r in
guard l.collisionHash == r.collisionHash else { return true }
let litems = l.reverseItems
let ritems = r.reverseItems
return litems.allSatisfy { li in
!ritems.contains { ri in li.key == ri.key }
}
}
}
}
// `self` is on a compressed path. Try descending down by one level.
assert(!level.isAtBottom)
let bucket = self.collisionHash[level]
return other.read { r in
if r.childMap.contains(bucket) {
let slot = r.childMap.slot(of: bucket)
return isDisjoint(level.descend(), with: r[child: slot])
}
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let p = r.itemPtr(at: rslot)
let hash = _Hash(p.pointee.key)
return read { l in
guard hash == l.collisionHash else { return true }
return !l.reverseItems.contains { $0.key == p.pointee.key }
}
}
return true
}
}
}
@@ -0,0 +1,61 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// TODO: `Equatable` needs more test coverage, apart from hash-collision smoke test
extension _HashNode {
@inlinable
internal func isEqualSet<Value2>(
to other: _HashNode<Key, Value2>,
by areEquivalent: (Value, Value2) -> Bool
) -> Bool {
if self.raw.storage === other.raw.storage { return true }
guard self.count == other.count else { return false }
if self.isCollisionNode {
guard other.isCollisionNode else { return false }
return self.read { lhs in
other.read { rhs in
guard lhs.collisionHash == rhs.collisionHash else { return false }
let l = lhs.reverseItems
let r = rhs.reverseItems
assert(l.count == r.count) // Already checked above
for i in l.indices {
let found = r.contains {
l[i].key == $0.key && areEquivalent(l[i].value, $0.value)
}
guard found else { return false }
}
return true
}
}
}
guard !other.isCollisionNode else { return false }
return self.read { l in
other.read { r in
guard l.itemMap == r.itemMap else { return false }
guard l.childMap == r.childMap else { return false }
guard l.reverseItems.elementsEqual(
r.reverseItems,
by: { $0.key == $1.key && areEquivalent($0.value, $1.value) })
else { return false }
let lc = l.children
let rc = r.children
return lc.elementsEqual(
rc,
by: { $0.isEqualSet(to: $1, by: areEquivalent) })
}
}
}
}
@@ -0,0 +1,89 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNode {
/// Returns true if `self` contains a subset of the keys in `other`.
/// Otherwise, returns false.
@inlinable @inline(never)
internal func isSubset<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 }
guard self.count <= other.count else { return false }
if self.isCollisionNode {
if other.isCollisionNode {
guard self.collisionHash == other.collisionHash else { return false }
return read { l in
other.read { r in
let li = l.reverseItems
let ri = r.reverseItems
return l.reverseItems.indices.allSatisfy { i in
ri.contains { $0.key == li[i].key }
}
}
}
}
// `self` is on a compressed path. Try to descend down by one level.
assert(!level.isAtBottom)
let bucket = self.collisionHash[level]
return other.read {
guard $0.childMap.contains(bucket) else { return false }
let slot = $0.childMap.slot(of: bucket)
return self.isSubset(level.descend(), of: $0[child: slot])
}
}
if other.isCollisionNode {
return read { l in
guard level.isAtRoot, l.hasSingletonItem else { return false }
// Annoying special case: the root node may contain a single item
// that matches one in the collision node.
return other.read { r in
let hash = _Hash(l[item: .zero].key)
return r.find(level, l[item: .zero].key, hash) != nil
}
}
}
return self.read { l in
other.read { r in
guard l.childMap.isSubset(of: r.childMap) else { return false }
guard l.itemMap.isSubset(of: r.itemMap.union(r.childMap)) else {
return false
}
for (bucket, lslot) in l.itemMap {
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
guard l[item: lslot].key == r[item: rslot].key else { return false }
} else {
let hash = _Hash(l[item: lslot].key)
let rslot = r.childMap.slot(of: bucket)
guard
r[child: rslot].containsKey(
level.descend(),
l[item: lslot].key,
hash)
else { return false }
}
}
for (bucket, lslot) in l.childMap {
let rslot = r.childMap.slot(of: bucket)
guard l[child: lslot].isSubset(level.descend(), of: r[child: rslot])
else { return false }
}
return true
}
}
}
}
@@ -0,0 +1,88 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
extension _HashNode {
@inlinable
internal func mapValues<T>(
_ transform: (Element) throws -> T
) rethrows -> _HashNode<Key, T> {
let c = self.count
return try read { source in
var result: _HashNode<Key, T>
if isCollisionNode {
result = _HashNode<Key, T>.allocateCollision(
count: c, source.collisionHash,
initializingWith: { _ in }
).node
} else {
result = _HashNode<Key, T>.allocate(
itemMap: source.itemMap,
childMap: source.childMap,
count: c,
initializingWith: { _, _ in }
).node
}
try result.update { target in
let sourceItems = source.reverseItems
let targetItems = target.reverseItems
assert(sourceItems.count == targetItems.count)
let sourceChildren = source.children
let targetChildren = target.children
assert(sourceChildren.count == targetChildren.count)
var i = 0
var j = 0
var success = false
defer {
if !success {
targetItems.prefix(i).deinitialize()
targetChildren.prefix(j).deinitialize()
target.clear()
}
}
while i < targetItems.count {
let key = sourceItems[i].key
let value = try transform(sourceItems[i])
targetItems.initializeElement(at: i, to: (key, value))
i += 1
}
while j < targetChildren.count {
let child = try sourceChildren[j].mapValues(transform)
targetChildren.initializeElement(at: j, to: child)
j += 1
}
success = true
}
result._invariantCheck()
return result
}
}
@inlinable
internal func mapValuesToVoid(
copy: Bool = false, extraBytes: Int = 0
) -> _HashNode<Key, Void> {
if Value.self == Void.self {
let node = unsafeBitCast(self, to: _HashNode<Key, Void>.self)
guard copy || !node.hasFreeSpace(extraBytes) else { return node }
return node.copy(withFreeSpace: extraBytes)
}
let node = mapValues { _ in () }
guard !node.hasFreeSpace(extraBytes) else { return node }
return node.copy(withFreeSpace: extraBytes)
}
}
@@ -0,0 +1,329 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNode {
/// - Returns: The number of new items added to `self`.
@inlinable
internal mutating func merge(
_ level: _HashLevel,
_ other: _HashNode,
_ combine: (Value, Value) throws -> Value
) rethrows -> Int {
guard other.count > 0 else { return 0 }
guard self.count > 0 else {
self = other
return self.count
}
if level.isAtRoot, self.hasSingletonItem {
// In this special case, the root node may turn into a collision node
// during the merge process. Prevent this from causing issues below by
// handling it up front.
var copy = other
let delta = try self.read { l in
let lp = l.itemPtr(at: .zero)
let c = copy.count
let res = copy.updateValue(
level, forKey: lp.pointee.key, _Hash(lp.pointee.key)
) {
$0.initialize(to: lp.pointee)
}
if !res.inserted {
try UnsafeHandle.update(res.leaf) {
let p = $0.itemPtr(at: res.slot)
p.pointee.value = try combine(lp.pointee.value, p.pointee.value)
}
}
return c - (res.inserted ? 0 : 1)
}
self = copy
return delta
}
return try _merge(level, other, combine)
}
@inlinable
internal mutating func _merge(
_ level: _HashLevel,
_ other: _HashNode,
_ combine: (Value, Value) throws -> Value
) rethrows -> Int {
// Note: don't check storage identities -- we do need to merge the contents
// of identical nodes.
if self.isCollisionNode || other.isCollisionNode {
return try _merge_slow(level, other, combine)
}
return try other.read { r in
var isUnique = self.isUnique()
var delta = 0
let (originalItems, originalChildren) = self.read {
($0.itemMap, $0.childMap)
}
for (bucket, _) in originalItems {
assert(!isCollisionNode)
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
let lslot = self.read { $0.itemMap.slot(of: bucket) }
let conflict = self.read { $0[item: lslot].key == rp.pointee.key }
if conflict {
self.ensureUnique(isUnique: isUnique)
try self.update {
let p = $0.itemPtr(at: lslot)
p.pointee.value = try combine(p.pointee.value, rp.pointee.value)
}
} else {
_ = self.ensureUniqueAndSpawnChild(
isUnique: isUnique,
level: level,
replacing: bucket,
itemSlot: lslot,
newHash: _Hash(rp.pointee.key),
{ $0.initialize(to: rp.pointee) })
// If we hadn't handled the singleton root node case above,
// then this call would sometimes turn `self` into a collision
// node on a compressed path, causing mischief.
assert(!self.isCollisionNode)
delta &+= 1
}
isUnique = true
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let rp = r.childPtr(at: rslot)
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _HashNode.spaceForSpawningChild)
let item = self.removeItem(at: bucket)
delta &-= 1
var child = rp.pointee
let r = child.updateValue(
level.descend(), forKey: item.key, _Hash(item.key)
) {
$0.initialize(to: item)
}
if !r.inserted {
try UnsafeHandle.update(r.leaf) {
let p = $0.itemPtr(at: r.slot)
p.pointee.value = try combine(item.value, p.pointee.value)
}
}
self.insertChild(child, bucket)
isUnique = true
delta &+= child.count
}
}
for (bucket, _) in originalChildren {
assert(!isCollisionNode)
let lslot = self.read { $0.childMap.slot(of: bucket) }
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
self.ensureUnique(isUnique: isUnique)
let h = _Hash(rp.pointee.key)
let res = self.update { l in
l[child: lslot].updateValue(
level.descend(), forKey: rp.pointee.key, h
) {
$0.initialize(to: rp.pointee)
}
}
if res.inserted {
self.count &+= 1
delta &+= 1
} else {
try UnsafeHandle.update(res.leaf) {
let p = $0.itemPtr(at: res.slot)
p.pointee.value = try combine(p.pointee.value, rp.pointee.value)
}
}
isUnique = true
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
self.ensureUnique(isUnique: isUnique)
let d = try self.update { l in
try l[child: lslot].merge(
level.descend(),
r[child: rslot],
combine)
}
self.count &+= d
delta &+= d
isUnique = true
}
}
assert(!self.isCollisionNode)
/// Add buckets in `other` that we haven't processed above.
let seen = self.read { l in l.itemMap.union(l.childMap) }
for (bucket, _) in r.itemMap.subtracting(seen) {
let rslot = r.itemMap.slot(of: bucket)
self.ensureUniqueAndInsertItem(
isUnique: isUnique, r[item: rslot], at: bucket)
delta &+= 1
isUnique = true
}
for (bucket, _) in r.childMap.subtracting(seen) {
let rslot = r.childMap.slot(of: bucket)
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild)
self.insertChild(r[child: rslot], bucket)
delta &+= r[child: rslot].count
isUnique = true
}
assert(isUnique)
return delta
}
}
@inlinable @inline(never)
internal mutating func _merge_slow(
_ 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 = _HashNode.build(
level: level,
child1: self, self.collisionHash,
child2: other, other.collisionHash)
return other.count
}
return try other.read { r in
var isUnique = self.isUnique()
var delta = 0
let originalItemCount = self.count
for rs: _HashSlot in stride(from: .zero, to: r.itemsEndSlot, by: 1) {
let rp = r.itemPtr(at: rs)
let lslot: _HashSlot? = self.read { l in
let litems = l.reverseItems
return litems
.suffix(originalItemCount)
.firstIndex { $0.key == rp.pointee.key }
.map { _HashSlot(litems.count &- 1 &- $0) }
}
if let lslot = lslot {
self.ensureUnique(isUnique: isUnique)
try self.update {
let p = $0.itemPtr(at: lslot)
p.pointee.value = try combine(p.pointee.value, rp.pointee.value)
}
} else {
_ = self.ensureUniqueAndAppendCollision(
isUnique: isUnique, rp.pointee)
delta &+= 1
}
isUnique = true
}
return delta
}
}
// One of the nodes must be on a compressed path.
assert(!level.isAtBottom)
if lc {
// `self` is a collision node on a compressed path. The other tree might
// have the same set of collisions, just expanded a bit deeper.
return try other.read { r in
let bucket = self.collisionHash[level]
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
let h = _Hash(rp.pointee.key)
let res = self.updateValue(
level.descend(), forKey: rp.pointee.key, h
) {
$0.initialize(to: rp.pointee)
}
if !res.inserted {
try UnsafeHandle.update(res.leaf) {
let p = $0.itemPtr(at: res.slot)
p.pointee.value = try combine(p.pointee.value, rp.pointee.value)
}
}
self = other._copyNodeAndReplaceItemWithNewChild(
level: level, self, at: bucket, itemSlot: rslot)
return other.count - (res.inserted ? 0 : 1)
}
if r.childMap.contains(bucket) {
let originalCount = self.count
let rslot = r.childMap.slot(of: bucket)
_ = try self._merge(level.descend(), r[child: rslot], combine)
var node = other.copy()
_ = node.replaceChild(at: bucket, rslot, with: self)
self = node
return self.count - originalCount
}
var node = other.copy(withFreeSpace: _HashNode.spaceForNewChild)
node.insertChild(self, bucket)
self = node
return other.count
}
}
assert(rc)
let isUnique = self.isUnique()
// `other` is a collision node on a compressed path.
return try other.read { r in
let bucket = r.collisionHash[level]
if self.read({ $0.itemMap.contains(bucket) }) {
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _HashNode.spaceForSpawningChild)
let item = self.removeItem(at: bucket)
let h = _Hash(item.key)
var copy = other
let res = copy.updateValue(level.descend(), forKey: item.key, h) {
$0.initialize(to: item)
}
if !res.inserted {
try UnsafeHandle.update(res.leaf) {
let p = $0.itemPtr(at: res.slot)
p.pointee.value = try combine(item.value, p.pointee.value)
}
}
assert(self.count > 0) // Singleton case handled up front above
self.insertChild(copy, bucket)
return other.count - (res.inserted ? 0 : 1)
}
if self.read({ $0.childMap.contains(bucket) }) {
self.ensureUnique(isUnique: isUnique)
let delta: Int = try self.update { l in
let lslot = l.childMap.slot(of: bucket)
let lchild = l.childPtr(at: lslot)
return try lchild.pointee._merge(level.descend(), other, combine)
}
assert(delta >= 0)
self.count &+= delta
return delta
}
self.ensureUnique(
isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild)
self.insertChild(other, bucket)
return other.count
}
}
}
@@ -0,0 +1,199 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNode {
@inlinable
internal func subtracting<Value2>(
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> _HashNode? {
assert(level.isAtRoot)
let builder = _subtracting(level, other)
guard let builder = builder else { return nil }
let root = builder.finalize(.top)
root._fullInvariantCheck()
return root
}
@inlinable
internal func _subtracting<Value2>(
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> Builder? {
if self.raw.storage === other.raw.storage { return .empty(level) }
if self.isCollisionNode || other.isCollisionNode {
return _subtracting_slow(level, other)
}
return self.read { l in
other.read { r in
var result: Builder = .empty(level)
var removing = false
for (bucket, lslot) in l.itemMap {
let lp = l.itemPtr(at: lslot)
let include: Bool
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
include = (lp.pointee.key != r[item: rslot].key)
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let h = _Hash(lp.pointee.key)
include = !r[child: rslot]
.containsKey(level.descend(), lp.pointee.key, h)
}
else {
include = true
}
if include, removing {
result.addNewItem(level, lp.pointee, at: bucket)
}
else if !include, !removing {
removing = true
result.copyItems(level, from: l, upTo: bucket)
}
}
for (bucket, lslot) in l.childMap {
var done = false
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
let h = _Hash(rp.pointee.key)
let child = l[child: lslot]
.removing(level.descend(), rp.pointee.key, h)?.replacement
if let child = child {
assert(child.count < self.count)
if !removing {
removing = true
result.copyItemsAndChildren(level, from: l, upTo: bucket)
}
result.addNewChildBranch(level, child, at: bucket)
done = true
}
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let child = l[child: lslot]
._subtracting(level.descend(), r[child: rslot])
if let child = child {
assert(child.count < self.count)
if !removing {
removing = true
result.copyItemsAndChildren(level, from: l, upTo: bucket)
}
result.addNewChildBranch(level, child, at: bucket)
done = true
}
}
if !done, removing {
result.addNewChildNode(level, l[child: lslot], at: bucket)
}
}
guard removing else { return nil }
return result
}
}
}
@inlinable @inline(never)
internal func _subtracting_slow<Value2>(
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> Builder? {
let lc = self.isCollisionNode
let rc = other.isCollisionNode
if lc && rc {
return read { l in
other.read { r in
guard l.collisionHash == r.collisionHash else {
return nil
}
var result: Builder = .empty(level)
var removing = false
let ritems = r.reverseItems
for lslot: _HashSlot in stride(from: .zero, to: l.itemsEndSlot, by: 1) {
let lp = l.itemPtr(at: lslot)
let include = !ritems.contains { $0.key == lp.pointee.key }
if include, removing {
result.addNewCollision(level, lp.pointee, l.collisionHash)
}
else if !include, !removing {
removing = true
result.copyCollisions(from: l, upTo: lslot)
}
}
guard removing else { return nil }
assert(result.count < self.count)
return result
}
}
}
// One of the nodes must be on a compressed path.
assert(!level.isAtBottom)
if lc {
// `self` is a collision node on a compressed path. The other tree might
// have the same set of collisions, just expanded a bit deeper.
return read { l in
other.read { r in
let bucket = l.collisionHash[level]
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let ritem = r.itemPtr(at: rslot)
let h = _Hash(ritem.pointee.key)
let res = l.find(level, ritem.pointee.key, h)
guard let res = res else { return nil }
return self._removingItemFromLeaf(level, at: bucket, res.slot)
.replacement
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
return _subtracting(level.descend(), r[child: rslot])
.map { .childBranch(level, $0, at: bucket) }
}
return nil
}
}
}
assert(rc)
// `other` is a collision node on a compressed path.
return read { l in
other.read { r in
let bucket = r.collisionHash[level]
if l.itemMap.contains(bucket) {
let lslot = l.itemMap.slot(of: bucket)
let litem = l.itemPtr(at: lslot)
let h = _Hash(litem.pointee.key)
let res = r.find(level, litem.pointee.key, h)
if res == nil { return nil }
return self._removingItemFromLeaf(level, at: bucket, lslot)
.replacement
}
if l.childMap.contains(bucket) {
let lslot = l.childMap.slot(of: bucket)
let branch = l[child: lslot]._subtracting(level.descend(), other)
guard let branch = branch else { return nil }
var result = self._removingChild(level, at: bucket, lslot)
result.addNewChildBranch(level, branch, at: bucket)
return result
}
return nil
}
}
}
}
@@ -0,0 +1,268 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNode {
@inlinable
internal func symmetricDifference<Value2>(
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> _HashNode<Key, Void>.Builder? {
guard self.count > 0 else {
return .init(level, other.mapValuesToVoid())
}
guard other.count > 0 else { return nil }
return _symmetricDifference(level, other)
}
@inlinable
internal func _symmetricDifference<Value2>(
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> _HashNode<Key, Void>.Builder {
typealias VoidNode = _HashNode<Key, Void>
assert(self.count > 0 && other.count > 0)
if self.raw.storage === other.raw.storage {
return .empty(level)
}
if self.isCollisionNode || other.isCollisionNode {
return _symmetricDifference_slow(level, other)
}
return self.read { l in
other.read { r in
var result: VoidNode.Builder = .empty(level)
for (bucket, lslot) in l.itemMap {
let lp = l.itemPtr(at: lslot)
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
if lp.pointee.key != rp.pointee.key {
let h1 = _Hash(lp.pointee.key)
let h2 = _Hash(rp.pointee.key)
let child = VoidNode.build(
level: level.descend(),
item1: (lp.pointee.key, ()), h1,
item2: { $0.initialize(to: (rp.pointee.key, ())) }, h2)
result.addNewChildNode(level, child.top, at: bucket)
}
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let rp = r.childPtr(at: rslot)
let h = _Hash(lp.pointee.key)
let child = rp.pointee
.removing(level.descend(), lp.pointee.key, h)?.replacement
if let child = child {
let child = child.mapValuesToVoid()
result.addNewChildBranch(level, child, at: bucket)
}
else {
var child2 = rp.pointee
.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
let r = child2.insert(level.descend(), (lp.pointee.key, ()), h)
assert(r.inserted)
result.addNewChildNode(level, child2, at: bucket)
}
}
else {
result.addNewItem(level, (lp.pointee.key, ()), at: bucket)
}
}
for (bucket, lslot) in l.childMap {
let lp = l.childPtr(at: lslot)
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
let h = _Hash(rp.pointee.key)
let child = lp.pointee
.mapValuesToVoid()
.removing(level.descend(), rp.pointee.key, h)?.replacement
if let child = child {
result.addNewChildBranch(level, child, at: bucket)
}
else {
var child2 = lp.pointee.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
let r2 = child2.insert(level.descend(), (rp.pointee.key, ()), h)
assert(r2.inserted)
result.addNewChildNode(level, child2, at: bucket)
}
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let b = l[child: lslot]._symmetricDifference(
level.descend(), r[child: rslot])
result.addNewChildBranch(level, b, at: bucket)
}
else {
result.addNewChildNode(
level, lp.pointee.mapValuesToVoid(), at: bucket)
}
}
let seen = l.itemMap.union(l.childMap)
for (bucket, rslot) in r.itemMap {
guard !seen.contains(bucket) else { continue }
result.addNewItem(level, (r[item: rslot].key, ()), at: bucket)
}
for (bucket, rslot) in r.childMap {
guard !seen.contains(bucket) else { continue }
result.addNewChildNode(
level, r[child: rslot].mapValuesToVoid(), at: bucket)
}
return result
}
}
}
@inlinable @inline(never)
internal func _symmetricDifference_slow<Value2>(
_ 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)
case (true, false):
return self._symmetricDifference_slow_left(level, other)
case (false, _):
return other._symmetricDifference_slow_left(level, self)
}
}
@inlinable
internal func _symmetricDifference_slow_both<Value2>(
_ 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 {
let node = VoidNode.build(
level: level,
child1: self.mapValuesToVoid(), l.collisionHash,
child2: other.mapValuesToVoid(), r.collisionHash)
return .node(level, node)
}
var result: VoidNode.Builder = .empty(level)
let ritems = r.reverseItems
for ls: _HashSlot in stride(from: .zero, to: l.itemsEndSlot, by: 1) {
let lp = l.itemPtr(at: ls)
let include = !ritems.contains(where: { $0.key == lp.pointee.key })
if include {
result.addNewCollision(level, (lp.pointee.key, ()), l.collisionHash)
}
}
// FIXME: Consider remembering slots of shared items in r by
// caching them in a bitset.
let litems = l.reverseItems
for rs: _HashSlot in stride(from: .zero, to: r.itemsEndSlot, by: 1) {
let rp = r.itemPtr(at: rs)
let include = !litems.contains(where: { $0.key == rp.pointee.key })
if include {
result.addNewCollision(level, (rp.pointee.key, ()), r.collisionHash)
}
}
return result
}
}
}
@inlinable
internal func _symmetricDifference_slow_left<Value2>(
_ 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
other.read { r in
assert(l.isCollisionNode && !r.isCollisionNode)
let bucket = l.collisionHash[level]
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
let rh = _Hash(rp.pointee.key)
guard rh == l.collisionHash else {
var copy = other.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForSpawningChild)
let item = copy.removeItem(at: bucket, rslot)
let child = VoidNode.build(
level: level.descend(),
item1: { $0.initialize(to: (item.key, ())) }, rh,
child2: self.mapValuesToVoid(), l.collisionHash)
copy.insertChild(child.top, bucket)
return .node(level, copy)
}
let litems = l.reverseItems
if let li = litems.firstIndex(where: { $0.key == rp.pointee.key }) {
if l.itemCount == 2 {
var node = other.mapValuesToVoid(copy: true)
node.replaceItem(
at: bucket, rslot,
with: (litems[1 &- li].key, ()))
return .node(level, node)
}
let lslot = _HashSlot(litems.count &- 1 &- li)
var child = self.mapValuesToVoid(copy: true)
_ = child.removeItem(at: .invalid, lslot)
if other.hasSingletonItem {
// Compression
return .collisionNode(level, child)
}
var node = other.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForSpawningChild)
_ = node.removeItem(at: bucket, rslot)
node.insertChild(child, bucket)
return .node(level, node)
}
if other.hasSingletonItem {
// Compression
var copy = self.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
_ = copy.ensureUniqueAndAppendCollision(
isUnique: true,
(r[item: .zero].key, ()))
return .collisionNode(level, copy)
}
var node = other.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForSpawningChild)
let item = node.removeItem(at: bucket, rslot)
var child = self.mapValuesToVoid(
copy: true, extraBytes: VoidNode.spaceForNewItem)
_ = child.ensureUniqueAndAppendCollision(
isUnique: true, (item.key, ()))
node.insertChild(child, bucket)
return .node(level, node)
}
if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let rp = r.childPtr(at: rslot)
let child = rp.pointee._symmetricDifference(level.descend(), self)
return other
.mapValuesToVoid()
.replacingChild(level, at: bucket, rslot, with: child)
}
var node = other
.mapValuesToVoid(copy: true, extraBytes: VoidNode.spaceForNewChild)
node.insertChild(self.mapValuesToVoid(), bucket)
return .node(level, node)
}
}
}
}
@@ -0,0 +1,257 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _HashNode {
@inlinable
internal func union<Value2>(
_ 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 {
// In this special case, the root node may turn into a collision node
// during the merge process. Prevent this from causing issues below by
// handling it up front.
return self.read { l in
let lp = l.itemPtr(at: .zero)
var copy = other.mapValuesToVoid(copy: true)
let r = copy.updateValue(
level, forKey: lp.pointee.key, _Hash(lp.pointee.key)
) {
$0.initialize(to: (lp.pointee.key, ()))
}
if !r.inserted {
UnsafeHandle.update(r.leaf) {
$0[item: r.slot] = lp.pointee
}
}
return (true, copy)
}
}
return _union(level, other)
}
@inlinable
internal func _union<Value2>(
_ level: _HashLevel,
_ other: _HashNode<Key, Value2>
) -> (copied: Bool, node: _HashNode<Key, Void>) {
if self.raw.storage === other.raw.storage {
return (false, self.mapValuesToVoid())
}
if self.isCollisionNode || other.isCollisionNode {
return _union_slow(level, other)
}
return self.read { l in
other.read { r in
var node = self.mapValuesToVoid()
var copied = false
for (bucket, lslot) in l.itemMap {
assert(!node.isCollisionNode)
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let lp = l.itemPtr(at: lslot)
let rp = r.itemPtr(at: rslot)
if lp.pointee.key != rp.pointee.key {
let slot = (
copied
? node.read { $0.itemMap.slot(of: bucket) }
: lslot)
_ = node.ensureUniqueAndSpawnChild(
isUnique: copied,
level: level,
replacing: bucket,
itemSlot: slot,
newHash: _Hash(rp.pointee.key),
{ $0.initialize(to: (rp.pointee.key, ())) })
// If we hadn't handled the singleton root node case above,
// then this call would sometimes turn `node` into a collision
// node on a compressed path, causing mischief.
assert(!node.isCollisionNode)
copied = true
}
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let rp = r.childPtr(at: rslot)
node.ensureUnique(
isUnique: copied, withFreeSpace: _HashNode.spaceForSpawningChild)
let item = node.removeItem(at: bucket)
let r = rp.pointee.mapValuesToVoid()
.inserting(level.descend(), (item.key, ()), _Hash(item.key))
node.insertChild(r.node, bucket)
copied = true
}
}
for (bucket, lslot) in l.childMap {
assert(!node.isCollisionNode)
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
let h = _Hash(rp.pointee.key)
let r = l[child: lslot].mapValuesToVoid()
.inserting(level.descend(), (rp.pointee.key, ()), h)
guard r.inserted else {
// Nothing to do
continue
}
node.ensureUnique(isUnique: copied)
let delta = node.replaceChild(at: bucket, with: r.node)
assert(delta == 1)
copied = true
}
else if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let child = l[child: lslot]._union(level.descend(), r[child: rslot])
guard child.copied else {
// Nothing to do
continue
}
node.ensureUnique(isUnique: copied)
let delta = node.replaceChild(at: bucket, with: child.node)
assert(delta > 0) // If we didn't add an item, why did we copy?
copied = true
}
}
assert(!node.isCollisionNode)
/// Add buckets in `other` that we haven't processed above.
let seen = l.itemMap.union(l.childMap)
for (bucket, _) in r.itemMap.subtracting(seen) {
let rslot = r.itemMap.slot(of: bucket)
node.ensureUniqueAndInsertItem(
isUnique: copied, (r[item: rslot].key, ()), at: bucket)
copied = true
}
for (bucket, _) in r.childMap.subtracting(seen) {
let rslot = r.childMap.slot(of: bucket)
node.ensureUnique(
isUnique: copied, withFreeSpace: _HashNode.spaceForNewChild)
copied = true
node.insertChild(r[child: rslot].mapValuesToVoid(), bucket)
}
return (copied, node)
}
}
}
@inlinable @inline(never)
internal func _union_slow<Value2>(
_ 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 = _HashNode<Key, Void>.build(
level: level,
child1: self.mapValuesToVoid(), l.collisionHash,
child2: other.mapValuesToVoid(), r.collisionHash)
return (true, node)
}
var copied = false
var node = self.mapValuesToVoid()
let litems = l.reverseItems
for rs: _HashSlot in stride(from: .zero, to: r.itemsEndSlot, by: 1) {
let p = r.itemPtr(at: rs)
if !litems.contains(where: { $0.key == p.pointee.key }) {
_ = node.ensureUniqueAndAppendCollision(
isUnique: copied, (p.pointee.key, ()))
copied = true
}
}
return (copied, node)
}
}
}
// One of the nodes must be on a compressed path.
assert(!level.isAtBottom)
if lc {
// `self` is a collision node on a compressed path. The other tree might
// have the same set of collisions, just expanded a bit deeper.
return read { l in
other.read { r in
let bucket = l.collisionHash[level]
if r.itemMap.contains(bucket) {
let rslot = r.itemMap.slot(of: bucket)
let rp = r.itemPtr(at: rslot)
if
r.hasSingletonItem
&& l.reverseItems.contains(where: { $0.key == rp.pointee.key })
{
return (false, self.mapValuesToVoid())
}
let node = other.mapValuesToVoid().copyNodeAndPushItemIntoNewChild(
level: level, self.mapValuesToVoid(), at: bucket, itemSlot: rslot)
return (true, node)
}
if r.childMap.contains(bucket) {
let rslot = r.childMap.slot(of: bucket)
let res = self._union(level.descend(), r[child: rslot])
var node = other.mapValuesToVoid(copy: true)
let delta = node.replaceChild(at: bucket, rslot, with: res.node)
assert(delta >= 0)
return (true, node)
}
var node = other.mapValuesToVoid(
copy: true, extraBytes: _HashNode<Key, Void>.spaceForNewChild)
node.insertChild(self.mapValuesToVoid(), bucket)
return (true, node)
}
}
}
assert(rc)
// `other` is a collision node on a compressed path.
return read { l -> (copied: Bool, node: _HashNode<Key, Void>) in
other.read { r -> (copied: Bool, node: _HashNode<Key, Void>) in
let bucket = r.collisionHash[level]
if l.itemMap.contains(bucket) {
let lslot = l.itemMap.slot(of: bucket)
assert(!l.hasSingletonItem) // Handled up front above
let node = self.mapValuesToVoid().copyNodeAndPushItemIntoNewChild(
level: level, other.mapValuesToVoid(), at: bucket, itemSlot: lslot)
return (true, node)
}
if l.childMap.contains(bucket) {
let lslot = l.childMap.slot(of: bucket)
let child = l[child: lslot]._union(level.descend(), other)
guard child.copied else { return (false, self.mapValuesToVoid()) }
var node = self.mapValuesToVoid(copy: true)
let delta = node.replaceChild(at: bucket, lslot, with: child.node)
assert(delta > 0) // If we didn't add an item, why did we copy?
return (true, node)
}
var node = self.mapValuesToVoid(
copy: true, extraBytes: _HashNode.spaceForNewChild)
node.insertChild(other.mapValuesToVoid(), bucket)
return (true, node)
}
}
}
}
@@ -0,0 +1,576 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
extension _HashNode {
@inlinable
internal mutating func insert(
_ level: _HashLevel,
_ item: Element,
_ hash: _Hash
) -> (inserted: Bool, leaf: _UnmanagedHashNode, slot: _HashSlot) {
insert(level, item.key, hash) { $0.initialize(to: item) }
}
@inlinable
internal mutating func insert(
_ level: _HashLevel,
_ key: Key,
_ hash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (inserted: Bool, leaf: _UnmanagedHashNode, slot: _HashSlot) {
defer { _invariantCheck() }
let isUnique = self.isUnique()
if !isUnique {
let r = self.inserting(level, key, hash, inserter)
self = r.node
return (r.inserted, r.leaf, r.slot)
}
let r = findForInsertion(level, key, hash)
switch r {
case .found(_, let slot):
return (false, unmanaged, slot)
case .insert(let bucket, let slot):
ensureUniqueAndInsertItem(
isUnique: true, at: bucket, itemSlot: slot, inserter)
return (true, unmanaged, slot)
case .appendCollision:
let slot = ensureUniqueAndAppendCollision(isUnique: true, inserter)
return (true, unmanaged, slot)
case .spawnChild(let bucket, let slot):
let r = ensureUniqueAndSpawnChild(
isUnique: true,
level: level,
replacing: bucket,
itemSlot: slot,
newHash: hash,
inserter)
return (true, r.leaf, r.slot)
case .expansion:
let r = _HashNode.build(
level: level,
item1: inserter, hash,
child2: self, self.collisionHash)
self = r.top
return (true, r.leaf, r.slot1)
case .descend(_, let slot):
let r = update {
$0[child: slot].insert(level.descend(), key, hash, inserter)
}
if r.inserted { count &+= 1 }
return r
}
}
@inlinable
internal func inserting(
_ level: _HashLevel,
_ item: __owned Element,
_ hash: _Hash
) -> (
inserted: Bool, node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot
) {
inserting(level, item.key, hash, { $0.initialize(to: item) })
}
@inlinable
internal func inserting(
_ level: _HashLevel,
_ key: Key,
_ hash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (
inserted: Bool, node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot
) {
defer { _invariantCheck() }
let r = findForInsertion(level, key, hash)
switch r {
case .found(_, let slot):
return (false, self, unmanaged, slot)
case .insert(let bucket, let slot):
let node = copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter)
return (true, node, node.unmanaged, slot)
case .appendCollision:
let r = copyNodeAndAppendCollision(inserter)
return (true, r.node, r.node.unmanaged, r.slot)
case .spawnChild(let bucket, let slot):
let existingHash = read { _Hash($0[item: slot].key) }
let r = copyNodeAndSpawnChild(
level: level,
replacing: bucket,
itemSlot: slot,
existingHash: existingHash,
newHash: hash,
inserter)
return (true, r.node, r.leaf, r.slot)
case .expansion:
let r = _HashNode.build(
level: level,
item1: inserter, hash,
child2: self, self.collisionHash)
return (true, r.top, r.leaf, r.slot1)
case .descend(_, let slot):
let r = read {
$0[child: slot].inserting(level.descend(), key, hash, inserter)
}
guard r.inserted else {
return (false, self, r.leaf, r.slot)
}
var copy = self.copy()
copy.update { $0[child: slot] = r.node }
copy.count &+= 1
return (true, copy, r.leaf, r.slot)
}
}
@inlinable
internal mutating func updateValue(
_ level: _HashLevel,
forKey key: Key,
_ hash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (inserted: Bool, leaf: _UnmanagedHashNode, slot: _HashSlot) {
defer { _invariantCheck() }
let isUnique = self.isUnique()
let r = findForInsertion(level, key, hash)
switch r {
case .found(_, let slot):
ensureUnique(isUnique: isUnique)
return (false, unmanaged, slot)
case .insert(let bucket, let slot):
ensureUniqueAndInsertItem(
isUnique: isUnique, at: bucket, itemSlot: slot, inserter)
return (true, unmanaged, slot)
case .appendCollision:
let slot = ensureUniqueAndAppendCollision(isUnique: isUnique, inserter)
return (true, unmanaged, slot)
case .spawnChild(let bucket, let slot):
let r = ensureUniqueAndSpawnChild(
isUnique: isUnique,
level: level,
replacing: bucket,
itemSlot: slot,
newHash: hash,
inserter)
return (true, r.leaf, r.slot)
case .expansion:
let r = _HashNode.build(
level: level,
item1: inserter, hash,
child2: self, self.collisionHash)
self = r.top
return (true, r.leaf, r.slot1)
case .descend(_, let slot):
ensureUnique(isUnique: isUnique)
let r = update {
$0[child: slot].updateValue(
level.descend(), forKey: key, hash, inserter)
}
if r.inserted { count &+= 1 }
return r
}
}
}
extension _HashNode {
@inlinable
internal mutating func ensureUniqueAndInsertItem(
isUnique: Bool,
_ item: Element,
at bucket: _Bucket
) {
let slot = self.read { $0.itemMap.slot(of: bucket) }
ensureUniqueAndInsertItem(
isUnique: isUnique,
at: bucket,
itemSlot: slot
) {
$0.initialize(to: item)
}
}
@inlinable
internal mutating func ensureUniqueAndInsertItem(
isUnique: Bool,
at bucket: _Bucket,
itemSlot slot: _HashSlot,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) {
assert(!isCollisionNode)
if !isUnique {
self = copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter)
return
}
if !hasFreeSpace(Self.spaceForNewItem) {
resizeNodeAndInsertItem(at: bucket, itemSlot: slot, inserter)
return
}
// In-place insert.
update {
let p = $0._makeRoomForNewItem(at: slot, bucket)
inserter(p)
}
self.count &+= 1
}
@inlinable @inline(never)
internal func copyNodeAndInsertItem(
at bucket: _Bucket,
itemSlot slot: _HashSlot,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> _HashNode {
assert(!isCollisionNode)
let c = self.count
return read { src in
assert(!src.itemMap.contains(bucket))
assert(!src.childMap.contains(bucket))
return Self.allocate(
itemMap: src.itemMap.inserting(bucket),
childMap: src.childMap,
count: c &+ 1
) { dstChildren, dstItems in
dstChildren.initializeAll(fromContentsOf: src.children)
let srcItems = src.reverseItems
assert(dstItems.count == srcItems.count + 1)
dstItems.suffix(slot.value)
.initializeAll(fromContentsOf: srcItems.suffix(slot.value))
let rest = srcItems.count &- slot.value
dstItems.prefix(rest)
.initializeAll(fromContentsOf: srcItems.prefix(rest))
inserter(dstItems.baseAddress! + rest)
}.node
}
}
@inlinable @inline(never)
internal mutating func resizeNodeAndInsertItem(
at bucket: _Bucket,
itemSlot slot: _HashSlot,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) {
assert(!isCollisionNode)
let c = self.count
self = update { src in
assert(!src.itemMap.contains(bucket))
assert(!src.childMap.contains(bucket))
return Self.allocate(
itemMap: src.itemMap.inserting(bucket),
childMap: src.childMap,
count: c &+ 1
) { dstChildren, dstItems in
dstChildren.moveInitializeAll(fromContentsOf: src.children)
let srcItems = src.reverseItems
assert(dstItems.count == srcItems.count + 1)
dstItems.suffix(slot.value)
.moveInitializeAll(fromContentsOf: srcItems.suffix(slot.value))
let rest = srcItems.count &- slot.value
dstItems.prefix(rest)
.moveInitializeAll(fromContentsOf: srcItems.prefix(rest))
inserter(dstItems.baseAddress! + rest)
src.clear()
}.node
}
}
}
extension _HashNode {
@inlinable
internal mutating func ensureUniqueAndAppendCollision(
isUnique: Bool,
_ item: Element
) -> _HashSlot {
ensureUniqueAndAppendCollision(isUnique: isUnique) {
$0.initialize(to: item)
}
}
@inlinable
internal mutating func ensureUniqueAndAppendCollision(
isUnique: Bool,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> _HashSlot {
assert(isCollisionNode)
if !isUnique {
let r = copyNodeAndAppendCollision(inserter)
self = r.node
return r.slot
}
if !hasFreeSpace(Self.spaceForNewItem) {
return resizeNodeAndAppendCollision(inserter)
}
// In-place insert.
update {
let p = $0._makeRoomForNewItem(at: $0.itemsEndSlot, .invalid)
inserter(p)
}
self.count &+= 1
return _HashSlot(self.count &- 1)
}
@inlinable @inline(never)
internal func copyNodeAndAppendCollision(
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (node: _HashNode, slot: _HashSlot) {
assert(isCollisionNode)
assert(self.count == read { $0.collisionCount })
let c = self.count
let node = read { src in
Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in
let srcItems = src.reverseItems
assert(dstItems.count == srcItems.count + 1)
dstItems.dropFirst().initializeAll(fromContentsOf: srcItems)
inserter(dstItems.baseAddress!)
}.node
}
return (node, _HashSlot(c))
}
@inlinable @inline(never)
internal mutating func resizeNodeAndAppendCollision(
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> _HashSlot {
assert(isCollisionNode)
assert(self.count == read { $0.collisionCount })
let c = self.count
self = update { src in
Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in
let srcItems = src.reverseItems
assert(dstItems.count == srcItems.count + 1)
dstItems.dropFirst().moveInitializeAll(fromContentsOf: srcItems)
inserter(dstItems.baseAddress!)
src.clear()
}.node
}
return _HashSlot(c)
}
}
extension _HashNode {
@inlinable
internal func _copyNodeAndReplaceItemWithNewChild(
level: _HashLevel,
_ newChild: __owned _HashNode,
at bucket: _Bucket,
itemSlot: _HashSlot
) -> _HashNode {
let c = self.count
return read { src in
assert(!src.isCollisionNode)
assert(src.itemMap.contains(bucket))
assert(!src.childMap.contains(bucket))
assert(src.itemMap.slot(of: bucket) == itemSlot)
if src.hasSingletonItem && newChild.isCollisionNode {
// Compression
return newChild
}
let childSlot = src.childMap.slot(of: bucket)
return Self.allocate(
itemMap: src.itemMap.removing(bucket),
childMap: src.childMap.inserting(bucket),
count: c &+ newChild.count &- 1
) { dstChildren, dstItems in
let srcChildren = src.children
let srcItems = src.reverseItems
// Initialize children.
dstChildren.prefix(childSlot.value)
.initializeAll(fromContentsOf: srcChildren.prefix(childSlot.value))
let rest = srcChildren.count &- childSlot.value
dstChildren.suffix(rest)
.initializeAll(fromContentsOf: srcChildren.suffix(rest))
dstChildren.initializeElement(at: childSlot.value, to: newChild)
// Initialize items.
dstItems.suffix(itemSlot.value)
.initializeAll(fromContentsOf: srcItems.suffix(itemSlot.value))
let rest2 = dstItems.count &- itemSlot.value
dstItems.prefix(rest2)
.initializeAll(fromContentsOf: srcItems.prefix(rest2))
}.node
}
}
/// The item at `itemSlot` must have already been deinitialized by the time
/// this function is called.
@inlinable
internal mutating func _resizeNodeAndReplaceItemWithNewChild(
level: _HashLevel,
_ newChild: __owned _HashNode,
at bucket: _Bucket,
itemSlot: _HashSlot
) {
let c = self.count
let node: _HashNode = update { src in
assert(!src.isCollisionNode)
assert(src.itemMap.contains(bucket))
assert(!src.childMap.contains(bucket))
assert(src.itemMap.slot(of: bucket) == itemSlot)
let childSlot = src.childMap.slot(of: bucket)
return Self.allocate(
itemMap: src.itemMap.removing(bucket),
childMap: src.childMap.inserting(bucket),
count: c &+ newChild.count &- 1
) { dstChildren, dstItems in
let srcChildren = src.children
let srcItems = src.reverseItems
// Initialize children.
dstChildren.prefix(childSlot.value)
.moveInitializeAll(fromContentsOf: srcChildren.prefix(childSlot.value))
let rest = srcChildren.count &- childSlot.value
dstChildren.suffix(rest)
.moveInitializeAll(fromContentsOf: srcChildren.suffix(rest))
dstChildren.initializeElement(at: childSlot.value, to: newChild)
// Initialize items.
dstItems.suffix(itemSlot.value)
.moveInitializeAll(fromContentsOf: srcItems.suffix(itemSlot.value))
let rest2 = dstItems.count &- itemSlot.value
dstItems.prefix(rest2)
.moveInitializeAll(fromContentsOf: srcItems.prefix(rest2))
src.clear()
}.node
}
self = node
}
}
extension _HashNode {
@inlinable @inline(never)
internal func copyNodeAndPushItemIntoNewChild(
level: _HashLevel,
_ newChild: __owned _HashNode,
at bucket: _Bucket,
itemSlot: _HashSlot
) -> _HashNode {
assert(!isCollisionNode)
let item = read { $0[item: itemSlot] }
let hash = _Hash(item.key)
let r = newChild.inserting(level, item, hash)
return _copyNodeAndReplaceItemWithNewChild(
level: level,
r.node,
at: bucket,
itemSlot: itemSlot)
}
}
extension _HashNode {
@inlinable
internal mutating func ensureUniqueAndSpawnChild(
isUnique: Bool,
level: _HashLevel,
replacing bucket: _Bucket,
itemSlot: _HashSlot,
newHash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (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 = _HashNode._collisionNode(newHash, read { $0[item: .zero] }, inserter)
return (unmanaged, _HashSlot(1))
}
if !isUnique {
let r = copyNodeAndSpawnChild(
level: level,
replacing: bucket,
itemSlot: itemSlot,
existingHash: existingHash,
newHash: newHash,
inserter)
self = r.node
return (r.leaf, r.slot)
}
if !hasFreeSpace(Self.spaceForSpawningChild) {
return resizeNodeAndSpawnChild(
level: level,
replacing: bucket,
itemSlot: itemSlot,
existingHash: existingHash,
newHash: newHash,
inserter)
}
let existing = removeItem(at: bucket, itemSlot)
let r = _HashNode.build(
level: level.descend(),
item1: existing, existingHash,
item2: inserter, newHash)
insertChild(r.top, bucket)
return (r.leaf, r.slot2)
}
@inlinable @inline(never)
internal func copyNodeAndSpawnChild(
level: _HashLevel,
replacing bucket: _Bucket,
itemSlot: _HashSlot,
existingHash: _Hash,
newHash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot) {
let r = read {
_HashNode.build(
level: level.descend(),
item1: $0[item: itemSlot], existingHash,
item2: inserter, newHash)
}
let node = _copyNodeAndReplaceItemWithNewChild(
level: level,
r.top,
at: bucket,
itemSlot: itemSlot)
node._invariantCheck()
return (node, r.leaf, r.slot2)
}
@inlinable @inline(never)
internal mutating func resizeNodeAndSpawnChild(
level: _HashLevel,
replacing bucket: _Bucket,
itemSlot: _HashSlot,
existingHash: _Hash,
newHash: _Hash,
_ inserter: (UnsafeMutablePointer<Element>) -> Void
) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) {
let r = update {
_HashNode.build(
level: level.descend(),
item1: $0.itemPtr(at: itemSlot).move(), existingHash,
item2: inserter, newHash)
}
_resizeNodeAndReplaceItemWithNewChild(
level: level,
r.top,
at: bucket,
itemSlot: itemSlot)
_invariantCheck()
return (r.leaf, r.slot2)
}
}
@@ -0,0 +1,272 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// MARK: Subtree-level in-place mutation operations
extension _HashNode {
@inlinable
internal mutating func ensureUnique(
level: _HashLevel, at path: _UnsafePath
) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) {
ensureUnique(isUnique: isUnique())
guard level < path.level else { return (unmanaged, path.currentItemSlot) }
return update {
$0[child: path.childSlot(at: level)]
.ensureUnique(level: level.descend(), at: path)
}
}
}
extension _HashNode {
@usableFromInline
@frozen
internal struct ValueUpdateState {
@usableFromInline
internal var key: Key
@usableFromInline
internal var value: Value?
@usableFromInline
internal let hash: _Hash
@usableFromInline
internal var path: _UnsafePath
@usableFromInline
internal var found: Bool
@inlinable
internal init(
_ key: Key,
_ hash: _Hash,
_ path: _UnsafePath
) {
self.key = key
self.value = nil
self.hash = hash
self.path = path
self.found = false
}
}
@inlinable
internal mutating func prepareValueUpdate(
_ key: Key,
_ hash: _Hash
) -> ValueUpdateState {
var state = ValueUpdateState(key, hash, _UnsafePath(root: raw))
_prepareValueUpdate(&state)
return state
}
@inlinable
internal mutating func _prepareValueUpdate(
_ state: inout ValueUpdateState
) {
// This doesn't make room for a new item if the key doesn't already exist
// but it does ensure that all parent nodes along its eventual path are
// uniquely held.
//
// If the key already exists, we ensure uniqueness for its node and extract
// its item but otherwise leave the tree as it was.
let isUnique = self.isUnique()
let r = findForInsertion(state.path.level, state.key, state.hash)
switch r {
case .found(_, let slot):
ensureUnique(isUnique: isUnique)
state.path.node = unmanaged
state.path.selectItem(at: slot)
state.found = true
(state.key, state.value) = update { $0.itemPtr(at: slot).move() }
case .insert(_, let slot):
state.path.selectItem(at: slot)
case .appendCollision:
state.path.selectItem(at: _HashSlot(self.count))
case .spawnChild(_, let slot):
state.path.selectItem(at: slot)
case .expansion:
state.path.selectEnd()
case .descend(_, let slot):
ensureUnique(isUnique: isUnique)
update {
let p = $0.childPtr(at: slot)
state.path.descendToChild(p.pointee.unmanaged, at: slot)
p.pointee._prepareValueUpdate(&state)
}
}
}
@inlinable
internal mutating func finalizeValueUpdate(
_ state: __owned ValueUpdateState
) {
switch (state.found, state.value != nil) {
case (true, true):
// Fast path: updating an existing value.
UnsafeHandle.update(state.path.node) {
$0.itemPtr(at: state.path.currentItemSlot)
.initialize(to: (state.key, state.value.unsafelyUnwrapped))
}
case (true, false):
// Removal
let remainder = _finalizeRemoval(.top, state.hash, at: state.path)
assert(remainder == nil)
case (false, true):
// Insertion
let r = updateValue(.top, forKey: state.key, state.hash) {
$0.initialize(to: (state.key, state.value.unsafelyUnwrapped))
}
assert(r.inserted)
case (false, false):
// Noop
break
}
}
@inlinable
internal mutating func _finalizeRemoval(
_ level: _HashLevel, _ hash: _Hash, at path: _UnsafePath
) -> Element? {
assert(isUnique())
if level == path.level {
return _removeItemFromUniqueLeafNode(
level, at: hash[level], path.currentItemSlot, by: { _ in }
).remainder
}
let slot = path.childSlot(at: level)
let remainder = update {
$0[child: slot]._finalizeRemoval(level.descend(), hash, at: path)
}
return _fixupUniqueAncestorAfterItemRemoval(
level, at: { _ in hash[level] }, slot, remainder: remainder)
}
}
extension _HashNode {
@usableFromInline
@frozen
internal struct DefaultedValueUpdateState {
@usableFromInline
internal var item: Element
@usableFromInline
internal var node: _UnmanagedHashNode
@usableFromInline
internal var slot: _HashSlot
@usableFromInline
internal var inserted: Bool
@inlinable
internal init(
_ item: Element,
in node: _UnmanagedHashNode,
at slot: _HashSlot,
inserted: Bool
) {
self.item = item
self.node = node
self.slot = slot
self.inserted = inserted
}
}
@inlinable
internal mutating func prepareDefaultedValueUpdate(
_ level: _HashLevel,
_ key: Key,
_ defaultValue: () -> Value,
_ hash: _Hash
) -> DefaultedValueUpdateState {
let isUnique = self.isUnique()
let r = findForInsertion(level, key, hash)
switch r {
case .found(_, let slot):
ensureUnique(isUnique: isUnique)
return DefaultedValueUpdateState(
update { $0.itemPtr(at: slot).move() },
in: unmanaged,
at: slot,
inserted: false)
case .insert(let bucket, let slot):
ensureUniqueAndInsertItem(
isUnique: isUnique, at: bucket, itemSlot: slot
) { _ in }
return DefaultedValueUpdateState(
(key, defaultValue()),
in: unmanaged,
at: slot,
inserted: true)
case .appendCollision:
let slot = ensureUniqueAndAppendCollision(isUnique: isUnique) { _ in }
return DefaultedValueUpdateState(
(key, defaultValue()),
in: unmanaged,
at: slot,
inserted: true)
case .spawnChild(let bucket, let slot):
let r = ensureUniqueAndSpawnChild(
isUnique: isUnique,
level: level,
replacing: bucket,
itemSlot: slot,
newHash: hash) { _ in }
return DefaultedValueUpdateState(
(key, defaultValue()),
in: r.leaf,
at: r.slot,
inserted: true)
case .expansion:
let r = _HashNode.build(
level: level,
item1: { _ in }, hash,
child2: self, self.collisionHash
)
self = r.top
return DefaultedValueUpdateState(
(key, defaultValue()),
in: r.leaf,
at: r.slot1,
inserted: true)
case .descend(_, let slot):
ensureUnique(isUnique: isUnique)
let res = update {
$0[child: slot].prepareDefaultedValueUpdate(
level.descend(), key, defaultValue, hash)
}
if res.inserted { count &+= 1 }
return res
}
}
@inlinable
internal mutating func finalizeDefaultedValueUpdate(
_ state: __owned DefaultedValueUpdateState
) {
UnsafeHandle.update(state.node) {
$0.itemPtr(at: state.slot).initialize(to: state.item)
}
}
}
@@ -0,0 +1,275 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
// MARK: Subtree-level removal operations
extension _HashNode {
/// Remove the item with the specified key from this subtree and return it.
///
/// This function may leave `self` containing a singleton item.
/// It is up to the caller to detect this situation & correct it when needed,
/// by inlining the remaining item into the parent node.
@inlinable
internal mutating func remove(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (removed: Element, remainder: Element?)? {
guard self.isUnique() else {
guard let r = removing(level, key, hash) else { return nil }
let remainder = self.applyReplacement(level, r.replacement)
return (r.removed, remainder)
}
guard let r = find(level, key, hash) else { return nil }
let bucket = hash[level]
guard r.descend else {
let r = _removeItemFromUniqueLeafNode(level, at: bucket, r.slot) {
$0.move()
}
return (r.result, r.remainder)
}
let r2 = update { $0[child: r.slot].remove(level.descend(), key, hash) }
guard let r2 = r2 else { return nil }
let remainder = _fixupUniqueAncestorAfterItemRemoval(
level,
at: { _ in hash[level] },
r.slot,
remainder: r2.remainder)
return (r2.removed, remainder)
}
}
extension _HashNode {
@inlinable
internal func removing(
_ level: _HashLevel, _ key: Key, _ hash: _Hash
) -> (removed: Element, replacement: Builder)? {
guard let r = find(level, key, hash) else { return nil }
let bucket = hash[level]
guard r.descend else {
return _removingItemFromLeaf(level, at: bucket, r.slot)
}
let r2 = read { $0[child: r.slot].removing(level.descend(), key, hash) }
guard let r2 = r2 else { return nil }
let replacement = self.replacingChild(
level, at: bucket, r.slot, with: r2.replacement)
return (r2.removed, replacement)
}
}
extension _HashNode {
@inlinable
internal mutating func remove(
_ level: _HashLevel, at path: _UnsafePath
) -> (removed: Element, remainder: Element?) {
defer { _invariantCheck() }
guard self.isUnique() else {
let r = removing(level, at: path)
let remainder = applyReplacement(level, r.replacement)
return (r.removed, remainder)
}
if level == path.level {
let slot = path.currentItemSlot
let bucket = read { $0.itemBucket(at: slot) }
let r = _removeItemFromUniqueLeafNode(
level, at: bucket, slot, by: { $0.move() })
return (r.result, r.remainder)
}
let slot = path.childSlot(at: level)
let r = update { $0[child: slot].remove(level.descend(), at: path) }
let remainder = _fixupUniqueAncestorAfterItemRemoval(
level,
at: { $0.childMap.bucket(at: slot) },
slot,
remainder: r.remainder)
return (r.removed, remainder)
}
@inlinable
internal func removing(
_ level: _HashLevel, at path: _UnsafePath
) -> (removed: Element, replacement: Builder) {
if level == path.level {
let slot = path.currentItemSlot
let bucket = read { $0.itemBucket(at: slot) }
return _removingItemFromLeaf(level, at: bucket, slot)
}
let slot = path.childSlot(at: level)
return read {
let bucket = $0.childMap.bucket(at: slot)
let r = $0[child: slot].removing(level.descend(), at: path)
return (
r.removed,
self.replacingChild(level, at: bucket, slot, with: r.replacement))
}
}
}
extension _HashNode {
@inlinable
internal mutating func _removeItemFromUniqueLeafNode<R>(
_ level: _HashLevel,
at bucket: _Bucket,
_ slot: _HashSlot,
by remover: (UnsafeMutablePointer<Element>) -> R
) -> (result: R, remainder: Element?) {
assert(isUnique())
let result = removeItem(at: bucket, slot, by: remover)
if isAtrophied {
self = removeSingletonChild()
}
if hasSingletonItem {
if level.isAtRoot {
if isCollisionNode {
_convertToRegularNode()
}
return (result, nil)
}
let item = removeSingletonItem()
return (result, item)
}
return (result, nil)
}
@inlinable
internal func _removingItemFromLeaf(
_ level: _HashLevel, at bucket: _Bucket, _ slot: _HashSlot
) -> (removed: Element, replacement: Builder) {
read {
if $0.isCollisionNode {
assert(slot.value < $0.collisionCount )
if $0.collisionCount == 2 {
// Node will evaporate
let remainder = _HashSlot(1 &- slot.value)
let bucket = $0.collisionHash[level]
return (
removed: $0[item: slot],
replacement: .item(level, $0[item: remainder], at: bucket))
}
var node = self.copy()
let old = node.removeItem(at: bucket, slot)
node._invariantCheck()
return (old, .collisionNode(level, node))
}
assert($0.itemMap.contains(bucket))
assert(slot == $0.itemMap.slot(of: bucket))
let willAtrophy = (
!$0.isCollisionNode
&& $0.itemMap.hasExactlyOneMember
&& $0.childMap.hasExactlyOneMember
&& $0[child: .zero].isCollisionNode)
if willAtrophy {
// Compression
let child = $0[child: .zero]
let old = $0[item: .zero]
return (old, .collisionNode(level, child))
}
if $0.itemMap.count == 2 && $0.childMap.isEmpty {
// Evaporating node
let remainder = _HashSlot(1 &- slot.value)
var map = $0.itemMap
if remainder != .zero { _ = map.popFirst() }
let bucket = map.first!
return (
removed: $0[item: slot],
replacement: .item(level, $0[item: remainder], at: bucket))
}
var node = self.copy()
let old = node.removeItem(at: bucket, slot)
node._invariantCheck()
return (old, .node(level, node))
}
}
}
extension _HashNode {
@inlinable
internal func _removingChild(
_ 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: _HashSlot(1 &- slot.value)].isCollisionNode
)
if willAtrophy {
// Compression
let child = $0[child: _HashSlot(1 &- slot.value)]
return .collisionNode(level, child)
}
if $0.itemMap.hasExactlyOneMember && $0.childMap.hasExactlyOneMember {
return .item(level, $0[item: .zero], at: $0.itemMap.first!)
}
if $0.hasSingletonChild {
// Evaporate node
return .empty(level)
}
var node = self.copy()
_ = node.removeChild(at: bucket, slot)
node._invariantCheck()
return .node(level, node)
}
}
}
extension _HashNode {
@inlinable
internal mutating func _fixupUniqueAncestorAfterItemRemoval(
_ level: _HashLevel,
at bucket: (UnsafeHandle) -> _Bucket,
_ childSlot: _HashSlot,
remainder: Element?
) -> Element? {
assert(isUnique())
count &-= 1
if let remainder = remainder {
if hasSingletonChild, !level.isAtRoot {
self = ._emptyNode()
return remainder
}
// Child to be inlined has already been cleared, so we need to adjust
// the count manually.
assert(read { $0[child: childSlot].count == 0 })
count &-= 1
let bucket = read { bucket($0) }
ensureUnique(isUnique: true, withFreeSpace: Self.spaceForInlinedChild)
_ = self.removeChild(at: bucket, childSlot)
insertItem(remainder, at: bucket)
return nil
}
if isAtrophied {
self = removeSingletonChild()
}
return nil
}
}
extension _HashNode {
@inlinable
internal mutating func _convertToRegularNode() {
assert(isCollisionNode && hasSingletonItem)
assert(isUnique())
update {
$0.itemMap = _Bitmap($0.collisionHash[.top])
$0.childMap = .empty
$0.bytesFree &+= MemoryLayout<_Hash>.stride
}
}
}
@@ -0,0 +1,295 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _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.
///
/// Handles do not own the storage they access -- it is the client's
/// responsibility to ensure that handles (and any pointer values generated
/// by them) do not escape the closure call that received them.
///
/// A handle can be either read-only or mutable, depending on the method used
/// to access it. In debug builds, methods that modify data trap at runtime if
/// they're called on a read-only view.
@usableFromInline
@frozen
internal struct UnsafeHandle {
@usableFromInline
internal typealias Element = (key: Key, value: Value)
@usableFromInline
internal let _header: UnsafeMutablePointer<_HashNodeHeader>
@usableFromInline
internal let _memory: UnsafeMutableRawPointer
#if DEBUG
@usableFromInline
internal let _isMutable: Bool
#endif
@inlinable
internal init(
_ header: UnsafeMutablePointer<_HashNodeHeader>,
_ memory: UnsafeMutableRawPointer,
isMutable: Bool
) {
self._header = header
self._memory = memory
#if DEBUG
self._isMutable = isMutable
#endif
}
}
}
extension _HashNode.UnsafeHandle {
@inlinable
@inline(__always)
func assertMutable() {
#if DEBUG
assert(_isMutable)
#endif
}
}
extension _HashNode.UnsafeHandle {
@inlinable @inline(__always)
static func read<R>(
_ node: _UnmanagedHashNode,
_ body: (Self) throws -> R
) rethrows -> R {
try node.ref._withUnsafeGuaranteedRef { storage in
try storage.withUnsafeMutablePointers { header, elements in
try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: false))
}
}
}
@inlinable @inline(__always)
static func read<R>(
_ storage: _RawHashStorage,
_ body: (Self) throws -> R
) rethrows -> R {
try storage.withUnsafeMutablePointers { header, elements in
try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: false))
}
}
@inlinable @inline(__always)
static func update<R>(
_ node: _UnmanagedHashNode,
_ body: (Self) throws -> R
) rethrows -> R {
try node.ref._withUnsafeGuaranteedRef { storage in
try storage.withUnsafeMutablePointers { header, elements in
try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: true))
}
}
}
@inlinable @inline(__always)
static func update<R>(
_ storage: _RawHashStorage,
_ body: (Self) throws -> R
) rethrows -> R {
try storage.withUnsafeMutablePointers { header, elements in
try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: true))
}
}
}
extension _HashNode.UnsafeHandle {
@inlinable @inline(__always)
internal var itemMap: _Bitmap {
get {
_header.pointee.itemMap
}
nonmutating set {
assertMutable()
_header.pointee.itemMap = newValue
}
}
@inlinable @inline(__always)
internal var childMap: _Bitmap {
get {
_header.pointee.childMap
}
nonmutating set {
assertMutable()
_header.pointee.childMap = newValue
}
}
@inlinable @inline(__always)
internal var byteCapacity: Int {
_header.pointee.byteCapacity
}
@inlinable @inline(__always)
internal var bytesFree: Int {
get { _header.pointee.bytesFree }
nonmutating set {
assertMutable()
_header.pointee.bytesFree = newValue
}
}
@inlinable @inline(__always)
internal var isCollisionNode: Bool {
_header.pointee.isCollisionNode
}
@inlinable @inline(__always)
internal var collisionCount: Int {
get { _header.pointee.collisionCount }
nonmutating set {
assertMutable()
_header.pointee.collisionCount = newValue
}
}
@inlinable @inline(__always)
internal var collisionHash: _Hash {
get {
assert(isCollisionNode)
return _memory.load(as: _Hash.self)
}
nonmutating set {
assertMutable()
assert(isCollisionNode)
_memory.storeBytes(of: newValue, as: _Hash.self)
}
}
@inlinable @inline(__always)
internal var _childrenStart: UnsafeMutablePointer<_HashNode> {
_memory.assumingMemoryBound(to: _HashNode.self)
}
@inlinable @inline(__always)
internal var hasChildren: Bool {
_header.pointee.hasChildren
}
@inlinable @inline(__always)
internal var childCount: Int {
_header.pointee.childCount
}
@inlinable
internal func childBucket(at slot: _HashSlot) -> _Bucket {
guard !isCollisionNode else { return .invalid }
return childMap.bucket(at: slot)
}
@inlinable @inline(__always)
internal var childrenEndSlot: _HashSlot {
_header.pointee.childrenEndSlot
}
@inlinable
internal var children: UnsafeMutableBufferPointer<_HashNode> {
UnsafeMutableBufferPointer(start: _childrenStart, count: childCount)
}
@inlinable
internal func childPtr(at slot: _HashSlot) -> UnsafeMutablePointer<_HashNode> {
assert(slot.value < childCount)
return _childrenStart + slot.value
}
@inlinable
internal subscript(child slot: _HashSlot) -> _HashNode {
unsafeAddress {
UnsafePointer(childPtr(at: slot))
}
nonmutating unsafeMutableAddress {
assertMutable()
return childPtr(at: slot)
}
}
@inlinable
internal var _itemsEnd: UnsafeMutablePointer<Element> {
(_memory + _header.pointee.byteCapacity)
.assumingMemoryBound(to: Element.self)
}
@inlinable @inline(__always)
internal var hasItems: Bool {
_header.pointee.hasItems
}
@inlinable @inline(__always)
internal var itemCount: Int {
_header.pointee.itemCount
}
@inlinable
internal func itemBucket(at slot: _HashSlot) -> _Bucket {
guard !isCollisionNode else { return .invalid }
return itemMap.bucket(at: slot)
}
@inlinable @inline(__always)
internal var itemsEndSlot: _HashSlot {
_header.pointee.itemsEndSlot
}
@inlinable
internal var reverseItems: UnsafeMutableBufferPointer<Element> {
let c = itemCount
return UnsafeMutableBufferPointer(start: _itemsEnd - c, count: c)
}
@inlinable
internal func itemPtr(at slot: _HashSlot) -> UnsafeMutablePointer<Element> {
assert(slot.value <= itemCount)
return _itemsEnd.advanced(by: -1 &- slot.value)
}
@inlinable
internal subscript(item slot: _HashSlot) -> Element {
unsafeAddress {
UnsafePointer(itemPtr(at: slot))
}
nonmutating unsafeMutableAddress {
assertMutable()
return itemPtr(at: slot)
}
}
@inlinable
internal func clear() {
assertMutable()
_header.pointee.clear()
}
}
extension _HashNode.UnsafeHandle {
@inlinable
internal var hasSingletonItem: Bool {
_header.pointee.hasSingletonItem
}
@inlinable
internal var hasSingletonChild: Bool {
_header.pointee.hasSingletonChild
}
@inlinable
internal var isAtrophiedNode: Bool {
hasSingletonChild && self[child: .zero].isCollisionNode
}
}
@@ -0,0 +1,138 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A node in the hash tree, logically representing a hash table with
/// 32 buckets, corresponding to a 5-bit slice of a full hash value.
///
/// Each bucket may store either a single key-value pair or a reference
/// to a child node that contains additional items.
///
/// To save space, children and items are stored compressed into the two
/// ends of a single raw storage buffer, with the free space in between
/// available for use by either side.
///
/// The storage is arranged as shown below.
///
/// ┌───┬───┬───┬───┬───┬──────────────────┬───┬───┬───┬───┐
/// │ 0 │ 1 │ 2 │ 3 │ 4 │→ free space ←│ 3 │ 2 │ 1 │ 0 │
/// └───┴───┴───┴───┴───┴──────────────────┴───┴───┴───┴───┘
/// children items
///
/// Note that the region for items grows downwards from the end, so the item
/// at slot 0 is at the very end of the buffer.
///
/// Two 32-bit bitmaps are used to associate each child and item with their
/// position in the hash table. The bucket occupied by the *n*th child in the
/// buffer above is identified by position of the *n*th true bit in the child
/// map, and the *n*th item's bucket corresponds to the *n*th true bit in the
/// items map.
@usableFromInline
@frozen
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.
//
// (_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: _RawHashNode
@inlinable
internal init(storage: _RawHashStorage, count: Int) {
self.raw = _RawHashNode(storage: storage, count: count)
}
}
extension _HashNode {
@inlinable @inline(__always)
internal var count: Int {
get { raw.count }
set { raw.count = newValue }
}
}
extension _HashNode {
@inlinable @inline(__always)
internal var unmanaged: _UnmanagedHashNode {
_UnmanagedHashNode(raw.storage)
}
@inlinable @inline(__always)
internal func isIdentical(to other: _UnmanagedHashNode) -> Bool {
raw.isIdentical(to: other)
}
}
extension _HashNode {
@inlinable @inline(__always)
internal func read<R>(
_ body: (UnsafeHandle) throws -> R
) rethrows -> R {
try UnsafeHandle.read(raw.storage, body)
}
@inlinable @inline(__always)
internal mutating func update<R>(
_ body: (UnsafeHandle) throws -> R
) rethrows -> R {
try UnsafeHandle.update(raw.storage, body)
}
}
// MARK: Shortcuts to reading header data
extension _HashNode {
@inlinable
internal var isCollisionNode: Bool {
read { $0.isCollisionNode }
}
@inlinable
internal var collisionHash: _Hash {
read { $0.collisionHash }
}
@inlinable
internal var hasSingletonItem: Bool {
read { $0.hasSingletonItem }
}
@inlinable
internal var hasSingletonChild: Bool {
read { $0.hasSingletonChild }
}
@inlinable
internal var isAtrophied: Bool {
read { $0.isAtrophiedNode }
}
}
extension _HashNode {
@inlinable
internal var initialVersionNumber: UInt {
// Ideally we would simply just generate a true random number, but the
// memory address of the root node is a reasonable substitute.
// Alternatively, we could use a per-thread counter along with a thread
// id, or some sort of global banks of atomic integer counters.
let address = Unmanaged.passUnretained(raw.storage).toOpaque()
return UInt(bitPattern: address)
}
}
@@ -0,0 +1,111 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// 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 `_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 _HashSlot {
@usableFromInline
internal var _value: UInt32
@inlinable @inline(__always)
internal init(_ value: UInt32) {
self._value = value
}
@inlinable @inline(__always)
internal init(_ value: UInt) {
assert(value <= UInt32.max)
self._value = UInt32(truncatingIfNeeded: value)
}
@inlinable @inline(__always)
internal init(_ value: Int) {
assert(value >= 0 && value <= UInt32.max)
self._value = UInt32(truncatingIfNeeded: value)
}
}
extension _HashSlot {
@inlinable @inline(__always)
internal static var zero: _HashSlot { _HashSlot(0) }
}
extension _HashSlot {
@inlinable @inline(__always)
internal var value: Int {
Int(truncatingIfNeeded: _value)
}
}
extension _HashSlot: Equatable {
@inlinable @inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left._value == right._value
}
}
extension _HashSlot: Comparable {
@inlinable @inline(__always)
internal static func <(left: Self, right: Self) -> Bool {
left._value < right._value
}
}
extension _HashSlot: Hashable {
@inlinable
internal func hash(into hasher: inout Hasher) {
hasher.combine(_value)
}
}
extension _HashSlot: CustomStringConvertible {
@usableFromInline
internal var description: String {
"\(_value)"
}
}
extension _HashSlot: Strideable {
@inlinable @inline(__always)
internal func advanced(by n: Int) -> _HashSlot {
assert(n >= 0 || value + n >= 0)
return _HashSlot(_value &+ UInt32(truncatingIfNeeded: n))
}
@inlinable @inline(__always)
internal func distance(to other: _HashSlot) -> Int {
if self < other {
return Int(truncatingIfNeeded: other._value - self._value)
}
return -Int(truncatingIfNeeded: self._value - other._value)
}
}
extension _HashSlot {
@inlinable @inline(__always)
internal func next() -> _HashSlot {
assert(_value < .max)
return _HashSlot(_value &+ 1)
}
@inlinable @inline(__always)
internal func previous() -> _HashSlot {
assert(_value > 0)
return _HashSlot(_value &- 1)
}
}
@@ -0,0 +1,116 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A fixed-size array of just enough size to hold an ancestor path in a
/// `TreeDictionary`.
@usableFromInline
@frozen
internal struct _HashStack<Element> {
#if arch(x86_64) || arch(arm64)
@inlinable
@inline(__always)
internal static var capacity: Int { 13 }
// xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xxxx
@usableFromInline
internal var _contents: (
Element, Element, Element, Element,
Element, Element, Element, Element,
Element, Element, Element, Element,
Element
)
#else
@inlinable
@inline(__always)
internal static var capacity: Int { 7 }
// xxxxx xxxxx xxxxx xxxxx xxxxx xxxxx xx
@usableFromInline
internal var _contents: (
Element, Element, Element, Element,
Element, Element, Element
)
#endif
@usableFromInline
internal var _count: UInt8
@inlinable
internal init(filledWith value: Element) {
assert(Self.capacity == _HashLevel.limit)
#if arch(x86_64) || arch(arm64)
_contents = (
value, value, value, value,
value, value, value, value,
value, value, value, value,
value
)
#else
_contents = (
value, value, value, value,
value, value, value
)
#endif
self._count = 0
}
@inlinable
@inline(__always)
internal var capacity: Int { Self.capacity }
@inlinable
@inline(__always)
internal var count: Int { Int(truncatingIfNeeded: _count) }
@inlinable
@inline(__always)
internal var isEmpty: Bool { _count == 0 }
@inlinable
subscript(level: UInt8) -> Element {
mutating get {
assert(level < _count)
return withUnsafeBytes(of: &_contents) { buffer in
// Homogeneous tuples are layout compatible with their element type
let start = buffer.baseAddress!.assumingMemoryBound(to: Element.self)
return start[Int(truncatingIfNeeded: level)]
}
}
set {
assert(level < capacity)
withUnsafeMutableBytes(of: &_contents) { buffer in
// Homogeneous tuples are layout compatible with their element type
let start = buffer.baseAddress!.assumingMemoryBound(to: Element.self)
start[Int(truncatingIfNeeded: level)] = newValue
}
}
}
@inlinable
mutating func push(_ item: Element) {
assert(_count < capacity)
self[_count] = item
_count &+= 1
}
@inlinable
mutating func pop() -> Element {
assert(_count > 0)
defer { _count &-= 1 }
return self[_count &- 1]
}
@inlinable
mutating func peek() -> Element {
assert(count > 0)
return self[_count &- 1]
}
}
@@ -0,0 +1,131 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
@usableFromInline
@frozen
internal struct _HashTreeIterator {
@usableFromInline
internal struct _Opaque {
internal var ancestorSlots: _AncestorHashSlots
internal var ancestorNodes: _HashStack<_UnmanagedHashNode>
internal var level: _HashLevel
internal var isAtEnd: Bool
@usableFromInline
@_effects(releasenone)
internal init(_ root: _UnmanagedHashNode) {
self.ancestorSlots = .empty
self.ancestorNodes = _HashStack(filledWith: root)
self.level = .top
self.isAtEnd = false
}
}
@usableFromInline
internal let root: _RawHashStorage
@usableFromInline
internal var node: _UnmanagedHashNode
@usableFromInline
internal var slot: _HashSlot
@usableFromInline
internal var endSlot: _HashSlot
@usableFromInline
internal var _o: _Opaque
@usableFromInline
@_effects(releasenone)
internal init(root: __shared _RawHashNode) {
self.root = root.storage
self.node = root.unmanaged
self.slot = .zero
self.endSlot = node.itemsEndSlot
self._o = _Opaque(self.node)
if node.hasItems { return }
if node.hasChildren {
_descendToLeftmostItem(ofChildAtSlot: .zero)
} else {
self._o.isAtEnd = true
}
}
}
extension _HashTreeIterator: IteratorProtocol {
@inlinable
internal mutating func next(
) -> (node: _UnmanagedHashNode, slot: _HashSlot)? {
guard slot < endSlot else {
return _next()
}
defer { slot = slot.next() }
return (node, slot)
}
@usableFromInline
@_effects(releasenone)
internal mutating func _next(
) -> (node: _UnmanagedHashNode, slot: _HashSlot)? {
if _o.isAtEnd { return nil }
if node.hasChildren {
_descendToLeftmostItem(ofChildAtSlot: .zero)
slot = slot.next()
return (node, .zero)
}
while !_o.level.isAtRoot {
let nextChild = _ascend().next()
if nextChild < node.childrenEndSlot {
_descendToLeftmostItem(ofChildAtSlot: nextChild)
slot = slot.next()
return (node, .zero)
}
}
// At end
endSlot = node.itemsEndSlot
slot = endSlot
_o.isAtEnd = true
return nil
}
}
extension _HashTreeIterator {
internal mutating func _descend(toChildSlot childSlot: _HashSlot) {
assert(childSlot < node.childrenEndSlot)
_o.ancestorSlots[_o.level] = childSlot
_o.ancestorNodes.push(node)
_o.level = _o.level.descend()
node = node.unmanagedChild(at: childSlot)
slot = .zero
endSlot = node.itemsEndSlot
}
internal mutating func _ascend() -> _HashSlot {
assert(!_o.level.isAtRoot)
node = _o.ancestorNodes.pop()
_o.level = _o.level.ascend()
let childSlot = _o.ancestorSlots[_o.level]
_o.ancestorSlots.clear(_o.level)
return childSlot
}
internal mutating func _descendToLeftmostItem(
ofChildAtSlot childSlot: _HashSlot
) {
_descend(toChildSlot: childSlot)
while endSlot == .zero {
assert(node.hasChildren)
_descend(toChildSlot: .zero)
}
}
}
@@ -0,0 +1,130 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
public struct _HashTreeStatistics {
/// The number of nodes in the tree.
public internal(set) var nodeCount: Int = 0
/// The number of collision nodes in the tree.
public internal(set) var collisionNodeCount: Int = 0
/// The number of elements within this tree.
public internal(set) var itemCount: Int = 0
/// The number of elements whose keys have colliding hashes in the tree.
public internal(set) var collisionCount: Int = 0
/// The number of key comparisons that need to be done due to hash collisions
/// when finding every key in the tree.
public internal(set) var _collisionChainCount: Int = 0
/// The maximum depth of the tree.
public internal(set) var maxItemDepth: Int = 0
internal var _sumItemDepth: Int = 0
/// The sum of all storage within the tree that is available for item storage,
/// measured in bytes. (This is storage is shared between actual
/// items and child references. Depending on alignment issues, not all of
/// this may be actually usable.)
public internal(set) var capacityBytes: Int = 0
/// The number of bytes of storage currently used for storing items.
public internal(set) var itemBytes: Int = 0
/// The number of bytes of storage currently used for storing child
/// references.
public internal(set) var childBytes: Int = 0
/// The number of bytes currently available for storage, summed over all
/// nodes in the tree.
public internal(set) var freeBytes: Int = 0
/// An estimate of the actual memory occupied by this tree. This includes
/// not only storage space for items & children, but also the memory taken up
/// by node headers and Swift's object headers.
public internal(set) var grossBytes: Int = 0
/// The average level of an item within this tree.
public var averageItemDepth: Double {
guard nodeCount > 0 else { return 0 }
return Double(_sumItemDepth) / Double(itemCount)
}
/// An estimate of how efficiently this data structure manages memory.
/// This is a value between 0 and 1 -- the ratio between how much space
/// the actual stored data occupies and the overall number of bytes allocated
/// for the entire data structure. (`itemBytes / grossBytes`)
public var memoryEfficiency: Double {
guard grossBytes > 0 else { return 1 }
return Double(itemBytes) / Double(grossBytes)
}
public var averageNodeSize: Double {
guard nodeCount > 0 else { return 0 }
return Double(capacityBytes) / Double(nodeCount)
}
/// The average number of keys that need to be compared within the tree
/// to find a member item. This is exactly 1 unless the tree contains hash
/// collisions.
public var averageLookupChainLength: Double {
guard itemCount > 0 else { return 1 }
return Double(itemCount + _collisionChainCount) / Double(itemCount)
}
internal init() {
// Nothing to do
}
}
extension _HashNode {
internal func gatherStatistics(
_ level: _HashLevel, _ stats: inout _HashTreeStatistics
) {
// The empty singleton does not count as a node and occupies no space.
if self.raw.storage === _emptySingleton { return }
read {
stats.nodeCount += 1
stats.itemCount += $0.itemCount
if isCollisionNode {
stats.collisionNodeCount += 1
stats.collisionCount += $0.itemCount
stats._collisionChainCount += $0.itemCount * ($0.itemCount - 1) / 2
}
let keyStride = MemoryLayout<Key>.stride
let valueStride = MemoryLayout<Value>.stride
stats.maxItemDepth = Swift.max(stats.maxItemDepth, level.depth)
stats._sumItemDepth += (level.depth + 1) * $0.itemCount
stats.capacityBytes += $0.byteCapacity
stats.freeBytes += $0.bytesFree
stats.itemBytes += $0.itemCount * (keyStride + valueStride)
stats.childBytes += $0.childCount * MemoryLayout<_RawHashNode>.stride
let objectHeaderSize = 2 * MemoryLayout<Int>.stride
// Note: for simplicity, we assume that there is no padding between
// the object header and the storage header.
let start = _getUnsafePointerToStoredProperties(self.raw.storage)
let capacity = self.raw.storage.capacity
let end = $0._memory + capacity * MemoryLayout<_RawHashNode>.stride
stats.grossBytes += objectHeaderSize + (end - start)
for child in $0.children {
child.gatherStatistics(level.descend(), &stats)
}
}
}
}
@@ -0,0 +1,116 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
extension _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 `_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.
///
/// Handles do not own the storage they access -- it is the client's
/// responsibility to ensure that handles (and any pointer values generated
/// by them) do not escape the closure call that received them.
@usableFromInline
@frozen
internal struct UnsafeHandle {
@usableFromInline
internal let _header: UnsafePointer<_HashNodeHeader>
@usableFromInline
internal let _memory: UnsafeRawPointer
@inlinable
internal init(
_ header: UnsafePointer<_HashNodeHeader>,
_ memory: UnsafeRawPointer
) {
self._header = header
self._memory = memory
}
}
}
extension _RawHashNode.UnsafeHandle {
@inlinable @inline(__always)
static func read<R>(
_ node: _UnmanagedHashNode,
_ body: (Self) throws -> R
) rethrows -> R {
try node.ref._withUnsafeGuaranteedRef { storage in
try storage.withUnsafeMutablePointers { header, elements in
try body(Self(header, UnsafeRawPointer(elements)))
}
}
}
}
extension _RawHashNode.UnsafeHandle {
@inline(__always)
internal var isCollisionNode: Bool {
_header.pointee.isCollisionNode
}
@inline(__always)
internal var collisionHash: _Hash {
assert(isCollisionNode)
return _memory.load(as: _Hash.self)
}
@inline(__always)
internal var hasChildren: Bool {
_header.pointee.hasChildren
}
@inline(__always)
internal var childCount: Int {
_header.pointee.childCount
}
@inline(__always)
internal var childrenEndSlot: _HashSlot {
_header.pointee.childrenEndSlot
}
@inline(__always)
internal var hasItems: Bool {
_header.pointee.hasItems
}
@inline(__always)
internal var itemCount: Int {
_header.pointee.itemCount
}
@inline(__always)
internal var itemsEndSlot: _HashSlot {
_header.pointee.itemsEndSlot
}
@inline(__always)
internal var _childrenStart: UnsafePointer<_RawHashNode> {
_memory.assumingMemoryBound(to: _RawHashNode.self)
}
internal subscript(child slot: _HashSlot) -> _RawHashNode {
unsafeAddress {
assert(slot < childrenEndSlot)
return _childrenStart + slot.value
}
}
internal var children: UnsafeBufferPointer<_RawHashNode> {
UnsafeBufferPointer(start: _childrenStart, count: childCount)
}
}
@@ -0,0 +1,73 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A type-erased node in a hash tree. This doesn't know about the user data
/// stored in the tree, but it has access to subtree counts and it can be used
/// to freely navigate within the tree structure.
///
/// This construct is powerful enough to implement APIs such as `index(after:)`,
/// `distance(from:to:)`, `index(_:offsetBy:)` in non-generic code.
@usableFromInline
@frozen
internal struct _RawHashNode {
@usableFromInline
internal var storage: _RawHashStorage
@usableFromInline
internal var count: Int
@inlinable
internal init(storage: _RawHashStorage, count: Int) {
self.storage = storage
self.count = count
}
}
extension _RawHashNode {
@inline(__always)
internal func read<R>(_ body: (UnsafeHandle) -> R) -> R {
storage.withUnsafeMutablePointers { header, elements in
body(UnsafeHandle(header, UnsafeRawPointer(elements)))
}
}
}
extension _RawHashNode {
@inlinable @inline(__always)
internal var unmanaged: _UnmanagedHashNode {
_UnmanagedHashNode(storage)
}
@inlinable @inline(__always)
internal func isIdentical(to other: _UnmanagedHashNode) -> Bool {
other.ref.toOpaque() == Unmanaged.passUnretained(storage).toOpaque()
}
}
extension _RawHashNode {
@usableFromInline
internal func validatePath(_ path: _UnsafePath) {
var l = _HashLevel.top
var n = self.unmanaged
while l < path.level {
let slot = path.ancestors[l]
precondition(slot < n.childrenEndSlot)
n = n.unmanagedChild(at: slot)
l = l.descend()
}
precondition(n == path.node)
if path._isItem {
precondition(path.nodeSlot < n.itemsEndSlot)
} else {
precondition(path.nodeSlot <= n.childrenEndSlot)
}
}
}
@@ -0,0 +1,135 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// The storage header in a hash tree node. This includes data about the
/// current size and capacity of the node's storage region, as well as
/// information about the currently occupied hash table buckets.
@usableFromInline
@frozen
internal struct _HashNodeHeader {
@usableFromInline
internal var itemMap: _Bitmap
@usableFromInline
internal var childMap: _Bitmap
@usableFromInline
internal var _byteCapacity: UInt32
@usableFromInline
internal var _bytesFree: UInt32
@inlinable
internal init(byteCapacity: Int) {
assert(byteCapacity >= 0 && byteCapacity <= UInt32.max)
self.itemMap = .empty
self.childMap = .empty
self._byteCapacity = UInt32(truncatingIfNeeded: byteCapacity)
self._bytesFree = self._byteCapacity
}
}
extension _HashNodeHeader {
@inlinable @inline(__always)
internal var byteCapacity: Int {
get { Int(truncatingIfNeeded: _byteCapacity) }
}
@inlinable
internal var bytesFree: Int {
@inline(__always)
get { Int(truncatingIfNeeded: _bytesFree) }
set {
assert(newValue >= 0 && newValue <= UInt32.max)
_bytesFree = UInt32(truncatingIfNeeded: newValue)
}
}
}
extension _HashNodeHeader {
@inlinable @inline(__always)
internal var isEmpty: Bool {
return itemMap.isEmpty && childMap.isEmpty
}
@inlinable @inline(__always)
internal var isCollisionNode: Bool {
!itemMap.isDisjoint(with: childMap)
}
@inlinable @inline(__always)
internal var hasChildren: Bool {
itemMap != childMap && !childMap.isEmpty
}
@inlinable @inline(__always)
internal var hasItems: Bool {
!itemMap.isEmpty
}
@inlinable
internal var childCount: Int {
itemMap == childMap ? 0 : childMap.count
}
@inlinable
internal var itemCount: Int {
(itemMap == childMap
? Int(truncatingIfNeeded: itemMap._value)
: itemMap.count)
}
@inlinable
internal var hasSingletonChild: Bool {
itemMap.isEmpty && childMap.hasExactlyOneMember
}
@inlinable
internal var hasSingletonItem: Bool {
if itemMap == childMap {
return itemMap._value == 1
}
return childMap.isEmpty && itemMap.hasExactlyOneMember
}
@inlinable @inline(__always)
internal var childrenEndSlot: _HashSlot {
_HashSlot(childCount)
}
@inlinable @inline(__always)
internal var itemsEndSlot: _HashSlot {
_HashSlot(itemCount)
}
@inlinable
internal var collisionCount: Int {
get {
assert(isCollisionNode)
return Int(truncatingIfNeeded: itemMap._value)
}
set {
assert(isCollisionNode || childMap.isEmpty)
assert(newValue > 0 && newValue < _Bitmap.Value.max)
itemMap._value = _Bitmap.Value(truncatingIfNeeded: newValue)
childMap = itemMap
}
}
}
extension _HashNodeHeader {
@inlinable
internal mutating func clear() {
itemMap = .empty
childMap = .empty
bytesFree = byteCapacity
}
}
@@ -0,0 +1,107 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import _CollectionsUtilities
/// An unsafe, unowned, type-erased reference to a hash tree node; essentially
/// 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
/// `_UnmanagedHashNode`. Doing so results in undefined behavior.
@usableFromInline
@frozen
internal struct _UnmanagedHashNode {
@usableFromInline
internal var ref: Unmanaged<_RawHashStorage>
@inlinable @inline(__always)
internal init(_ storage: _RawHashStorage) {
self.ref = .passUnretained(storage)
}
}
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
/// invalid -- however, it may incorrectly return true in this case.
/// (This can happen when a destroyed node's memory region is later reused for
/// a newly created node.)
@inlinable
internal static func ==(left: Self, right: Self) -> Bool {
left.ref.toOpaque() == right.ref.toOpaque()
}
}
extension _UnmanagedHashNode: CustomStringConvertible {
@usableFromInline
internal var description: String {
_addressString(for: ref.toOpaque())
}
}
extension _UnmanagedHashNode {
@inlinable @inline(__always)
internal func withRaw<R>(_ body: (_RawHashStorage) -> R) -> R {
ref._withUnsafeGuaranteedRef(body)
}
@inline(__always)
internal func read<R>(_ body: (_RawHashNode.UnsafeHandle) -> R) -> R {
ref._withUnsafeGuaranteedRef { storage in
storage.withUnsafeMutablePointers { header, elements in
body(_RawHashNode.UnsafeHandle(header, UnsafeRawPointer(elements)))
}
}
}
@inlinable
internal var hasItems: Bool {
withRaw { $0.header.hasItems }
}
@inlinable
internal var hasChildren: Bool {
withRaw { $0.header.hasChildren }
}
@inlinable
internal var itemCount: Int {
withRaw { $0.header.itemCount }
}
@inlinable
internal var childCount: Int {
withRaw { $0.header.childCount }
}
@inlinable
internal var itemsEndSlot: _HashSlot {
withRaw { _HashSlot($0.header.itemCount) }
}
@inlinable
internal var childrenEndSlot: _HashSlot {
withRaw { _HashSlot($0.header.childCount) }
}
@inlinable
internal func unmanagedChild(at slot: _HashSlot) -> Self {
withRaw { raw in
assert(slot.value < raw.header.childCount)
return raw.withUnsafeMutablePointerToElements { p in
Self(p[slot.value].storage)
}
}
}
}
@@ -0,0 +1,890 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A non-owning, mutable construct representing a path to an item or child node
/// within a hash tree (or the virtual slot addressing the end of the
/// items or children region within a node).
///
/// Path values provide mutating methods to freely navigate around in the tree,
/// including basics such as descending into a child node, ascending to a
/// parent or selecting a particular item within the current node; as well as
/// more complicated methods such as finding the next/previous item in a
/// preorder walk of the tree.
///
/// Paths are, for the most part, represented by a series of slot values
/// identifying a particular branch within each level in the tree up to and
/// including the final node on the path.
///
/// However, to speed up common operations, path values also include a single
/// `_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.
///
/// Note: paths only have a direct reference to their final node. This means
/// that ascending to the parent node requires following the path from the root
/// node down. (Paths could also store references to every node alongside them
/// in a fixed-size array; this would speed up walking over the tree, but it
/// would considerably embiggen the size of the path construct.)
@usableFromInline
@frozen
internal struct _UnsafePath {
@usableFromInline
internal var ancestors: _AncestorHashSlots
@usableFromInline
internal var node: _UnmanagedHashNode
@usableFromInline
internal var nodeSlot: _HashSlot
@usableFromInline
internal var level: _HashLevel
@usableFromInline
internal var _isItem: Bool
@inlinable
internal init(root: __shared _RawHashNode) {
self.level = .top
self.ancestors = .empty
self.node = root.unmanaged
self.nodeSlot = .zero
self._isItem = root.storage.header.hasItems
}
}
extension _UnsafePath {
internal init(
_ level: _HashLevel,
_ ancestors: _AncestorHashSlots,
_ node: _UnmanagedHashNode,
childSlot: _HashSlot
) {
assert(childSlot < node.childrenEndSlot)
self.level = level
self.ancestors = ancestors
self.node = node
self.nodeSlot = childSlot
self._isItem = false
}
@inlinable
internal init(
_ level: _HashLevel,
_ ancestors: _AncestorHashSlots,
_ node: _UnmanagedHashNode,
itemSlot: _HashSlot
) {
assert(itemSlot < node.itemsEndSlot)
self.level = level
self.ancestors = ancestors
self.node = node
self.nodeSlot = itemSlot
self._isItem = true
}
}
extension _UnsafePath: Equatable {
@usableFromInline
@_effects(releasenone)
internal static func ==(left: Self, right: Self) -> Bool {
// Note: we don't compare nodes (node equality should follow from the rest)
left.level == right.level
&& left.ancestors == right.ancestors
&& left.nodeSlot == right.nodeSlot
&& left._isItem == right._isItem
}
}
extension _UnsafePath: Hashable {
@usableFromInline
@_effects(releasenone)
internal func hash(into hasher: inout Hasher) {
// Note: we don't hash nodes, as they aren't compared by ==, either.
hasher.combine(ancestors.path)
hasher.combine(nodeSlot)
hasher.combine(level._shift)
hasher.combine(_isItem)
}
}
extension _UnsafePath: Comparable {
@usableFromInline
@_effects(releasenone)
internal static func <(left: Self, right: Self) -> Bool {
// This implements a total ordering across paths based on the slot
// sequences they contain, corresponding to a preorder walk of the tree.
//
// Paths addressing items within a node are ordered before paths addressing
// a child node within the same node.
var level: _HashLevel = .top
while level < left.level, level < right.level {
let l = left.ancestors[level]
let r = right.ancestors[level]
guard l == r else { return l < r }
level = level.descend()
}
assert(level < left.level || !left.ancestors.hasDataBelow(level))
assert(level < right.level || !right.ancestors.hasDataBelow(level))
if level < right.level {
guard !left._isItem else { return true }
let l = left.nodeSlot
let r = right.ancestors[level]
return l < r
}
if level < left.level {
guard !right._isItem else { return false }
let l = left.ancestors[level]
let r = right.nodeSlot
return l < r
}
guard left._isItem == right._isItem else { return left._isItem }
return left.nodeSlot < right.nodeSlot
}
}
extension _UnsafePath: CustomStringConvertible {
@usableFromInline
internal var description: String {
var d = "@"
var l: _HashLevel = .top
while l < self.level {
d += ".\(self.ancestors[l])"
l = l.descend()
}
if isPlaceholder {
d += ".end[\(self.nodeSlot)]"
} else if isOnItem {
d += "[\(self.nodeSlot)]"
} else if isOnChild {
d += ".\(self.nodeSlot)"
} else if isOnNodeEnd {
d += ".end(\(self.nodeSlot))"
}
return d
}
}
extension _UnsafePath {
/// Returns true if this path addresses an item in the tree; otherwise returns
/// false.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable @inline(__always)
internal var isOnItem: Bool {
// Note: this may be true even if nodeSlot == itemCount (insertion paths).
_isItem
}
/// Returns true if this path addresses the position following a node's last
/// valid item. Such paths can represent the place of an item that might be
/// inserted later; they do not occur while simply iterating over existing
/// items.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
internal var isPlaceholder: Bool {
_isItem && nodeSlot.value == node.itemCount
}
/// Returns true if this path addresses a node in the tree; otherwise returns
/// false.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
internal var isOnChild: Bool {
!_isItem && nodeSlot.value < node.childCount
}
/// Returns true if this path addresses an empty slot within a node in a tree;
/// otherwise returns false.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
internal var isOnNodeEnd: Bool {
!_isItem && nodeSlot.value == node.childCount
}
}
extension _UnsafePath {
/// Returns an unmanaged reference to the child node this path is currently
/// addressing.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
internal var currentChild: _UnmanagedHashNode {
assert(isOnChild)
return node.unmanagedChild(at: nodeSlot)
}
/// Returns the chid slot in this path corresponding to the specified level.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
internal func childSlot(at level: _HashLevel) -> _HashSlot {
assert(level < self.level)
return ancestors[level]
}
/// Returns the slot of the currently addressed item.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable @inline(__always)
internal var currentItemSlot: _HashSlot {
assert(isOnItem)
return nodeSlot
}
}
extension _UnsafePath {
/// Positions this path on the item with the specified slot within its
/// current node.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
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.
assert(slot <= node.itemsEndSlot)
nodeSlot = slot
_isItem = true
}
/// Positions this path on the child with the specified slot within its
/// current node, without descending into it.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
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)
nodeSlot = slot
_isItem = false
}
/// Positions this path on the empty slot at the end of its current node.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@usableFromInline
@_effects(releasenone)
internal mutating func selectEnd() {
nodeSlot = node.childrenEndSlot
_isItem = false
}
/// Descend onto the first path within the currently selected child.
/// (Either the first item if it exists, or the first child. If the child
/// is an empty node (which should not happen in a valid hash tree), then this
/// selects the empty slot at the end of it.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
internal mutating func descend() {
self.node = currentChild
self.ancestors[level] = nodeSlot
self.nodeSlot = .zero
self._isItem = node.hasItems
self.level = level.descend()
}
/// Descend onto the first path within the currently selected child.
/// (Either the first item if it exists, or the first child. If the child
/// is an empty node (which should not happen in a valid hash tree), then this
/// selects the empty slot at the end of it.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@inlinable
internal mutating func descendToChild(
_ child: _UnmanagedHashNode, at slot: _HashSlot
) {
assert(slot < node.childrenEndSlot)
assert(child == node.unmanagedChild(at: slot))
self.node = child
self.ancestors[level] = slot
self.nodeSlot = .zero
self._isItem = node.hasItems
self.level = level.descend()
}
internal mutating func ascend(
to ancestor: _UnmanagedHashNode, at level: _HashLevel
) {
guard level != self.level else { return }
assert(level < self.level)
self.level = level
self.node = ancestor
self.nodeSlot = ancestors[level]
self.ancestors.clear(atOrBelow: level)
self._isItem = false
}
/// Ascend to the nearest ancestor for which the `test` predicate returns
/// true. Because paths do not contain references to every node on them,
/// you need to manually supply a valid reference to the root node. This
/// method visits every node between the root and the current final node on
/// the path.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
internal mutating func ascendToNearestAncestor(
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: _HashLevel = .top
while l < self.level {
let slot = self.ancestors[l]
if test(n, slot) {
best = _UnsafePath(
l, self.ancestors.truncating(to: l), n, childSlot: slot)
}
n = n.unmanagedChild(at: slot)
l = l.descend()
}
guard let best = best else { return false }
self = best
return true
}
}
extension _UnsafePath {
/// Given a path that is on an item, advance it to the next item within its
/// current node, and return true. If there is no next item, position the path
/// on the first child, and return false. If there is no children, position
/// the path on the node's end position, and return false.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
mutating func selectNextItem() -> Bool {
assert(isOnItem)
nodeSlot = nodeSlot.next()
if nodeSlot < node.itemsEndSlot { return true }
nodeSlot = .zero
_isItem = false
return false
}
/// Given a path that is on a child node, advance it to the next child within
/// its current node, and return true. If there is no next child, position
/// the path on the node's end position, and return false.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
mutating func selectNextChild() -> Bool {
assert(!isOnItem)
let childrenEndSlot = node.childrenEndSlot
guard nodeSlot < childrenEndSlot else { return false }
nodeSlot = nodeSlot.next()
return nodeSlot < childrenEndSlot
}
}
extension _UnsafePath {
/// If this path addresses a child node, descend into the leftmost item
/// within the subtree under it (i.e., the first item that would be visited
/// by a preorder walk within that subtree). Do nothing if the path addresses
/// an item or the end position.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
@usableFromInline
@_effects(releasenone)
internal mutating func descendToLeftMostItem() {
while isOnChild {
descend()
}
}
/// Given a path addressing a child node, descend into the rightmost item
/// within the subtree under it (i.e., the last item that would be visited
/// by a preorder walk within that subtree). Do nothing if the path addresses
/// an item or the end position.
///
/// - Note: It is undefined behavior to call this on a path that is no longer
/// valid.
internal mutating func descendToRightMostItem() {
assert(isOnChild)
while true {
descend()
let childrenEndSlot = node.childrenEndSlot
guard childrenEndSlot > .zero else { break }
selectChild(at: childrenEndSlot.previous())
}
let itemsEndSlot = node.itemsEndSlot
assert(itemsEndSlot > .zero)
selectItem(at: itemsEndSlot.previous())
}
/// Find the next item in a preorder walk in the tree following the currently
/// addressed item, and return true. Return false and do nothing if the
/// path does not currently address an item.
@usableFromInline
@_effects(releasenone)
internal mutating func findSuccessorItem(under root: _RawHashNode) -> Bool {
guard isOnItem else { return false }
if selectNextItem() { return true }
if node.hasChildren {
descendToLeftMostItem()
assert(isOnItem)
return true
}
if ascendToNearestAncestor(
under: root, where: { $1.next() < $0.childrenEndSlot }
) {
let r = selectNextChild()
assert(r)
descendToLeftMostItem()
assert(isOnItem)
return true
}
self = _UnsafePath(root: root)
self.selectEnd()
return true
}
/// Find the previous item in a preorder walk in the tree preceding the
/// currently addressed position, and return true.
/// Return false if there is no previous item.
@usableFromInline
@_effects(releasenone)
internal mutating func findPredecessorItem(under root: _RawHashNode) -> Bool {
switch (isOnItem, nodeSlot > .zero) {
case (true, true):
selectItem(at: nodeSlot.previous())
return true
case (false, true):
selectChild(at: nodeSlot.previous())
descendToRightMostItem()
return true
case (false, false):
if node.hasItems {
selectItem(at: node.itemsEndSlot.previous())
return true
}
case (true, false):
break
}
guard
ascendToNearestAncestor(
under: root,
where: { $0.hasItems || $1 > .zero })
else { return false }
if nodeSlot > .zero {
selectChild(at: nodeSlot.previous())
descendToRightMostItem()
return true
}
if node.hasItems {
selectItem(at: node.itemsEndSlot.previous())
return true
}
return false
}
}
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: _HashLevel, of path: _UnsafePath
) -> Int {
if path.isOnNodeEnd { return count }
assert(path.isOnItem)
if level < path.level {
let childSlot = path.childSlot(at: level)
return read {
let prefix = $0.children[..<childSlot.value]
.reduce($0.itemCount) { $0 + $1.count }
let positionWithinChild = $0[child: childSlot]
.preorderPosition(level.descend(), of: path)
return prefix + positionWithinChild
}
}
assert(path.level == level)
return path.nodeSlot.value
}
}
extension _UnsafePath {
/// Set the path to the item at the specified position in a preorder walk
/// of the subtree rooted at the current node.
///
/// - Returns: `(found, remaining)`, where found is true if the item was
/// successfully found, and false otherwise. If `found` is false then
/// `remaining` is the number of items that still need to be skipped to
/// find the correct item (outside this subtree).
/// If `found` is true, then `remaining` is zero.
internal mutating func findItemAtPreorderPosition(
_ position: Int
) -> (found: Bool, remaining: Int) {
assert(position >= 0)
let top = node
let topLevel = level
var stop = false
var remaining = position
while !stop {
let itemCount = node.itemCount
if remaining < itemCount {
selectItem(at: _HashSlot(remaining))
return (true, 0)
}
remaining -= itemCount
node.read {
let children = $0.children
for i in children.indices {
let c = children[i].count
if remaining < c {
descendToChild(children[i].unmanaged, at: _HashSlot(i))
return
}
remaining &-= c
}
stop = true
}
}
ascend(to: top, at: topLevel)
selectEnd()
return (false, remaining)
}
}
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.
///
/// This method must only be called on the root node.
@usableFromInline
@_effects(releasenone)
internal func distance(
_ level: _HashLevel, from start: _UnsafePath, to end: _UnsafePath
) -> Int {
assert(level.isAtRoot)
if start.isOnNodeEnd {
// Shortcut: distance from end.
return preorderPosition(level, of: end) - count
}
if end.isOnNodeEnd {
// Shortcut: distance to end.
return count - preorderPosition(level, of: start)
}
assert(start.isOnItem)
assert(end.isOnItem)
if start.level == end.level, start.ancestors == end.ancestors {
// Shortcut: the paths are under the same node.
precondition(start.node == end.node, "Internal index validation error")
return start.currentItemSlot.distance(to: end.currentItemSlot)
}
if
start.level < end.level,
start.ancestors.isEqual(to: end.ancestors, upTo: start.level)
{
// Shortcut: start's node is an ancestor of end's position.
return start.node._distance(
start.level, fromItemAt: start.currentItemSlot, to: end)
}
if start.ancestors.isEqual(to: end.ancestors, upTo: end.level) {
// Shortcut: end's node is an ancestor of start's position.
return -end.node._distance(
end.level, fromItemAt: end.currentItemSlot, to: start)
}
// No shortcuts -- the two paths are in different subtrees.
// Start descending from the root to look for the closest common
// ancestor.
if start < end {
return _distance(level, from: start, to: end)
}
return -_distance(level, from: end, to: start)
}
internal func _distance(
_ level: _HashLevel, from start: _UnsafePath, to end: _UnsafePath
) -> Int {
assert(start < end)
assert(level < start.level)
assert(level < end.level)
let slot1 = start.childSlot(at: level)
let slot2 = end.childSlot(at: level)
if slot1 == slot2 {
return read {
$0[child: slot1]._distance(level.descend(), from: start, to: end)
}
}
return read {
let children = $0.children
let d1 = children[slot1.value]
.preorderPosition(level.descend(), of: start)
let d2 = children[slot1.value &+ 1 ..< slot2.value]
.reduce(0) { $0 + $1.count }
let d3 = children[slot2.value]
.preorderPosition(level.descend(), of: end)
return (children[slot1.value].count - d1) + d2 + d3
}
}
}
extension _UnmanagedHashNode {
internal func _distance(
_ level: _HashLevel, fromItemAt start: _HashSlot, to end: _UnsafePath
) -> Int {
read {
assert(start < $0.itemsEndSlot)
assert(level < end.level)
let childSlot = end.childSlot(at: level)
let children = $0.children
let prefix = children[..<childSlot.value]
.reduce($0.itemCount - start.value) { $0 + $1.count }
let positionWithinChild = children[childSlot.value]
.preorderPosition(level.descend(), of: end)
return prefix + positionWithinChild
}
}
}
extension _HashNode {
/// Return the path to the given key in this tree if it exists; otherwise
/// return nil.
@inlinable
internal func path(
to key: Key, _ hash: _Hash
) -> _UnsafePath? {
var node = unmanaged
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 }
guard r.descend else {
return _UnsafePath(level, ancestors, node, itemSlot: r.slot)
}
node = node.unmanagedChild(at: r.slot)
ancestors[level] = r.slot
level = level.descend()
}
return nil
}
}
extension _RawHashNode {
@usableFromInline
@_effects(releasenone)
internal func seek(
_ level: _HashLevel,
_ path: inout _UnsafePath,
offsetBy distance: Int,
limitedBy limit: _UnsafePath
) -> (found: Bool, limited: Bool) {
assert(level.isAtRoot)
if (distance > 0 && limit < path) || (distance < 0 && limit > path) {
return (seek(level, &path, offsetBy: distance), false)
}
var d = distance
guard self._seek(level, &path, offsetBy: &d) else {
path = limit
return (distance >= 0 && d == 0 && limit.isOnNodeEnd, true)
}
let found = (
distance == 0
|| (distance > 0 && path <= limit)
|| (distance < 0 && path >= limit))
return (found, true)
}
@usableFromInline
@_effects(releasenone)
internal func seek(
_ level: _HashLevel,
_ path: inout _UnsafePath,
offsetBy distance: Int
) -> Bool {
var d = distance
if self._seek(level, &path, offsetBy: &d) {
return true
}
if distance > 0, d == 0 { // endIndex
return true
}
return false
}
internal func _seek(
_ level: _HashLevel,
_ path: inout _UnsafePath,
offsetBy distance: inout Int
) -> Bool {
// This is a bit complicated, because we only have a direct reference to the
// final node on the path, and we want to avoid having to descend
// from the root down if the target item stays within the original node's
// subtree. So we first figure out the subtree situation, and only start the
// recursion if the target is outside of it.
assert(level.isAtRoot)
assert(path.isOnItem || path.isOnNodeEnd)
guard distance != 0 else { return true }
if distance > 0 {
if !path.isOnItem { return false }
// Try a local search within the subtree starting at the current node.
let slot = path.currentItemSlot
let r = path.findItemAtPreorderPosition(distance &+ slot.value)
if r.found {
assert(r.remaining == 0)
return true
}
assert(r.remaining >= 0 && r.remaining <= distance)
distance = r.remaining
// Fall back to recursively descending from the root.
return _seekForward(level, by: &distance, fromSubtree: &path)
}
// distance < 0
if !path.isOnNodeEnd {
// Shortcut: see if the destination item is within the same node.
// (Doing this here allows us to avoid having to descend from the root
// down only to figure this out.)
let slot = path.nodeSlot
distance &+= slot.value
if distance >= 0 {
path.selectItem(at: _HashSlot(distance))
distance = 0
return true
}
}
// Otherwise we need to visit ancestor nodes to find the item at the right
// position. We also do this when we start from the end index -- there
// will be no recursion in that case anyway.
return _seekBackward(level, by: &distance, fromSubtree: &path)
}
/// 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: _HashLevel,
by distance: inout Int,
fromSubtree path: inout _UnsafePath
) -> Bool {
assert(distance >= 0)
assert(level <= path.level)
guard level < path.level else {
path.selectEnd()
return false
}
return read {
let children = $0.children
var i = path.childSlot(at: level).value
if children[i]._seekForward(
level.descend(), by: &distance, fromSubtree: &path
) {
assert(distance == 0)
return true
}
path.ascend(to: unmanaged, at: level)
i &+= 1
while i < children.endIndex {
let c = children[i].count
if distance < c {
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)
distance = 0
return true
}
distance &-= c
i &+= 1
}
path.selectEnd()
return false
}
}
/// 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: _HashLevel,
by distance: inout Int,
fromSubtree path: inout _UnsafePath
) -> Bool {
assert(distance < 0)
assert(level <= path.level)
return read {
let children = $0.children
var slot: _HashSlot
if level < path.level {
// We need to descend to the end of the path before we can start the
// search for real.
slot = path.childSlot(at: level)
if children[slot.value]._seekBackward(
level.descend(), by: &distance, fromSubtree: &path
) {
// A deeper level has found the target item.
assert(distance == 0)
return true
}
// No luck yet -- ascend to this node and look through preceding data.
path.ascend(to: unmanaged, at: level)
} else if path.isOnNodeEnd {
// When we start from the root's end (the end index), we don't need
// to descend before starting to look at previous children.
assert(level.isAtRoot && path.node == self.unmanaged)
slot = path.node.childrenEndSlot
} else { // level == path.level
// The outermost caller has already gone as far back as possible
// within the original subtree. Return a level higher to actually
// start the rest of the search.
return false
}
// Look through all preceding children for the target item.
while slot > .zero {
slot = slot.previous()
let c = children[slot.value].count
if c + distance >= 0 {
path.descendToChild(children[slot.value].unmanaged, at: slot)
let r = path.findItemAtPreorderPosition(c + distance)
precondition(r.found, "Internal inconsistency: invalid node counts")
distance = 0
return true
}
distance += c
}
// See if the target is hiding somwhere in our immediate items.
distance &+= $0.itemCount
if distance >= 0 {
path.selectItem(at: _HashSlot(distance))
distance = 0
return true
}
// No joy -- we need to continue searching a level higher.
assert(distance < 0)
return false
}
}
}