mirror of
https://github.com/apple/swift-collections
synced 2026-11-27 04:54:21 +00:00
[PersistentCollections] offset → slot
(Internally) standardize on using the word “slot” to refer to an id for a location within a contiguous storage buffer that can hold a single item of some kind. “Offset” is sometimes used in public APIs (to refer to integer distances within collections, relative to some start position), and using the same term here causes internal naming difficulties. A “bucket” is therefore a more specific name for a slot within a hash table.
This commit is contained in:
1 parent
bf3617e379
commit
0fe7f080c0
17 files changed
+414
-269
No files matched your search
@@ -11,7 +11,7 @@
|
||||
|
||||
@usableFromInline
|
||||
@frozen
|
||||
struct _AncestorOffsets {
|
||||
struct _AncestorSlots {
|
||||
@usableFromInline
|
||||
internal var path: UInt
|
||||
|
||||
@@ -21,37 +21,37 @@ struct _AncestorOffsets {
|
||||
}
|
||||
}
|
||||
|
||||
extension _AncestorOffsets: Equatable {
|
||||
extension _AncestorSlots: Equatable {
|
||||
@inlinable @inline(__always)
|
||||
internal static func ==(left: Self, right: Self) -> Bool {
|
||||
left.path == right.path
|
||||
}
|
||||
}
|
||||
|
||||
extension _AncestorOffsets {
|
||||
extension _AncestorSlots {
|
||||
@inlinable @inline(__always)
|
||||
internal static var empty: Self { Self(0) }
|
||||
}
|
||||
|
||||
extension _AncestorOffsets {
|
||||
extension _AncestorSlots {
|
||||
@inlinable @inline(__always)
|
||||
internal subscript(_ level: _Level) -> Int {
|
||||
internal subscript(_ level: _Level) -> _Slot {
|
||||
get {
|
||||
assert(level.shift < UInt.bitWidth)
|
||||
return Int(bitPattern: (path &>> level.shift) & _Bucket.bitMask)
|
||||
return _Slot((path &>> level.shift) & _Bucket.bitMask)
|
||||
}
|
||||
set {
|
||||
assert(newValue < UInt.bitWidth)
|
||||
assert(self[level] == 0)
|
||||
path |= (UInt(bitPattern: newValue) &<< level.shift)
|
||||
assert(newValue._value < UInt.bitWidth)
|
||||
assert(self[level] == .zero)
|
||||
path |= (UInt(truncatingIfNeeded: newValue._value) &<< level.shift)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func truncating(to level: _Level) -> _AncestorOffsets {
|
||||
internal func truncating(to level: _Level) -> _AncestorSlots {
|
||||
assert(level.shift <= UInt.bitWidth)
|
||||
guard level.shift < UInt.bitWidth else { return self }
|
||||
return _AncestorOffsets(path & ((1 &<< level.shift) &- 1))
|
||||
return _AncestorSlots(path & ((1 &<< level.shift) &- 1))
|
||||
}
|
||||
|
||||
@inlinable
|
||||
|
||||
@@ -105,13 +105,13 @@ extension _Bitmap {
|
||||
}
|
||||
|
||||
@inlinable @inline(__always)
|
||||
internal func offset(of bucket: _Bucket) -> Int {
|
||||
_value._rank(ofBit: bucket.value)
|
||||
internal func slot(of bucket: _Bucket) -> _Slot {
|
||||
_Slot(_value._rank(ofBit: bucket.value))
|
||||
}
|
||||
|
||||
@inlinable @inline(__always)
|
||||
internal func bucket(at offset: Int) -> _Bucket {
|
||||
_Bucket(_value._bit(ranked: offset)!)
|
||||
internal func bucket(at slot: _Slot) -> _Bucket {
|
||||
_Bucket(_value._bit(ranked: slot.value)!)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,8 +40,8 @@ extension _Node.Storage {
|
||||
}
|
||||
|
||||
extension _Node.UnsafeHandle {
|
||||
internal func _itemString(at offset: Int) -> String {
|
||||
let item = self[item: offset]
|
||||
internal func _itemString(at slot: _Slot) -> String {
|
||||
let item = self[item: slot]
|
||||
let hash = _Hash(item.key).description
|
||||
return "hash: \(hash), key: \(item.key), value: \(item.value)"
|
||||
}
|
||||
@@ -73,39 +73,39 @@ extension _Node.UnsafeHandle {
|
||||
""")
|
||||
guard limit > 0 else { return }
|
||||
if iterationOrder {
|
||||
for offset in 0 ..< itemCount {
|
||||
print(" \(restPrefix)[\(offset)] \(_itemString(at: offset))")
|
||||
for slot in stride(from: .zero, to: itemEnd, by: 1) {
|
||||
print(" \(restPrefix)[\(slot)] \(_itemString(at: slot))")
|
||||
}
|
||||
for offset in 0 ..< childCount {
|
||||
self[child: offset].dump(
|
||||
for slot in stride(from: .zero, to: childEnd, by: 1) {
|
||||
self[child: slot].dump(
|
||||
iterationOrder: true,
|
||||
limit: limit - 1,
|
||||
firstPrefix: " \(restPrefix).\(offset)",
|
||||
restPrefix: " \(restPrefix).\(offset)",
|
||||
firstPrefix: " \(restPrefix).\(slot)",
|
||||
restPrefix: " \(restPrefix).\(slot)",
|
||||
depth: depth + 1)
|
||||
}
|
||||
}
|
||||
else if isCollisionNode {
|
||||
for offset in 0 ..< itemCount {
|
||||
print("\(restPrefix)[\(offset)] \(_itemString(at: offset))")
|
||||
for slot in stride(from: .zero, to: itemEnd, by: 1) {
|
||||
print("\(restPrefix)[\(slot)] \(_itemString(at: slot))")
|
||||
}
|
||||
} else {
|
||||
var itemOffset = 0
|
||||
var childOffset = 0
|
||||
var itemSlot: _Slot = .zero
|
||||
var childSlot: _Slot = .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: itemOffset))")
|
||||
itemOffset += 1
|
||||
print("\(restPrefix) \(bucketStr) \(_itemString(at: itemSlot))")
|
||||
itemSlot = itemSlot.next()
|
||||
} else if childMap.contains(bucket) {
|
||||
self[child: childOffset].dump(
|
||||
self[child: childSlot].dump(
|
||||
iterationOrder: false,
|
||||
limit: limit - 1,
|
||||
firstPrefix: "\(restPrefix) \(bucketStr) ",
|
||||
restPrefix: "\(restPrefix) ",
|
||||
depth: depth + 1)
|
||||
childOffset += 1
|
||||
childSlot = childSlot.next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ extension _Node {
|
||||
update {
|
||||
$0.childMap.insert(bucket)
|
||||
$0.bytesFree &-= MemoryLayout<_Node>.stride
|
||||
$0.childPtr(at: 0).initialize(to: _child)
|
||||
$0.childPtr(at: .zero).initialize(to: _child)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,8 +71,8 @@ extension _Node {
|
||||
$0.itemMap.insert(itemBucket)
|
||||
$0.childMap.insert(childBucket)
|
||||
$0.bytesFree &-= MemoryLayout<Element>.stride + MemoryLayout<_Node>.stride
|
||||
$0.itemPtr(at: 0).initialize(to: _item)
|
||||
$0.childPtr(at: 0).initialize(to: child)
|
||||
$0.itemPtr(at: .zero).initialize(to: _item)
|
||||
$0.childPtr(at: .zero).initialize(to: child)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ extension _Node {
|
||||
#if COLLECTIONS_INTERNAL_CHECKS
|
||||
@usableFromInline @inline(never)
|
||||
internal func _invariantCheck() {
|
||||
storage.header._invariantCheck()
|
||||
raw.storage.header._invariantCheck()
|
||||
read {
|
||||
let itemBytes = $0.itemCount * MemoryLayout<Element>.stride
|
||||
let childBytes = $0.childCount * MemoryLayout<_Node>.stride
|
||||
@@ -55,31 +55,31 @@ extension _Node {
|
||||
if $0.isCollisionNode {
|
||||
precondition(count == $0.itemCount)
|
||||
precondition(count > 0)
|
||||
let key = $0[item: 0].key
|
||||
let key = $0[item: .zero].key
|
||||
let hash = _Hash(key)
|
||||
precondition(
|
||||
hash.isEqual(to: path, upTo: level),
|
||||
"Misplaced colliding key '\(key)': \(path) isn't a prefix of \(hash)")
|
||||
for item in $0._items.dropFirst() {
|
||||
for item in $0.reverseItems.dropFirst() {
|
||||
precondition(_Hash(item.key) == hash)
|
||||
}
|
||||
}
|
||||
var itemOffset = 0
|
||||
var childOffset = 0
|
||||
var itemSlot: _Slot = .zero
|
||||
var childSlot: _Slot = .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._items[itemOffset].key
|
||||
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)")
|
||||
itemOffset += 1
|
||||
itemSlot = itemSlot.next()
|
||||
}
|
||||
if $0.hasChildren && $0.childMap.contains(bucket) {
|
||||
$0[child: childOffset]._fullInvariantCheck(level.descend(), path)
|
||||
childOffset += 1
|
||||
$0[child: childSlot]._fullInvariantCheck(level.descend(), path)
|
||||
childSlot = childSlot.next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,30 +23,30 @@
|
||||
@frozen
|
||||
internal enum _FindResult {
|
||||
/// The item we're looking for is stored directly in this node, at the
|
||||
/// bucket / item offset identified in the payload.
|
||||
/// 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, Int)
|
||||
case found(_Bucket, _Slot)
|
||||
/// 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 offset. (Which is currently empty.)
|
||||
/// at the specified bucket / item slot. (Which is currently empty.)
|
||||
///
|
||||
/// If the current node is a collision node, then the bucket value is
|
||||
/// set to `_Bucket.invalid`.
|
||||
case notFound(_Bucket, Int)
|
||||
case notFound(_Bucket, _Slot)
|
||||
/// 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 offset. However, that bucket is already
|
||||
/// 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 newCollision(_Bucket, Int)
|
||||
case newCollision(_Bucket, _Slot)
|
||||
/// 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
|
||||
@@ -67,10 +67,10 @@ internal enum _FindResult {
|
||||
case expansion(_Hash)
|
||||
/// 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 & offset.
|
||||
/// bucket & slot.
|
||||
///
|
||||
/// (This case is never returned if the current node is a collision node.)
|
||||
case descend(_Bucket, Int)
|
||||
case descend(_Bucket, _Slot)
|
||||
}
|
||||
|
||||
extension _Node {
|
||||
@@ -89,32 +89,32 @@ extension _Node.UnsafeHandle {
|
||||
) -> _FindResult {
|
||||
guard !isCollisionNode else {
|
||||
if !level.isAtBottom {
|
||||
let h = _Hash(self[item: 0].key)
|
||||
let h = _Hash(self[item: .zero].key)
|
||||
if h != hash {
|
||||
return .expansion(h)
|
||||
}
|
||||
}
|
||||
// Note: this searches the items in reverse insertion order.
|
||||
guard let offset = reverseItems.firstIndex(where: { $0.key == key }) else {
|
||||
return .notFound(.invalid, itemCount)
|
||||
guard let slot = reverseItems.firstIndex(where: { $0.key == key }) else {
|
||||
return .notFound(.invalid, itemEnd)
|
||||
}
|
||||
return .found(.invalid, itemCount &- 1 &- offset)
|
||||
return .found(.invalid, _Slot(itemCount &- 1 &- slot))
|
||||
}
|
||||
let bucket = hash[level]
|
||||
if itemMap.contains(bucket) {
|
||||
let offset = itemMap.offset(of: bucket)
|
||||
if self[item: offset].key == key {
|
||||
return .found(bucket, offset)
|
||||
let slot = itemMap.slot(of: bucket)
|
||||
if self[item: slot].key == key {
|
||||
return .found(bucket, slot)
|
||||
}
|
||||
return .newCollision(bucket, offset)
|
||||
return .newCollision(bucket, slot)
|
||||
}
|
||||
if childMap.contains(bucket) {
|
||||
let offset = childMap.offset(of: bucket)
|
||||
return .descend(bucket, offset)
|
||||
let slot = childMap.slot(of: bucket)
|
||||
return .descend(bucket, slot)
|
||||
}
|
||||
// Don't calculate the offset unless the caller will need it.
|
||||
let offset = forInsert ? itemMap.offset(of: bucket) : 0
|
||||
return .notFound(bucket, offset)
|
||||
// Don't calculate the slot unless the caller will need it.
|
||||
let slot = forInsert ? itemMap.slot(of: bucket) : .zero
|
||||
return .notFound(bucket, slot)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,12 +126,12 @@ extension _Node {
|
||||
read {
|
||||
let r = $0.find(level, key, hash, forInsert: false)
|
||||
switch r {
|
||||
case .found(_, let offset):
|
||||
return $0[item: offset].value
|
||||
case .found(_, let slot):
|
||||
return $0[item: slot].value
|
||||
case .notFound, .newCollision, .expansion:
|
||||
return nil
|
||||
case .descend(_, let offset):
|
||||
return $0[child: offset].get(level.descend(), key, hash)
|
||||
case .descend(_, let slot):
|
||||
return $0[child: slot].get(level.descend(), key, hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -147,8 +147,8 @@ extension _Node {
|
||||
return true
|
||||
case .notFound, .newCollision, .expansion:
|
||||
return false
|
||||
case .descend(_, let offset):
|
||||
return $0[child: offset].containsKey(level.descend(), key, hash)
|
||||
case .descend(_, let slot):
|
||||
return $0[child: slot].containsKey(level.descend(), key, hash)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -161,17 +161,18 @@ extension _Node {
|
||||
) -> Int? {
|
||||
let r = find(level, key, hash, forInsert: false)
|
||||
switch r {
|
||||
case .found(_, let offset):
|
||||
return offset
|
||||
case .found(_, let slot):
|
||||
return slot.value
|
||||
case .notFound, .newCollision, .expansion:
|
||||
return nil
|
||||
case .descend(_, let offset):
|
||||
case .descend(_, let slot):
|
||||
return read { h in
|
||||
let children = h._children
|
||||
let p = children[offset].position(forKey: key, level.descend(), hash)
|
||||
let p = children[slot.value]
|
||||
.position(forKey: key, level.descend(), hash)
|
||||
guard let p = p else { return nil }
|
||||
let c = h.itemCount &+ p
|
||||
return children[..<offset].reduce(into: c) { $0 &+= $1.count }
|
||||
return children[..<slot.value].reduce(into: c) { $0 &+= $1.count }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -183,7 +184,7 @@ extension _Node {
|
||||
var itemsToSkip = position
|
||||
let itemCount = $0.itemCount
|
||||
if itemsToSkip < itemCount {
|
||||
return $0[item: itemsToSkip]
|
||||
return $0[item: _Slot(itemsToSkip)]
|
||||
}
|
||||
itemsToSkip -= itemCount
|
||||
let children = $0._children
|
||||
|
||||
@@ -12,16 +12,16 @@
|
||||
// MARK: Node-level mutation operations
|
||||
|
||||
extension _Node.UnsafeHandle {
|
||||
/// Insert `item` at `offset` corresponding to `bucket`.
|
||||
/// Insert `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`.
|
||||
@inlinable
|
||||
internal func _insertItem(_ item: __owned Element, at offset: Int) {
|
||||
internal func _insertItem(_ item: __owned Element, at slot: _Slot) {
|
||||
assertMutable()
|
||||
let c = itemCount
|
||||
assert(offset >= 0 && offset <= c)
|
||||
assert(slot.value <= c)
|
||||
|
||||
let stride = MemoryLayout<Element>.stride
|
||||
assert(bytesFree >= stride)
|
||||
@@ -31,44 +31,44 @@ extension _Node.UnsafeHandle {
|
||||
.advanced(by: byteCapacity &- (c &+ 1) &* stride)
|
||||
.bindMemory(to: Element.self, capacity: 1)
|
||||
|
||||
let prefix = c &- offset
|
||||
let prefix = c &- slot.value
|
||||
start.moveInitialize(from: start + 1, count: prefix)
|
||||
(start + prefix).initialize(to: item)
|
||||
}
|
||||
|
||||
/// Insert `child` at `offset`. There must be enough free space in the node
|
||||
/// 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 _Node, at offset: Int) {
|
||||
internal func _insertChild(_ child: __owned _Node, at slot: _Slot) {
|
||||
assertMutable()
|
||||
assert(!isCollisionNode)
|
||||
|
||||
let c = childMap.count
|
||||
assert(offset >= 0 && offset <= c)
|
||||
assert(slot.value <= c)
|
||||
|
||||
let stride = MemoryLayout<_Node>.stride
|
||||
assert(bytesFree >= stride)
|
||||
bytesFree &-= stride
|
||||
|
||||
_memory.bindMemory(to: _Node.self, capacity: c &+ 1)
|
||||
let q = _childrenStart + offset
|
||||
(q + 1).moveInitialize(from: q, count: c &- offset)
|
||||
let q = _childrenStart + slot.value
|
||||
(q + 1).moveInitialize(from: q, count: c &- slot.value)
|
||||
q.initialize(to: child)
|
||||
}
|
||||
|
||||
/// Remove and return the item at `offset`, increasing the amount of free
|
||||
/// 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(at offset: Int) -> Element {
|
||||
internal func _removeItem(at slot: _Slot) -> Element {
|
||||
assertMutable()
|
||||
let c = itemCount
|
||||
assert(offset >= 0 && offset < c)
|
||||
assert(slot.value < c)
|
||||
let stride = MemoryLayout<Element>.stride
|
||||
bytesFree &+= stride
|
||||
|
||||
@@ -76,30 +76,30 @@ extension _Node.UnsafeHandle {
|
||||
.advanced(by: byteCapacity &- stride &* c)
|
||||
.assumingMemoryBound(to: Element.self)
|
||||
|
||||
let prefix = c &- 1 &- offset
|
||||
let prefix = c &- 1 &- slot.value
|
||||
let q = start + prefix
|
||||
let item = q.move()
|
||||
(start + 1).moveInitialize(from: start, count: prefix)
|
||||
return item
|
||||
}
|
||||
|
||||
/// Remove and return the child at `offset`, increasing the amount of free
|
||||
/// 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 offset: Int) -> _Node {
|
||||
internal func _removeChild(at slot: _Slot) -> _Node {
|
||||
assertMutable()
|
||||
assert(!isCollisionNode)
|
||||
let count = childCount
|
||||
assert(offset >= 0 && offset < count)
|
||||
assert(slot.value < count)
|
||||
|
||||
bytesFree &+= MemoryLayout<_Node>.stride
|
||||
|
||||
let q = _childrenStart + offset
|
||||
let q = _childrenStart + slot.value
|
||||
let child = q.move()
|
||||
q.moveInitialize(from: q + 1, count: count &- 1 &- offset)
|
||||
q.moveInitialize(from: q + 1, count: count &- 1 &- slot.value)
|
||||
return child
|
||||
}
|
||||
}
|
||||
@@ -109,19 +109,19 @@ extension _Node {
|
||||
internal mutating func insertItem(
|
||||
_ item: __owned Element, _ bucket: _Bucket
|
||||
) {
|
||||
let offset = read { $0.itemMap.offset(of: bucket) }
|
||||
self.insertItem(item, at: offset, bucket)
|
||||
let slot = read { $0.itemMap.slot(of: bucket) }
|
||||
self.insertItem(item, at: slot, bucket)
|
||||
}
|
||||
|
||||
/// Insert `item` at `offset` corresponding to `bucket`.
|
||||
/// Insert `item` at `slot` corresponding to `bucket`.
|
||||
/// There must be enough free space in the node to fit the new item.
|
||||
@inlinable
|
||||
internal mutating func insertItem(
|
||||
_ item: __owned Element, at offset: Int, _ bucket: _Bucket
|
||||
_ item: __owned Element, at slot: _Slot, _ bucket: _Bucket
|
||||
) {
|
||||
self.count &+= 1
|
||||
update {
|
||||
$0._insertItem(item, at: offset)
|
||||
$0._insertItem(item, at: slot)
|
||||
if $0.isCollisionNode {
|
||||
assert(bucket.isInvalid)
|
||||
$0.collisionCount &+= 1
|
||||
@@ -129,7 +129,7 @@ extension _Node {
|
||||
assert(!$0.itemMap.contains(bucket))
|
||||
assert(!$0.childMap.contains(bucket))
|
||||
$0.itemMap.insert(bucket)
|
||||
assert($0.itemMap.offset(of: bucket) == offset)
|
||||
assert($0.itemMap.slot(of: bucket) == slot)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -146,30 +146,30 @@ extension _Node {
|
||||
assert(!$0.itemMap.contains(bucket))
|
||||
assert(!$0.childMap.contains(bucket))
|
||||
|
||||
let offset = $0.childMap.offset(of: bucket)
|
||||
$0._insertChild(child, at: offset)
|
||||
let slot = $0.childMap.slot(of: bucket)
|
||||
$0._insertChild(child, at: slot)
|
||||
$0.childMap.insert(bucket)
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove and return the item at `offset`, increasing the amount of free
|
||||
/// Remove and return the item at `slot`, increasing the amount of free
|
||||
/// space available in the node.
|
||||
@inlinable
|
||||
internal mutating func removeItem(
|
||||
at offset: Int, _ bucket: _Bucket
|
||||
at slot: _Slot, _ bucket: _Bucket
|
||||
) -> Element {
|
||||
defer { _invariantCheck() }
|
||||
assert(count > 0)
|
||||
count &-= 1
|
||||
return update {
|
||||
let old = $0._removeItem(at: offset)
|
||||
let old = $0._removeItem(at: slot)
|
||||
if $0.isCollisionNode {
|
||||
assert(bucket.isInvalid)
|
||||
assert(offset >= 0 && offset < $0.collisionCount)
|
||||
assert(slot.value < $0.collisionCount)
|
||||
$0.collisionCount &-= 1
|
||||
} else {
|
||||
assert($0.itemMap.contains(bucket))
|
||||
assert($0.itemMap.offset(of: bucket) == offset)
|
||||
assert($0.itemMap.slot(of: bucket) == slot)
|
||||
$0.itemMap.remove(bucket)
|
||||
}
|
||||
return old
|
||||
@@ -178,14 +178,14 @@ extension _Node {
|
||||
|
||||
@inlinable
|
||||
internal mutating func removeChild(
|
||||
at offset: Int, _ bucket: _Bucket
|
||||
at slot: _Slot, _ bucket: _Bucket
|
||||
) -> _Node {
|
||||
defer { _invariantCheck() }
|
||||
assert(!isCollisionNode)
|
||||
let child = update {
|
||||
assert($0.childMap.contains(bucket))
|
||||
assert($0.childMap.offset(of: bucket) == offset)
|
||||
let child = $0._removeChild(at: offset)
|
||||
assert($0.childMap.slot(of: bucket) == slot)
|
||||
let child = $0._removeChild(at: slot)
|
||||
$0.childMap.remove(bucket)
|
||||
return child
|
||||
}
|
||||
@@ -201,7 +201,7 @@ extension _Node {
|
||||
count = 0
|
||||
return update {
|
||||
assert($0.itemCount == 1 && $0.childCount == 0)
|
||||
let old = $0._removeItem(at: 0)
|
||||
let old = $0._removeItem(at: .zero)
|
||||
$0.itemMap = .empty
|
||||
$0.childMap = .empty
|
||||
return old
|
||||
@@ -213,7 +213,7 @@ extension _Node {
|
||||
defer { _invariantCheck() }
|
||||
let child = update {
|
||||
assert($0.itemCount == 0 && $0.childCount == 1)
|
||||
let child = $0._removeChild(at: 0)
|
||||
let child = $0._removeChild(at: .zero)
|
||||
$0.childMap = .empty
|
||||
return child
|
||||
}
|
||||
@@ -237,29 +237,29 @@ extension _Node {
|
||||
let isUnique = self.isUnique()
|
||||
let r = find(level, key, hash, forInsert: true)
|
||||
switch r {
|
||||
case .found(_, let offset):
|
||||
case .found(_, let slot):
|
||||
ensureUnique(isUnique: isUnique)
|
||||
_invariantCheck() // FIXME
|
||||
return update {
|
||||
let p = $0.itemPtr(at: offset)
|
||||
let p = $0.itemPtr(at: slot)
|
||||
let old = p.pointee.value
|
||||
p.pointee.value = value
|
||||
return old
|
||||
}
|
||||
case .notFound(let bucket, let offset):
|
||||
case .notFound(let bucket, let slot):
|
||||
ensureUnique(isUnique: isUnique, withFreeSpace: Self.spaceForNewItem)
|
||||
insertItem((key, value), at: offset, bucket)
|
||||
insertItem((key, value), at: slot, bucket)
|
||||
return nil
|
||||
case .newCollision(let bucket, let offset):
|
||||
let existingHash = read { _Hash($0[item: offset].key) }
|
||||
case .newCollision(let bucket, let slot):
|
||||
let existingHash = read { _Hash($0[item: slot].key) }
|
||||
if hash == existingHash, hasSingletonItem {
|
||||
// Convert current node to a collision node.
|
||||
ensureUnique(isUnique: isUnique, withFreeSpace: Self.spaceForNewItem)
|
||||
update { $0.collisionCount = 1 }
|
||||
insertItem((key, value), at: 1, .invalid)
|
||||
insertItem((key, value), at: _Slot(1), .invalid)
|
||||
} else {
|
||||
ensureUnique(isUnique: isUnique, withFreeSpace: Self.spaceForNewCollision)
|
||||
let existing = removeItem(at: offset, bucket)
|
||||
let existing = removeItem(at: slot, bucket)
|
||||
let node = _Node(
|
||||
level: level.descend(),
|
||||
item1: existing, existingHash,
|
||||
@@ -273,10 +273,10 @@ extension _Node {
|
||||
item1: (key, value), hash,
|
||||
child2: self, collisionHash)
|
||||
return nil
|
||||
case .descend(_, let offset):
|
||||
case .descend(_, let slot):
|
||||
ensureUnique(isUnique: isUnique)
|
||||
let old = update {
|
||||
$0[child: offset].updateValue(value, forKey: key, level.descend(), hash)
|
||||
$0[child: slot].updateValue(value, forKey: key, level.descend(), hash)
|
||||
}
|
||||
if old == nil { count &+= 1 }
|
||||
return old
|
||||
@@ -302,8 +302,8 @@ extension _Node {
|
||||
}
|
||||
let r = find(level, key, hash, forInsert: false)
|
||||
switch r {
|
||||
case .found(let bucket, let offset):
|
||||
let old = removeItem(at: offset, bucket)
|
||||
case .found(let bucket, let slot):
|
||||
let old = removeItem(at: slot, bucket)
|
||||
if isAtrophied {
|
||||
self = removeSingletonChild()
|
||||
}
|
||||
@@ -313,9 +313,9 @@ extension _Node {
|
||||
return old
|
||||
case .notFound, .newCollision, .expansion:
|
||||
return nil
|
||||
case .descend(let bucket, let offset):
|
||||
case .descend(let bucket, let slot):
|
||||
let (old, needsInlining) = update {
|
||||
let child = $0.childPtr(at: offset)
|
||||
let child = $0.childPtr(at: slot)
|
||||
let old = child.pointee.remove(key, level.descend(), hash)
|
||||
guard old != nil else { return (old, false) }
|
||||
let needsInlining = child.pointee.hasSingletonItem
|
||||
@@ -325,7 +325,7 @@ extension _Node {
|
||||
count &-= 1
|
||||
if needsInlining {
|
||||
ensureUnique(isUnique: true, withFreeSpace: Self.spaceForInlinedChild)
|
||||
var child = self.removeChild(at: offset, bucket)
|
||||
var child = self.removeChild(at: slot, bucket)
|
||||
let item = child.removeSingletonItem()
|
||||
insertItem(item, bucket)
|
||||
}
|
||||
@@ -341,7 +341,7 @@ extension _Node {
|
||||
assert(isCollisionNode && hasSingletonItem)
|
||||
assert(isUnique())
|
||||
update {
|
||||
let hash = _Hash($0[item: 0].key)
|
||||
let hash = _Hash($0[item: .zero].key)
|
||||
$0.itemMap = _Bitmap(hash[.top])
|
||||
$0.childMap = .empty
|
||||
}
|
||||
@@ -353,16 +353,18 @@ extension _Node {
|
||||
) -> (replacement: _Node, old: Element)? {
|
||||
let r = find(level, key, hash, forInsert: false)
|
||||
switch r {
|
||||
case .found(let bucket, let offset):
|
||||
case .found(let bucket, let slot):
|
||||
// Don't copy the node if we'd immediately discard it.
|
||||
let willAtrophy = read {
|
||||
$0.itemCount == 1 && $0.childCount == 1 && $0[child: 0].isCollisionNode
|
||||
$0.itemCount == 1
|
||||
&& $0.childCount == 1
|
||||
&& $0[child: .zero].isCollisionNode
|
||||
}
|
||||
if willAtrophy {
|
||||
return read { ($0[child: 0], $0[item: 0]) }
|
||||
return read { ($0[child: .zero], $0[item: .zero]) }
|
||||
}
|
||||
var node = self.copy()
|
||||
let old = node.removeItem(at: offset, bucket)
|
||||
let old = node.removeItem(at: slot, bucket)
|
||||
if level.isAtRoot, node.isCollisionNode, node.hasSingletonItem {
|
||||
node._convertToRegularNode()
|
||||
}
|
||||
@@ -370,12 +372,12 @@ extension _Node {
|
||||
return (node, old)
|
||||
case .notFound, .newCollision, .expansion:
|
||||
return nil
|
||||
case .descend(let bucket, let offset):
|
||||
let r = read { $0[child: offset].removing(key, level.descend(), hash) }
|
||||
case .descend(let bucket, let slot):
|
||||
let r = read { $0[child: slot].removing(key, level.descend(), hash) }
|
||||
guard var r = r else { return nil }
|
||||
if r.replacement.hasSingletonItem {
|
||||
var node = copy(withFreeSpace: Self.spaceForInlinedChild)
|
||||
_ = node.removeChild(at: offset, bucket)
|
||||
_ = node.removeChild(at: slot, bucket)
|
||||
let item = r.replacement.removeSingletonItem()
|
||||
node.insertItem(item, bucket)
|
||||
node._invariantCheck()
|
||||
@@ -386,7 +388,7 @@ extension _Node {
|
||||
return (r.replacement, r.old)
|
||||
}
|
||||
var node = copy()
|
||||
node.update { $0[child: offset] = r.replacement }
|
||||
node.update { $0[child: slot] = r.replacement }
|
||||
node.count &-= 1
|
||||
node._invariantCheck()
|
||||
return (node, r.old)
|
||||
|
||||
@@ -195,7 +195,9 @@ extension _Node {
|
||||
assert(target.bytesFree >= space)
|
||||
}
|
||||
}
|
||||
self.count = 0
|
||||
self._invariantCheck()
|
||||
new._invariantCheck()
|
||||
self = new
|
||||
}
|
||||
}
|
||||
|
||||
@@ -149,21 +149,26 @@ extension _Node.UnsafeHandle {
|
||||
_header.pointee.childCount
|
||||
}
|
||||
|
||||
@inlinable @inline(__always)
|
||||
internal var childEnd: _Slot {
|
||||
_header.pointee.childEnd
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var _children: UnsafeMutableBufferPointer<_Node> {
|
||||
UnsafeMutableBufferPointer(start: _childrenStart, count: childCount)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func childPtr(at offset: Int) -> UnsafeMutablePointer<_Node> {
|
||||
assert(offset >= 0 && offset < childCount)
|
||||
return _childrenStart + offset
|
||||
internal func childPtr(at slot: _Slot) -> UnsafeMutablePointer<_Node> {
|
||||
assert(slot.value < childCount)
|
||||
return _childrenStart + slot.value
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal subscript(child offset: Int) -> _Node {
|
||||
unsafeAddress { UnsafePointer(childPtr(at: offset)) }
|
||||
nonmutating unsafeMutableAddress { childPtr(at: offset) }
|
||||
internal subscript(child slot: _Slot) -> _Node {
|
||||
unsafeAddress { UnsafePointer(childPtr(at: slot)) }
|
||||
nonmutating unsafeMutableAddress { childPtr(at: slot) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@@ -182,6 +187,11 @@ extension _Node.UnsafeHandle {
|
||||
_header.pointee.itemCount
|
||||
}
|
||||
|
||||
@inlinable @inline(__always)
|
||||
internal var itemEnd: _Slot {
|
||||
_header.pointee.itemEnd
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var reverseItems: UnsafeMutableBufferPointer<Element> {
|
||||
let c = itemCount
|
||||
@@ -189,15 +199,15 @@ extension _Node.UnsafeHandle {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func itemPtr(at offset: Int) -> UnsafeMutablePointer<Element> {
|
||||
assert(offset >= 0 && offset < itemCount)
|
||||
return _itemsEnd.advanced(by: -1 &- offset)
|
||||
internal func itemPtr(at slot: _Slot) -> UnsafeMutablePointer<Element> {
|
||||
assert(slot.value < itemCount)
|
||||
return _itemsEnd.advanced(by: -1 &- slot.value)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal subscript(item offset: Int) -> Element {
|
||||
unsafeAddress { UnsafePointer(itemPtr(at: offset)) }
|
||||
unsafeMutableAddress { itemPtr(at: offset) }
|
||||
internal subscript(item slot: _Slot) -> Element {
|
||||
unsafeAddress { UnsafePointer(itemPtr(at: slot)) }
|
||||
unsafeMutableAddress { itemPtr(at: slot) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +224,6 @@ extension _Node.UnsafeHandle {
|
||||
|
||||
@inlinable
|
||||
internal var isAtrophiedNode: Bool {
|
||||
hasSingletonChild && self[child: 0].isCollisionNode
|
||||
hasSingletonChild && self[child: .zero].isCollisionNode
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,8 @@
|
||||
/// └───┴───┴───┴───┴───┴──────────────────┴───┴───┴───┴───┘
|
||||
/// children items
|
||||
///
|
||||
/// Note that the region for items grows downwards from the end.
|
||||
/// 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
|
||||
|
||||
@@ -46,6 +46,11 @@ extension _RawNode.UnsafeHandle {
|
||||
_header.pointee.childCount
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal var childEnd: _Slot {
|
||||
_header.pointee.childEnd
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal var hasItems: Bool {
|
||||
_header.pointee.hasItems
|
||||
@@ -56,16 +61,20 @@ extension _RawNode.UnsafeHandle {
|
||||
_header.pointee.itemCount
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal var itemEnd: _Slot {
|
||||
_header.pointee.itemEnd
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
internal var _childrenStart: UnsafePointer<_RawNode> {
|
||||
_memory.assumingMemoryBound(to: _RawNode.self)
|
||||
}
|
||||
|
||||
internal subscript(child offset: Int) -> _RawNode {
|
||||
internal subscript(child slot: _Slot) -> _RawNode {
|
||||
unsafeAddress {
|
||||
assert(offset >= 0 && offset < childCount)
|
||||
return _childrenStart + offset
|
||||
assert(slot < childEnd)
|
||||
return _childrenStart + slot.value
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,16 +52,16 @@ extension _RawNode {
|
||||
var l = _Level.top
|
||||
var n = self.unmanaged
|
||||
while l < path.level {
|
||||
let offset = path.ancestors[l]
|
||||
precondition(offset < n.childCount)
|
||||
n = n.unmanagedChild(at: offset)
|
||||
let slot = path.ancestors[l]
|
||||
precondition(slot < n.childEnd)
|
||||
n = n.unmanagedChild(at: slot)
|
||||
l = l.descend()
|
||||
}
|
||||
precondition(n == path.node)
|
||||
if path._isItem {
|
||||
precondition(path._nodeOffset < n.itemCount)
|
||||
precondition(path.nodeSlot < n.itemEnd)
|
||||
} else {
|
||||
precondition(path._nodeOffset <= n.childCount)
|
||||
precondition(path.nodeSlot <= n.childEnd)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 _Slot {
|
||||
@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 _Slot {
|
||||
@inlinable @inline(__always)
|
||||
internal static var zero: _Slot { _Slot(0) }
|
||||
}
|
||||
|
||||
extension _Slot {
|
||||
@inlinable @inline(__always)
|
||||
internal var value: Int {
|
||||
Int(truncatingIfNeeded: _value)
|
||||
}
|
||||
}
|
||||
|
||||
extension _Slot: Equatable {
|
||||
@inlinable @inline(__always)
|
||||
internal static func ==(left: Self, right: Self) -> Bool {
|
||||
left._value == right._value
|
||||
}
|
||||
}
|
||||
|
||||
extension _Slot: Comparable {
|
||||
@inlinable @inline(__always)
|
||||
internal static func <(left: Self, right: Self) -> Bool {
|
||||
left._value < right._value
|
||||
}
|
||||
}
|
||||
|
||||
extension _Slot: Hashable {
|
||||
@inlinable
|
||||
internal func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(_value)
|
||||
}
|
||||
}
|
||||
|
||||
extension _Slot: CustomStringConvertible {
|
||||
@usableFromInline
|
||||
internal var description: String {
|
||||
"\(_value)"
|
||||
}
|
||||
}
|
||||
|
||||
extension _Slot: Strideable {
|
||||
@inlinable @inline(__always)
|
||||
internal func advanced(by n: Int) -> _Slot {
|
||||
return _Slot(_value &+ UInt32(truncatingIfNeeded: n))
|
||||
}
|
||||
|
||||
@inlinable @inline(__always)
|
||||
internal func distance(to other: _Slot) -> Int {
|
||||
if self < other {
|
||||
return Int(truncatingIfNeeded: other._value - self._value)
|
||||
}
|
||||
return -Int(truncatingIfNeeded: self._value - other._value)
|
||||
}
|
||||
}
|
||||
|
||||
extension _Slot {
|
||||
@inlinable @inline(__always)
|
||||
internal func next() -> _Slot {
|
||||
assert(_value < .max)
|
||||
return _Slot(_value &+ 1)
|
||||
}
|
||||
|
||||
@inlinable @inline(__always)
|
||||
internal func previous() -> _Slot {
|
||||
assert(_value > 0)
|
||||
return _Slot(_value &- 1)
|
||||
}
|
||||
}
|
||||
@@ -84,6 +84,16 @@ extension _StorageHeader {
|
||||
: itemMap.count)
|
||||
}
|
||||
|
||||
@inlinable @inline(__always)
|
||||
internal var childEnd: _Slot {
|
||||
_Slot(childCount)
|
||||
}
|
||||
|
||||
@inlinable @inline(__always)
|
||||
internal var itemEnd: _Slot {
|
||||
_Slot(itemCount)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var collisionCount: Int {
|
||||
get {
|
||||
|
||||
@@ -73,11 +73,21 @@ extension _UnmanagedNode {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func unmanagedChild(at offset: Int) -> Self {
|
||||
internal var itemEnd: _Slot {
|
||||
withRaw { _Slot($0.header.itemCount) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var childEnd: _Slot {
|
||||
withRaw { _Slot($0.header.childCount) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func unmanagedChild(at slot: _Slot) -> Self {
|
||||
withRaw { raw in
|
||||
assert(offset >= 0 && offset < raw.header.childCount)
|
||||
assert(slot.value < raw.header.childCount)
|
||||
return raw.withUnsafeMutablePointerToElements { p in
|
||||
Self(p[offset].storage)
|
||||
Self(p[slot.value].storage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,13 +12,13 @@
|
||||
@usableFromInline
|
||||
internal struct _UnsafePath {
|
||||
@usableFromInline
|
||||
internal var ancestors: _AncestorOffsets
|
||||
internal var ancestors: _AncestorSlots
|
||||
|
||||
@usableFromInline
|
||||
internal var node: _UnmanagedNode
|
||||
|
||||
@usableFromInline
|
||||
internal var _nodeOffset: UInt32
|
||||
internal var nodeSlot: _Slot
|
||||
|
||||
@usableFromInline
|
||||
internal var level: _Level
|
||||
@@ -32,7 +32,7 @@ internal struct _UnsafePath {
|
||||
self.level = .top
|
||||
self.ancestors = .empty
|
||||
self.node = root.unmanaged
|
||||
self._nodeOffset = 0
|
||||
self.nodeSlot = .zero
|
||||
self._isItem = root.storage.header.hasItems
|
||||
}
|
||||
}
|
||||
@@ -40,15 +40,15 @@ internal struct _UnsafePath {
|
||||
extension _UnsafePath {
|
||||
internal init(
|
||||
_ level: _Level,
|
||||
_ ancestors: _AncestorOffsets,
|
||||
_ ancestors: _AncestorSlots,
|
||||
_ node: _UnmanagedNode,
|
||||
_ childOffset: Int
|
||||
_ childSlot: _Slot
|
||||
) {
|
||||
assert(childOffset >= 0 && childOffset < node.childCount)
|
||||
assert(childSlot < node.childEnd)
|
||||
self.level = level
|
||||
self.ancestors = ancestors
|
||||
self.node = node
|
||||
self._nodeOffset = UInt32(truncatingIfNeeded: childOffset)
|
||||
self.nodeSlot = childSlot
|
||||
self._isItem = false
|
||||
}
|
||||
}
|
||||
@@ -60,7 +60,7 @@ extension _UnsafePath: Equatable {
|
||||
// Note: we don't compare nodes (node equality should follow from the rest)
|
||||
left.level == right.level
|
||||
&& left.ancestors == right.ancestors
|
||||
&& left._nodeOffset == right._nodeOffset
|
||||
&& left.nodeSlot == right.nodeSlot
|
||||
&& left._isItem == right._isItem
|
||||
}
|
||||
}
|
||||
@@ -71,7 +71,7 @@ extension _UnsafePath: Hashable {
|
||||
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(_nodeOffset)
|
||||
hasher.combine(nodeSlot)
|
||||
hasher.combine(level._shift)
|
||||
hasher.combine(_isItem)
|
||||
}
|
||||
@@ -81,7 +81,7 @@ extension _UnsafePath: Comparable {
|
||||
@usableFromInline
|
||||
@_effects(releasenone)
|
||||
internal static func <(left: Self, right: Self) -> Bool {
|
||||
// This implements a total ordering across paths based on the offset
|
||||
// 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
|
||||
@@ -98,18 +98,18 @@ extension _UnsafePath: Comparable {
|
||||
assert(level < right.level || !right.ancestors.hasDataBelow(level))
|
||||
if level < right.level {
|
||||
guard !left._isItem else { return true }
|
||||
let l = left._nodeOffset
|
||||
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._nodeOffset
|
||||
let r = right.nodeSlot
|
||||
return l < r
|
||||
}
|
||||
guard left._isItem == right._isItem else { return left._isItem }
|
||||
return left._nodeOffset < right._nodeOffset
|
||||
return left.nodeSlot < right.nodeSlot
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,13 +123,13 @@ extension _UnsafePath: CustomStringConvertible {
|
||||
l = l.descend()
|
||||
}
|
||||
if isPlaceholder {
|
||||
d += "[\(self._nodeOffset)]?"
|
||||
d += "[\(self.nodeSlot)]?"
|
||||
} else if isOnItem {
|
||||
d += "[\(self._nodeOffset)]"
|
||||
d += "[\(self.nodeSlot)]"
|
||||
} else if isOnChild {
|
||||
d += ".\(self._nodeOffset)"
|
||||
d += ".\(self.nodeSlot)"
|
||||
} else if isOnNodeEnd {
|
||||
d += ".$(\(self._nodeOffset))"
|
||||
d += ".$(\(self.nodeSlot))"
|
||||
}
|
||||
return d
|
||||
}
|
||||
@@ -145,7 +145,7 @@ extension _UnsafePath {
|
||||
/// trigger undefined behavior.
|
||||
@inlinable @inline(__always)
|
||||
internal var isOnItem: Bool {
|
||||
// Note: this may be true even if nodeOffset == itemCount (insertion paths).
|
||||
// Note: this may be true even if nodeSlot == itemCount (insertion paths).
|
||||
_isItem
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ extension _UnsafePath {
|
||||
/// inserted later; they do not occur while simply iterating over existing
|
||||
/// items.
|
||||
internal var isPlaceholder: Bool {
|
||||
_isItem && _nodeOffset == node.itemCount
|
||||
_isItem && nodeSlot.value == node.itemCount
|
||||
}
|
||||
|
||||
/// Returns true if this path addresses a node in the tree; otherwise returns
|
||||
@@ -165,7 +165,7 @@ extension _UnsafePath {
|
||||
/// never get called when the node is no longer valid; otherwise this will
|
||||
/// trigger undefined behavior.
|
||||
internal var isOnChild: Bool {
|
||||
!_isItem && _nodeOffset < node.childCount
|
||||
!_isItem && nodeSlot.value < node.childCount
|
||||
}
|
||||
|
||||
/// Returns true if this path addresses an empty slot within a node in a tree;
|
||||
@@ -176,29 +176,18 @@ extension _UnsafePath {
|
||||
/// never get called when the node is no longer valid; otherwise this will
|
||||
/// trigger undefined behavior.
|
||||
internal var isOnNodeEnd: Bool {
|
||||
!_isItem && _nodeOffset == node.childCount
|
||||
!_isItem && nodeSlot.value == node.childCount
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var isOnLeftmostItem: Bool {
|
||||
// We are on the leftmost item in the tree if we are currently
|
||||
// addressing an item and the ancestors path is all zero bits.
|
||||
_isItem && ancestors == .empty && _nodeOffset == 0
|
||||
_isItem && ancestors == .empty && nodeSlot == .zero
|
||||
}
|
||||
}
|
||||
|
||||
extension _UnsafePath {
|
||||
@inlinable @inline(__always)
|
||||
internal var nodeOffset: Int {
|
||||
get {
|
||||
Int(truncatingIfNeeded: _nodeOffset)
|
||||
}
|
||||
set {
|
||||
assert(newValue >= 0 && newValue <= UInt32.max)
|
||||
_nodeOffset = UInt32(truncatingIfNeeded: newValue)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns an unmanaged reference to the child node this path is currently
|
||||
/// addressing.
|
||||
///
|
||||
@@ -208,28 +197,28 @@ extension _UnsafePath {
|
||||
/// trigger undefined behavior.
|
||||
internal var currentChild: _UnmanagedNode {
|
||||
assert(isOnChild)
|
||||
return node.unmanagedChild(at: nodeOffset)
|
||||
return node.unmanagedChild(at: nodeSlot)
|
||||
}
|
||||
|
||||
internal func childOffset(at level: _Level) -> Int {
|
||||
internal func childSlot(at level: _Level) -> _Slot {
|
||||
assert(level < self.level)
|
||||
return ancestors[level]
|
||||
}
|
||||
/// Returns the offset to the currently addressed item.
|
||||
/// Returns the slot of the currently addressed item.
|
||||
///
|
||||
/// - Note: This method needs to resolve the unmanaged node reference
|
||||
/// that is stored in the path. It is up to the caller to ensure this will
|
||||
/// never get called when the node is no longer valid; otherwise this will
|
||||
/// trigger undefined behavior.
|
||||
@inlinable @inline(__always)
|
||||
internal var currentItemOffset: Int {
|
||||
internal var currentItemSlot: _Slot {
|
||||
assert(isOnItem)
|
||||
return nodeOffset
|
||||
return nodeSlot
|
||||
}
|
||||
}
|
||||
|
||||
extension _UnsafePath {
|
||||
/// Positions this path on the item with the specified offset within its
|
||||
/// Positions this path on the item with the specified slot within its
|
||||
/// current node.
|
||||
///
|
||||
/// - Note: This method needs to resolve the unmanaged node reference
|
||||
@@ -237,16 +226,16 @@ extension _UnsafePath {
|
||||
/// never get called when the node is no longer valid; otherwise this will
|
||||
/// trigger undefined behavior.
|
||||
@inlinable
|
||||
internal mutating func selectItem(at offset: Int) {
|
||||
// As a special exception, this allows offset to equal the item count.
|
||||
internal mutating func selectItem(at slot: _Slot) {
|
||||
// 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(offset >= 0 && offset <= node.itemCount)
|
||||
nodeOffset = offset
|
||||
assert(slot <= node.itemEnd)
|
||||
nodeSlot = slot
|
||||
_isItem = true
|
||||
}
|
||||
|
||||
/// Positions this path on the child with the specified offset within its
|
||||
/// Positions this path on the child with the specified slot within its
|
||||
/// current node, without descending into it.
|
||||
///
|
||||
/// - Note: This method needs to resolve the unmanaged node reference
|
||||
@@ -254,11 +243,11 @@ extension _UnsafePath {
|
||||
/// never get called when the node is no longer valid; otherwise this will
|
||||
/// trigger undefined behavior.
|
||||
@inlinable
|
||||
internal mutating func selectChild(at offset: Int) {
|
||||
// As a special exception, this allows offset to equal the child count.
|
||||
internal mutating func selectChild(at slot: _Slot) {
|
||||
// As a special exception, this allows slot to equal the child count.
|
||||
// This is equivalent to a call to `selectEnd()`.
|
||||
assert(offset >= 0 && offset <= node.childCount)
|
||||
nodeOffset = offset
|
||||
assert(slot <= node.childEnd)
|
||||
nodeSlot = slot
|
||||
_isItem = false
|
||||
}
|
||||
|
||||
@@ -271,7 +260,7 @@ extension _UnsafePath {
|
||||
@usableFromInline
|
||||
@_effects(releasenone)
|
||||
internal mutating func selectEnd() {
|
||||
nodeOffset = node.childCount
|
||||
nodeSlot = node.childEnd
|
||||
_isItem = false
|
||||
}
|
||||
|
||||
@@ -288,26 +277,26 @@ extension _UnsafePath {
|
||||
@_effects(releasenone)
|
||||
internal mutating func descend() {
|
||||
self.node = currentChild
|
||||
self.ancestors[level] = nodeOffset
|
||||
self.nodeOffset = 0
|
||||
self.ancestors[level] = nodeSlot
|
||||
self.nodeSlot = .zero
|
||||
self._isItem = node.hasItems
|
||||
self.level = level.descend()
|
||||
}
|
||||
|
||||
internal mutating func ascendToNearestAncestor(
|
||||
under root: _RawNode,
|
||||
where test: (_UnmanagedNode, Int) -> Bool
|
||||
where test: (_UnmanagedNode, _Slot) -> Bool
|
||||
) -> Bool {
|
||||
if self.level.isAtRoot { return false }
|
||||
var best: _UnsafePath? = nil
|
||||
var n = root.unmanaged
|
||||
var l: _Level = .top
|
||||
while l < self.level {
|
||||
let offset = self.ancestors[l]
|
||||
if test(n, offset) {
|
||||
best = _UnsafePath(l, self.ancestors.truncating(to: l), n, offset)
|
||||
let slot = self.ancestors[l]
|
||||
if test(n, slot) {
|
||||
best = _UnsafePath(l, self.ancestors.truncating(to: l), n, slot)
|
||||
}
|
||||
n = n.unmanagedChild(at: offset)
|
||||
n = n.unmanagedChild(at: slot)
|
||||
l = l.descend()
|
||||
}
|
||||
guard let best = best else { return false }
|
||||
@@ -325,7 +314,7 @@ extension _UnsafePath {
|
||||
}
|
||||
assert(l.descend() == self.level)
|
||||
self._isItem = false
|
||||
self.nodeOffset = self.ancestors[l]
|
||||
self.nodeSlot = self.ancestors[l]
|
||||
let oldNode = self.node
|
||||
self.node = n
|
||||
self.ancestors.clear(l)
|
||||
@@ -337,19 +326,19 @@ extension _UnsafePath {
|
||||
extension _UnsafePath {
|
||||
mutating func selectNextItem() -> Bool {
|
||||
assert(isOnItem)
|
||||
_nodeOffset &+= 1
|
||||
if _nodeOffset < node.itemCount { return true }
|
||||
_nodeOffset = 0
|
||||
nodeSlot = nodeSlot.next()
|
||||
if nodeSlot < node.itemEnd { return true }
|
||||
nodeSlot = .zero
|
||||
_isItem = false
|
||||
return false
|
||||
}
|
||||
|
||||
mutating func selectNextChild() -> Bool {
|
||||
assert(!isOnItem)
|
||||
let childCount = node.childCount
|
||||
guard _nodeOffset < childCount else { return false }
|
||||
_nodeOffset &+= 1
|
||||
return _nodeOffset < childCount
|
||||
let childEnd = node.childEnd
|
||||
guard nodeSlot < childEnd else { return false }
|
||||
nodeSlot = nodeSlot.next()
|
||||
return nodeSlot < childEnd
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,13 +355,13 @@ extension _UnsafePath {
|
||||
assert(isOnChild)
|
||||
while true {
|
||||
descend()
|
||||
let childCount = node.childCount
|
||||
guard childCount > 0 else { break }
|
||||
selectChild(at: childCount - 1)
|
||||
let childEnd = node.childEnd
|
||||
guard childEnd > .zero else { break }
|
||||
selectChild(at: childEnd.previous())
|
||||
}
|
||||
let itemCount = node.itemCount
|
||||
assert(itemCount > 0)
|
||||
selectItem(at: itemCount - 1)
|
||||
let itemEnd = node.itemEnd
|
||||
assert(itemEnd > .zero)
|
||||
selectItem(at: itemEnd.previous())
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@@ -386,7 +375,7 @@ extension _UnsafePath {
|
||||
return true
|
||||
}
|
||||
if ascendToNearestAncestor(
|
||||
under: root, where: { $1 &+ 1 < $0.childCount }
|
||||
under: root, where: { $1.next() < $0.childEnd }
|
||||
) {
|
||||
let r = selectNextChild()
|
||||
assert(r)
|
||||
@@ -402,33 +391,35 @@ extension _UnsafePath {
|
||||
@usableFromInline
|
||||
@_effects(releasenone)
|
||||
internal mutating func findPredecessorItem(under root: _RawNode) -> Bool {
|
||||
switch (isOnItem, nodeOffset > 0) {
|
||||
switch (isOnItem, nodeSlot > .zero) {
|
||||
case (true, true):
|
||||
selectItem(at: nodeOffset &- 1)
|
||||
selectItem(at: nodeSlot.previous())
|
||||
return true
|
||||
case (false, true):
|
||||
selectChild(at: nodeOffset &- 1)
|
||||
selectChild(at: nodeSlot.previous())
|
||||
descendToRightMostItem()
|
||||
return true
|
||||
case (false, false):
|
||||
if node.hasItems {
|
||||
selectItem(at: node.itemCount &- 1)
|
||||
selectItem(at: node.itemEnd.previous())
|
||||
return true
|
||||
}
|
||||
case (true, false):
|
||||
break
|
||||
}
|
||||
guard
|
||||
ascendToNearestAncestor(under: root, where: { $0.hasItems || $1 > 0 })
|
||||
ascendToNearestAncestor(
|
||||
under: root,
|
||||
where: { $0.hasItems || $1 > .zero })
|
||||
else { return false }
|
||||
|
||||
if nodeOffset > 0 {
|
||||
selectChild(at: nodeOffset &- 1)
|
||||
if nodeSlot > .zero {
|
||||
selectChild(at: nodeSlot.previous())
|
||||
descendToRightMostItem()
|
||||
return true
|
||||
}
|
||||
if node.hasItems {
|
||||
selectItem(at: node.itemCount &- 1)
|
||||
selectItem(at: node.itemEnd.previous())
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -436,21 +427,23 @@ extension _UnsafePath {
|
||||
}
|
||||
|
||||
extension _RawNode {
|
||||
internal func preorderPosition(_ level: _Level, of path: _UnsafePath) -> Int {
|
||||
internal func preorderPosition(
|
||||
_ level: _Level, of path: _UnsafePath
|
||||
) -> Int {
|
||||
if path.isOnNodeEnd { return count }
|
||||
assert(path.isOnItem)
|
||||
if level < path.level {
|
||||
let childOffset = path.childOffset(at: level)
|
||||
let childSlot = path.childSlot(at: level)
|
||||
return read {
|
||||
let prefix = $0._children[..<childOffset]
|
||||
let prefix = $0._children[..<childSlot.value]
|
||||
.reduce($0.itemCount) { $0 + $1.count }
|
||||
let positionWithinChild = $0[child: childOffset]
|
||||
let positionWithinChild = $0[child: childSlot]
|
||||
.preorderPosition(level.descend(), of: path)
|
||||
return prefix + positionWithinChild
|
||||
}
|
||||
}
|
||||
assert(path.level == level)
|
||||
return path.nodeOffset
|
||||
return path.nodeSlot.value
|
||||
}
|
||||
|
||||
@usableFromInline
|
||||
@@ -472,7 +465,7 @@ extension _RawNode {
|
||||
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 end.currentItemOffset - start.currentItemOffset
|
||||
return start.currentItemSlot.distance(to: end.currentItemSlot)
|
||||
}
|
||||
if
|
||||
start.level < end.level,
|
||||
@@ -480,12 +473,12 @@ extension _RawNode {
|
||||
{
|
||||
// Shortcut: start's node is an ancestor of end's position.
|
||||
return start.node._distance(
|
||||
start.level, fromItemAtOffset: start.currentItemOffset, to: end)
|
||||
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, fromItemAtOffset: end.currentItemOffset, to: start)
|
||||
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
|
||||
@@ -502,35 +495,38 @@ extension _RawNode {
|
||||
assert(start < end)
|
||||
assert(level < start.level)
|
||||
assert(level < end.level)
|
||||
let offset1 = start.childOffset(at: level)
|
||||
let offset2 = end.childOffset(at: level)
|
||||
if offset1 == offset2 {
|
||||
let slot1 = start.childSlot(at: level)
|
||||
let slot2 = end.childSlot(at: level)
|
||||
if slot1 == slot2 {
|
||||
return read {
|
||||
$0[child: offset1]._distance(level.descend(), from: start, to: end)
|
||||
$0[child: slot1]._distance(level.descend(), from: start, to: end)
|
||||
}
|
||||
}
|
||||
return read {
|
||||
let children = $0._children
|
||||
let d1 = children[offset1].preorderPosition(level.descend(), of: start)
|
||||
let d2 = children[offset1 &+ 1 ..< offset2].reduce(0) { $0 + $1.count }
|
||||
let d3 = children[offset2].preorderPosition(level.descend(), of: end)
|
||||
return (children[offset1].count - d1) + d2 + d3
|
||||
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 _UnmanagedNode {
|
||||
internal func _distance(
|
||||
_ level: _Level, fromItemAtOffset start: Int, to end: _UnsafePath
|
||||
_ level: _Level, fromItemAt start: _Slot, to end: _UnsafePath
|
||||
) -> Int {
|
||||
read {
|
||||
assert(start >= 0 && start < $0.itemCount)
|
||||
assert(start < $0.itemEnd)
|
||||
assert(level < end.level)
|
||||
let childOffset = end.childOffset(at: level)
|
||||
let childSlot = end.childSlot(at: level)
|
||||
let children = $0._children
|
||||
let prefix = children[..<childOffset]
|
||||
.reduce($0.itemCount - start) { $0 + $1.count }
|
||||
let positionWithinChild = children[childOffset]
|
||||
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
|
||||
}
|
||||
@@ -548,16 +544,16 @@ extension _Node {
|
||||
$0.find(path.level, key, hash, forInsert: false)
|
||||
}
|
||||
switch r {
|
||||
case .found(_, let offset):
|
||||
path.selectItem(at: offset)
|
||||
case .found(_, let slot):
|
||||
path.selectItem(at: slot)
|
||||
return (true, path)
|
||||
case .notFound(_, let offset), .newCollision(_, let offset):
|
||||
path.selectItem(at: offset)
|
||||
case .notFound(_, let slot), .newCollision(_, let slot):
|
||||
path.selectItem(at: slot)
|
||||
return (false, path)
|
||||
case .expansion:
|
||||
return (false, path)
|
||||
case .descend(_, let offset):
|
||||
path.selectChild(at: offset)
|
||||
case .descend(_, let slot):
|
||||
path.selectChild(at: slot)
|
||||
path.descend()
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -100,7 +100,7 @@ extension PersistentDictionary: BidirectionalCollection {
|
||||
precondition(_isValid(i), "Invalid index")
|
||||
precondition(i._path.isOnItem, "Can't get element at endIndex")
|
||||
return _Node.UnsafeHandle.read(i._path.node) {
|
||||
$0[item: i._path.currentItemOffset]
|
||||
$0[item: i._path.currentItemSlot]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user