mirror of
https://github.com/apple/swift-collections
synced 2026-11-27 04:54:21 +00:00
Merge pull request #188 from lorentey/PersistentCollections-updates
Persistent collections updates (part 9)
This commit is contained in:
54 files changed
+3545
-980
No files matched your search
@@ -11,8 +11,6 @@
|
||||
|
||||
import _CollectionsUtilities
|
||||
|
||||
extension BitSet: _FastMembershipCheckable {}
|
||||
|
||||
extension BitSet {
|
||||
/// Creates a new empty bit set with enough storage capacity to store values
|
||||
/// up to the given maximum value without reallocating storage.
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 OrderedSet: _FastMembershipCheckable {}
|
||||
@@ -9,6 +9,8 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
import _CollectionsUtilities
|
||||
|
||||
/// A set of `_Bucket` values, represented by a 32-bit wide bitset.
|
||||
@usableFromInline
|
||||
@frozen
|
||||
@@ -112,12 +114,24 @@ extension _Bitmap {
|
||||
_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) -> _Slot {
|
||||
_Slot(_value._rank(ofBit: bucket.value))
|
||||
|
||||
@@ -13,126 +13,215 @@ extension _Node {
|
||||
@usableFromInline
|
||||
@frozen
|
||||
internal enum Builder {
|
||||
@usableFromInline typealias Element = _Node.Element
|
||||
|
||||
case empty
|
||||
case item(Element, _Hash)
|
||||
case node(_Node, _Hash)
|
||||
|
||||
@inlinable
|
||||
internal init(_ level: _Level, _ node: _Node, _ hashPrefix: _Hash) {
|
||||
if node.count == 0 {
|
||||
self = .empty
|
||||
} else if node.hasSingletonItem {
|
||||
let item = node.read { $0[item: .zero] }
|
||||
self = .item(item, hashPrefix)
|
||||
} else {
|
||||
self = .node(node, hashPrefix)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func finalize(_ level: _Level) -> _Node {
|
||||
assert(level.isAtRoot)
|
||||
switch self {
|
||||
case .empty:
|
||||
return _Node(storage: _emptySingleton, count: 0)
|
||||
case .item(let item, let h):
|
||||
return _Node._regularNode(item, h[level])
|
||||
case .node(let node, _):
|
||||
return node
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func addNewCollision(_ newItem: Element, _ hash: _Hash) {
|
||||
switch self {
|
||||
case .empty:
|
||||
self = .item(newItem, hash)
|
||||
case .item(let oldItem, let h):
|
||||
assert(hash == h)
|
||||
let node = _Node._collisionNode(hash, oldItem, newItem)
|
||||
self = .node(node, hash)
|
||||
case .node(var node, let h):
|
||||
self = .empty
|
||||
assert(node.isCollisionNode)
|
||||
assert(hash == h)
|
||||
assert(hash == node.collisionHash)
|
||||
node.ensureUniqueAndAppendCollision(isUnique: true, newItem)
|
||||
self = .node(node, h)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func addNewItem(
|
||||
_ level: _Level, _ newItem: Element, _ hashPrefix: _Hash
|
||||
) {
|
||||
switch self {
|
||||
case .empty:
|
||||
self = .item(newItem, hashPrefix)
|
||||
case .item(let oldItem, let oldHash):
|
||||
let bucket1 = oldHash[level]
|
||||
let bucket2 = hashPrefix[level]
|
||||
assert(bucket1 != bucket2)
|
||||
assert(oldHash.isEqual(to: hashPrefix, upTo: level))
|
||||
let node = _Node._regularNode(oldItem, bucket1, newItem, bucket2)
|
||||
self = .node(node, hashPrefix)
|
||||
case .node(var node, let nodeHash):
|
||||
self = .empty
|
||||
assert(!node.isCollisionNode)
|
||||
assert(nodeHash.isEqual(to: hashPrefix, upTo: level))
|
||||
let bucket = hashPrefix[level]
|
||||
node.ensureUniqueAndInsertItem(isUnique: true, newItem, bucket)
|
||||
self = .node(node, nodeHash)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func addNewChildBranch(
|
||||
_ level: _Level, _ branch: Builder
|
||||
) {
|
||||
switch (self, branch) {
|
||||
case (_, .empty):
|
||||
break
|
||||
case (.empty, .item):
|
||||
self = branch
|
||||
case (.empty, .node(let child, let childHash)):
|
||||
if child.isCollisionNode {
|
||||
// Compression
|
||||
assert(!level.isAtBottom)
|
||||
self = branch
|
||||
} else {
|
||||
let node = _Node._regularNode(child, childHash[level])
|
||||
self = .node(node, childHash)
|
||||
}
|
||||
case let (.item(li, lh), .item(ri, rh)):
|
||||
let node = _Node._regularNode(li, lh[level], ri, rh[level])
|
||||
self = .node(node, lh)
|
||||
case let (.item(item, itemHash), .node(child, childHash)):
|
||||
assert(itemHash.isEqual(to: childHash, upTo: level))
|
||||
let node = _Node._regularNode(
|
||||
item, itemHash[level],
|
||||
child, childHash[level])
|
||||
self = .node(node, childHash)
|
||||
case (.node(var node, let nodeHash), .item(let item, let itemHash)):
|
||||
if node.isCollisionNode {
|
||||
// Expansion
|
||||
assert(!level.isAtBottom)
|
||||
node = _Node._regularNode(node, nodeHash[level])
|
||||
}
|
||||
assert(!node.isCollisionNode)
|
||||
assert(nodeHash.isEqual(to: itemHash, upTo: level))
|
||||
node.ensureUniqueAndInsertItem(isUnique: true, item, itemHash[level])
|
||||
self = .node(node, nodeHash)
|
||||
case (.node(var node, let nodeHash), .node(let child, let childHash)):
|
||||
if node.isCollisionNode {
|
||||
// Expansion
|
||||
assert(!level.isAtBottom)
|
||||
node = _Node._regularNode(node, nodeHash[level])
|
||||
}
|
||||
assert(nodeHash.isEqual(to: childHash, upTo: level))
|
||||
node.ensureUnique(isUnique: true, withFreeSpace: _Node.spaceForNewChild)
|
||||
node.insertChild(child, childHash[level])
|
||||
self = .node(node, nodeHash)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension _Node.Builder {
|
||||
@inlinable
|
||||
internal var count: Int {
|
||||
switch self {
|
||||
case .empty:
|
||||
return 0
|
||||
case .item:
|
||||
return 1
|
||||
case .node(let node, _):
|
||||
return node.count
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal var isEmpty: Bool {
|
||||
guard case .empty = self else { return false }
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
extension _Node.Builder {
|
||||
@inlinable
|
||||
internal init(_ level: _Level, _ node: _Node, _ hashPrefix: _Hash) {
|
||||
if node.count == 0 {
|
||||
self = .empty
|
||||
} else if node.hasSingletonItem {
|
||||
let item = node.read { $0[item: .zero] }
|
||||
self = .item(item, hashPrefix)
|
||||
} else {
|
||||
self = .node(node, hashPrefix)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func finalize(_ level: _Level) -> _Node {
|
||||
assert(level.isAtRoot)
|
||||
switch self {
|
||||
case .empty:
|
||||
return _Node(storage: _emptySingleton, count: 0)
|
||||
case .item(let item, let h):
|
||||
return _Node._regularNode(item, h[level])
|
||||
case .node(let node, _):
|
||||
return node
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func addNewCollision(_ newItem: Element, _ hash: _Hash) {
|
||||
switch self {
|
||||
case .empty:
|
||||
self = .item(newItem, hash)
|
||||
case .item(let oldItem, let h):
|
||||
assert(hash == h)
|
||||
let node = _Node._collisionNode(hash, oldItem, newItem)
|
||||
self = .node(node, hash)
|
||||
case .node(var node, let h):
|
||||
self = .empty
|
||||
assert(node.isCollisionNode)
|
||||
assert(hash == h)
|
||||
assert(hash == node.collisionHash)
|
||||
_ = node.ensureUniqueAndAppendCollision(isUnique: true, newItem)
|
||||
self = .node(node, h)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func addNewItem(
|
||||
_ level: _Level, _ newItem: Element, _ hashPrefix: _Hash
|
||||
) {
|
||||
switch self {
|
||||
case .empty:
|
||||
self = .item(newItem, hashPrefix)
|
||||
case .item(let oldItem, let oldHash):
|
||||
let bucket1 = oldHash[level]
|
||||
let bucket2 = hashPrefix[level]
|
||||
assert(bucket1 != bucket2)
|
||||
assert(oldHash.isEqual(to: hashPrefix, upTo: level))
|
||||
let node = _Node._regularNode(oldItem, bucket1, newItem, bucket2)
|
||||
self = .node(node, hashPrefix)
|
||||
case .node(var node, let nodeHash):
|
||||
self = .empty
|
||||
if node.isCollisionNode {
|
||||
// Expansion
|
||||
assert(!level.isAtBottom)
|
||||
node = _Node._regularNode(node, nodeHash[level])
|
||||
}
|
||||
assert(nodeHash.isEqual(to: hashPrefix, upTo: level))
|
||||
let bucket = hashPrefix[level]
|
||||
node.ensureUniqueAndInsertItem(isUnique: true, newItem, at: bucket)
|
||||
self = .node(node, nodeHash)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func addNewChildBranch(
|
||||
_ level: _Level, _ branch: Self
|
||||
) {
|
||||
switch (self, branch) {
|
||||
case (_, .empty):
|
||||
break
|
||||
case (.empty, .item):
|
||||
self = branch
|
||||
case (.empty, .node(let child, let childHash)):
|
||||
if child.isCollisionNode {
|
||||
// Compression
|
||||
assert(!level.isAtBottom)
|
||||
self = branch
|
||||
} else {
|
||||
let node = _Node._regularNode(child, childHash[level])
|
||||
self = .node(node, childHash)
|
||||
}
|
||||
case let (.item(li, lh), .item(ri, rh)):
|
||||
let node = _Node._regularNode(li, lh[level], ri, rh[level])
|
||||
self = .node(node, lh)
|
||||
case let (.item(item, itemHash), .node(child, childHash)):
|
||||
assert(itemHash.isEqual(to: childHash, upTo: level))
|
||||
let node = _Node._regularNode(
|
||||
item, itemHash[level],
|
||||
child, childHash[level])
|
||||
self = .node(node, childHash)
|
||||
case (.node(var node, let nodeHash), .item(let item, let itemHash)):
|
||||
if node.isCollisionNode {
|
||||
// Expansion
|
||||
assert(!level.isAtBottom)
|
||||
node = _Node._regularNode(node, nodeHash[level])
|
||||
}
|
||||
assert(!node.isCollisionNode)
|
||||
assert(nodeHash.isEqual(to: itemHash, upTo: level))
|
||||
node.ensureUniqueAndInsertItem(
|
||||
isUnique: true, item, at: itemHash[level])
|
||||
self = .node(node, nodeHash)
|
||||
case (.node(var node, let nodeHash), .node(let child, let childHash)):
|
||||
if node.isCollisionNode {
|
||||
// Expansion
|
||||
assert(!level.isAtBottom)
|
||||
node = _Node._regularNode(node, nodeHash[level])
|
||||
}
|
||||
assert(nodeHash.isEqual(to: childHash, upTo: level))
|
||||
node.ensureUnique(isUnique: true, withFreeSpace: _Node.spaceForNewChild)
|
||||
node.insertChild(child, childHash[level])
|
||||
self = .node(node, nodeHash)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func childBranch(
|
||||
_ level: _Level, _ branch: Self
|
||||
) -> Self {
|
||||
var result: Self = .empty
|
||||
result.addNewChildBranch(level, branch)
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
extension _Node.Builder {
|
||||
@inlinable
|
||||
internal mutating func copyCollisions(
|
||||
from source: _Node.UnsafeHandle,
|
||||
upTo end: _Slot
|
||||
) {
|
||||
assert(isEmpty)
|
||||
assert(source.isCollisionNode)
|
||||
assert(end < source.itemsEndSlot)
|
||||
let h = source.collisionHash
|
||||
for slot: _Slot in stride(from: .zero, to: end, by: 1) {
|
||||
self.addNewCollision(source[item: slot], h)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func copyItems(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
from source: _Node.UnsafeHandle,
|
||||
upTo end: _Bucket
|
||||
) {
|
||||
assert(isEmpty)
|
||||
assert(!source.isCollisionNode)
|
||||
for (b, s) in source.itemMap.intersection(_Bitmap(upTo: end)) {
|
||||
let h = hashPrefix.appending(b, at: level)
|
||||
self.addNewItem(level, source[item: s], h)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func copyItemsAndChildren(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
from source: _Node.UnsafeHandle,
|
||||
upTo end: _Bucket
|
||||
) {
|
||||
assert(isEmpty)
|
||||
assert(!source.isCollisionNode)
|
||||
for (b, s) in source.itemMap {
|
||||
let h = hashPrefix.appending(b, at: level)
|
||||
self.addNewItem(level, source[item: s], h)
|
||||
}
|
||||
for (b, s) in source.childMap.intersection(_Bitmap(upTo: end)) {
|
||||
let h = hashPrefix.appending(b, at: level)
|
||||
self.addNewChildBranch(level, .node(source[child: s], h))
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -139,6 +139,27 @@ extension _Node {
|
||||
r.node._invariantCheck()
|
||||
return r.node
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func _regularNode(
|
||||
_ child1: __owned _Node,
|
||||
_ child1Bucket: _Bucket,
|
||||
_ child2: __owned _Node,
|
||||
_ child2Bucket: _Bucket
|
||||
) -> _Node {
|
||||
assert(child1Bucket != child2Bucket)
|
||||
let r = _Node.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 _Node {
|
||||
@@ -150,6 +171,7 @@ extension _Node {
|
||||
item2 inserter2: (UnsafeMutablePointer<Element>) -> Void,
|
||||
_ hash2: _Hash
|
||||
) -> (top: _Node, leaf: _UnmanagedNode, slot1: _Slot, slot2: _Slot) {
|
||||
assert(hash1.isEqual(to: hash2, upTo: level.ascend()))
|
||||
if hash1 == hash2 {
|
||||
let top = _collisionNode(hash1, item1, inserter2)
|
||||
return (top, top.unmanaged, _Slot(0), _Slot(1))
|
||||
@@ -203,4 +225,27 @@ extension _Node {
|
||||
let node = _regularNode(inserter1, hash1[level], child2, hash2[level])
|
||||
return (node, node.unmanaged, .zero, .zero)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal static func build(
|
||||
level: _Level,
|
||||
child1: __owned _Node,
|
||||
_ hash1: _Hash,
|
||||
child2: __owned _Node,
|
||||
_ hash2: _Hash
|
||||
) -> _Node {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -80,7 +80,7 @@ extension _Node.UnsafeHandle {
|
||||
extension _Node {
|
||||
@inlinable @inline(__always)
|
||||
internal mutating func insertItem(
|
||||
_ item: __owned Element, _ bucket: _Bucket
|
||||
_ item: __owned Element, at bucket: _Bucket
|
||||
) {
|
||||
let slot = read { $0.itemMap.slot(of: bucket) }
|
||||
self.insertItem(item, at: slot, bucket)
|
||||
|
||||
@@ -62,6 +62,21 @@ extension _Node.UnsafeHandle {
|
||||
}
|
||||
|
||||
extension _Node {
|
||||
@inlinable
|
||||
internal mutating func removeItem(
|
||||
at bucket: _Bucket
|
||||
) -> Element {
|
||||
let slot = read { $0.itemMap.slot(of: bucket) }
|
||||
return removeItem(at: slot, bucket, by: { $0.move() })
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func removeItem(
|
||||
at slot: _Slot, _ bucket: _Bucket
|
||||
) -> Element {
|
||||
removeItem(at: slot, bucket, by: { $0.move() })
|
||||
}
|
||||
|
||||
/// Remove the item at `slot`, increasing the amount of free
|
||||
/// space available in the node.
|
||||
///
|
||||
|
||||
@@ -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 _Node {
|
||||
@inlinable
|
||||
internal mutating func replaceItem(
|
||||
at bucket: _Bucket, _ slot: _Slot, with item: 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: _Node
|
||||
) -> 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: _Slot, with child: _Node
|
||||
) -> Int {
|
||||
let delta = 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: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ slot: _Slot,
|
||||
with child: __owned Builder
|
||||
) -> Builder {
|
||||
let bucket = hashPrefix[level]
|
||||
read {
|
||||
assert(!$0.isCollisionNode)
|
||||
assert($0.childMap.contains(bucket))
|
||||
assert(slot == $0.childMap.slot(of: bucket))
|
||||
}
|
||||
switch child {
|
||||
case .empty:
|
||||
return _removingChild(level, hashPrefix, bucket, slot)
|
||||
case let .item(item, hash):
|
||||
assert(hash.isEqual(to: hashPrefix, upTo: level))
|
||||
assert(hash[level] == bucket)
|
||||
if hasSingletonChild {
|
||||
return child
|
||||
}
|
||||
var node = self.copy(withFreeSpace: _Node.spaceForInlinedChild)
|
||||
_ = node.removeChild(at: slot, bucket)
|
||||
node.insertItem(item, at: bucket)
|
||||
node._invariantCheck()
|
||||
return .node(node, hashPrefix)
|
||||
case let .node(node, hash):
|
||||
assert(hash.isEqual(to: hashPrefix, upTo: level))
|
||||
assert(hash[level] == bucket)
|
||||
if node.isCollisionNode, self.hasSingletonChild {
|
||||
// Compression
|
||||
assert(!level.isAtBottom)
|
||||
return child
|
||||
}
|
||||
var copy = self.copy()
|
||||
_ = copy.replaceChild(at: bucket, slot, with: node)
|
||||
return .node(copy, hashPrefix)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,34 +15,71 @@ extension _Node {
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ isIncluded: (Element) throws -> Bool
|
||||
) rethrows -> Builder {
|
||||
// FIXME: Consider preserving `self` when nothing needs to be removed.
|
||||
) rethrows -> Builder? {
|
||||
guard !isCollisionNode else {
|
||||
return try _filter_slow(isIncluded)
|
||||
}
|
||||
return try self.read {
|
||||
var result: Builder = .empty
|
||||
|
||||
if isCollisionNode {
|
||||
let items = $0.reverseItems
|
||||
for i in items.indices {
|
||||
if try isIncluded(items[i]) {
|
||||
result.addNewCollision(items[i], $0.collisionHash)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
var removing = false // true if we need to remove something
|
||||
|
||||
for (bucket, slot) in $0.itemMap {
|
||||
let p = $0.itemPtr(at: slot)
|
||||
if try isIncluded(p.pointee) {
|
||||
let include = try isIncluded(p.pointee)
|
||||
switch (include, removing) {
|
||||
case (true, true):
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewItem(level, p.pointee, h)
|
||||
case (false, false):
|
||||
removing = true
|
||||
result.copyItems(level, hashPrefix, from: $0, upTo: bucket)
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for (bucket, slot) in $0.childMap {
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
let branch = try $0[child: slot].filter(level.descend(), h, isIncluded)
|
||||
result.addNewChildBranch(level, branch)
|
||||
if let branch = branch {
|
||||
assert(branch.count < self.count)
|
||||
if !removing {
|
||||
removing = true
|
||||
result.copyItemsAndChildren(
|
||||
level, hashPrefix, from: $0, upTo: bucket)
|
||||
}
|
||||
result.addNewChildBranch(level, branch)
|
||||
} else if removing {
|
||||
result.addNewChildBranch(level, .node($0[child: slot], h))
|
||||
}
|
||||
}
|
||||
|
||||
guard removing else { return nil }
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable @inline(never)
|
||||
internal func _filter_slow(
|
||||
_ isIncluded: (Element) throws -> Bool
|
||||
) rethrows -> Builder? {
|
||||
try self.read {
|
||||
var result: Builder = .empty
|
||||
var removing = false
|
||||
|
||||
for slot: _Slot in stride(from: .zero, to: $0.itemsEndSlot, by: 1) {
|
||||
let p = $0.itemPtr(at: slot)
|
||||
let include = try isIncluded(p.pointee)
|
||||
if include, removing {
|
||||
result.addNewCollision(p.pointee, $0.collisionHash)
|
||||
}
|
||||
else if !include, !removing {
|
||||
removing = true
|
||||
result.copyCollisions(from: $0, upTo: slot)
|
||||
}
|
||||
}
|
||||
guard removing else { return nil }
|
||||
assert(result.count < self.count)
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,9 +15,8 @@ extension _Node {
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> Builder {
|
||||
// FIXME: Consider preserving `self` when nothing needs to be removed.
|
||||
if self.raw.storage === other.raw.storage { return .node(self, hashPrefix) }
|
||||
) -> Builder? {
|
||||
if self.raw.storage === other.raw.storage { return nil }
|
||||
|
||||
if self.isCollisionNode || other.isCollisionNode {
|
||||
return _intersection_slow(level, hashPrefix, other)
|
||||
@@ -26,50 +25,77 @@ extension _Node {
|
||||
return self.read { l in
|
||||
other.read { r in
|
||||
var result: Builder = .empty
|
||||
for (bucket, _) in l.itemMap.intersection(r.itemMap) {
|
||||
let lslot = l.itemMap.slot(of: bucket)
|
||||
let rslot = r.itemMap.slot(of: bucket)
|
||||
var removing = false
|
||||
|
||||
for (bucket, lslot) in l.itemMap {
|
||||
let lp = l.itemPtr(at: lslot)
|
||||
if lp.pointee.key == r[item: rslot].key {
|
||||
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 {
|
||||
let hashPrefix = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewItem(level, lp.pointee, hashPrefix)
|
||||
}
|
||||
}
|
||||
|
||||
for (bucket, _) in l.itemMap.intersection(r.childMap) {
|
||||
let lslot = l.itemMap.slot(of: bucket)
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
let lp = l.itemPtr(at: lslot)
|
||||
let h = _Hash(lp.pointee.key)
|
||||
if r[child: rslot].containsKey(level.descend(), lp.pointee.key, h) {
|
||||
let hashPrefix = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewItem(level, lp.pointee, hashPrefix)
|
||||
else if !include, !removing {
|
||||
removing = true
|
||||
result.copyItems(level, hashPrefix, from: l, upTo: bucket)
|
||||
}
|
||||
}
|
||||
|
||||
for (bucket, _) in l.childMap.intersection(r.itemMap) {
|
||||
let lslot = l.childMap.slot(of: 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 {
|
||||
UnsafeHandle.read(res.node) {
|
||||
let p = $0.itemPtr(at: res.slot)
|
||||
result.addNewItem(level, p.pointee, h)
|
||||
for (bucket, lslot) in l.childMap {
|
||||
if r.itemMap.contains(bucket) {
|
||||
if !removing {
|
||||
removing = true
|
||||
result.copyItemsAndChildren(
|
||||
level, hashPrefix, from: l, upTo: bucket)
|
||||
}
|
||||
let rslot = r.itemMap.slot(of: bucket)
|
||||
let rp = r.itemPtr(at: rslot)
|
||||
let h = _Hash(rp.pointee.key)
|
||||
let res = l[child: lslot].lookup(level.descend(), rp.pointee.key, h)
|
||||
if let res = res {
|
||||
UnsafeHandle.read(res.node) {
|
||||
let p = $0.itemPtr(at: res.slot)
|
||||
result.addNewItem(level, p.pointee, h)
|
||||
}
|
||||
}
|
||||
}
|
||||
else if r.childMap.contains(bucket) {
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
let branch = l[child: lslot].intersection(
|
||||
level.descend(),
|
||||
hashPrefix.appending(bucket, at: level),
|
||||
r[child: rslot])
|
||||
if let branch = branch {
|
||||
assert(branch.count < self.count)
|
||||
if !removing {
|
||||
removing = true
|
||||
result.copyItemsAndChildren(
|
||||
level, hashPrefix, from: l, upTo: bucket)
|
||||
}
|
||||
result.addNewChildBranch(level, branch)
|
||||
} else if removing {
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewChildBranch(level, .node(l[child: lslot], h))
|
||||
}
|
||||
}
|
||||
else if !removing {
|
||||
removing = true
|
||||
result.copyItemsAndChildren(
|
||||
level, hashPrefix, from: l, upTo: bucket)
|
||||
}
|
||||
}
|
||||
|
||||
for (bucket, _) in l.childMap.intersection(r.childMap) {
|
||||
let lslot = l.childMap.slot(of: bucket)
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
let branch = l[child: lslot].intersection(
|
||||
level.descend(),
|
||||
hashPrefix.appending(bucket, at: level),
|
||||
r[child: rslot])
|
||||
result.addNewChildBranch(level, branch)
|
||||
}
|
||||
guard removing else { return nil }
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -80,7 +106,7 @@ extension _Node {
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> Builder {
|
||||
) -> Builder? {
|
||||
let lc = self.isCollisionNode
|
||||
let rc = other.isCollisionNode
|
||||
if lc && rc {
|
||||
@@ -88,13 +114,22 @@ extension _Node {
|
||||
other.read { r in
|
||||
guard l.collisionHash == r.collisionHash else { return .empty }
|
||||
var result: Builder = .empty
|
||||
let litems = l.reverseItems
|
||||
var removing = false
|
||||
|
||||
let ritems = r.reverseItems
|
||||
for i in litems.indices {
|
||||
if ritems.contains(where: { $0.key == litems[i].key }) {
|
||||
result.addNewCollision(litems[i], l.collisionHash)
|
||||
for lslot: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) {
|
||||
let lp = l.itemPtr(at: lslot)
|
||||
let include = ritems.contains { $0.key == lp.pointee.key }
|
||||
if include, removing {
|
||||
result.addNewCollision(lp.pointee, l.collisionHash)
|
||||
}
|
||||
else if !include, !removing {
|
||||
removing = true
|
||||
result.copyCollisions(from: l, upTo: lslot)
|
||||
}
|
||||
}
|
||||
guard removing else { return nil }
|
||||
assert(result.count < self.count)
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -143,11 +178,18 @@ extension _Node {
|
||||
return .item(litem.pointee, r.collisionHash)
|
||||
}
|
||||
if l.childMap.contains(bucket) {
|
||||
let lslot = l.itemMap.slot(of: bucket)
|
||||
return intersection(
|
||||
let lslot = l.childMap.slot(of: bucket)
|
||||
let branch = l[child: lslot].intersection(
|
||||
level.descend(),
|
||||
hashPrefix.appending(bucket, at: level),
|
||||
l[child: lslot])
|
||||
other)
|
||||
guard let branch = branch else {
|
||||
assert(l[child: lslot].isCollisionNode)
|
||||
assert(l[child: lslot].collisionHash == r.collisionHash)
|
||||
// Compression
|
||||
return .node(l[child: lslot], r.collisionHash)
|
||||
}
|
||||
return .childBranch(level, branch)
|
||||
}
|
||||
return .empty
|
||||
}
|
||||
|
||||
@@ -17,13 +17,14 @@ extension _Node {
|
||||
_ level: _Level,
|
||||
with other: _Node<Key, Value2>
|
||||
) -> Bool {
|
||||
if self.raw.storage === other.raw.storage { return count == 0 }
|
||||
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: other)
|
||||
return other._isDisjointCollision(level, with: self)
|
||||
}
|
||||
|
||||
return self.read { l in
|
||||
@@ -96,8 +97,8 @@ extension _Node {
|
||||
return isDisjoint(level.descend(), with: r[child: slot])
|
||||
}
|
||||
if r.itemMap.contains(bucket) {
|
||||
let slot = r.itemMap.slot(of: bucket)
|
||||
let p = r.itemPtr(at: slot)
|
||||
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 }
|
||||
|
||||
@@ -27,7 +27,7 @@ extension _Node {
|
||||
guard lhs.collisionHash == rhs.collisionHash else { return false }
|
||||
let l = lhs.reverseItems
|
||||
let r = rhs.reverseItems
|
||||
guard l.count == r.count else { return false }
|
||||
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)
|
||||
|
||||
@@ -17,6 +17,7 @@ extension _Node {
|
||||
_ level: _Level,
|
||||
of other: _Node<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 }
|
||||
|
||||
@@ -42,8 +43,17 @@ extension _Node {
|
||||
return self.isSubset(level.descend(), of: $0[child: slot])
|
||||
}
|
||||
}
|
||||
|
||||
guard !other.isCollisionNode else { return false }
|
||||
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
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 _Node {
|
||||
@inlinable
|
||||
internal mutating func merge(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node,
|
||||
_ combine: (Value, Value) throws -> Value
|
||||
) rethrows {
|
||||
guard other.count > 0 else { return }
|
||||
guard self.count > 0 else {
|
||||
self = other
|
||||
return
|
||||
}
|
||||
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
|
||||
try self.read { l in
|
||||
let lp = l.itemPtr(at: .zero)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
self = copy
|
||||
return
|
||||
}
|
||||
|
||||
try _merge(level, hashPrefix, other, combine)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func _merge(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node,
|
||||
_ combine: (Value, Value) throws -> Value
|
||||
) rethrows {
|
||||
// Note: don't check storage identities -- we do need to merge the contents
|
||||
// of identical nodes.
|
||||
|
||||
if self.isCollisionNode || other.isCollisionNode {
|
||||
try _merge_slow(level, hashPrefix, other, combine)
|
||||
return
|
||||
}
|
||||
|
||||
var isUnique = self.isUnique()
|
||||
|
||||
try other.read { r in
|
||||
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)
|
||||
}
|
||||
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: _Node.spaceForSpawningChild)
|
||||
let item = self.removeItem(at: bucket)
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
} 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)
|
||||
try self.update { l in
|
||||
try l[child: lslot].merge(
|
||||
level.descend(),
|
||||
hashPrefix.appending(bucket, at: level),
|
||||
r[child: rslot],
|
||||
combine)
|
||||
}
|
||||
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)
|
||||
isUnique = true
|
||||
}
|
||||
for (bucket, _) in r.childMap.subtracting(seen) {
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
self.ensureUnique(
|
||||
isUnique: isUnique, withFreeSpace: _Node.spaceForNewChild)
|
||||
self.insertChild(r[child: rslot], bucket)
|
||||
isUnique = true
|
||||
}
|
||||
|
||||
assert(isUnique)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable @inline(never)
|
||||
internal mutating func _merge_slow(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node,
|
||||
_ combine: (Value, Value) throws -> Value
|
||||
) rethrows {
|
||||
let lc = self.isCollisionNode
|
||||
let rc = other.isCollisionNode
|
||||
if lc && rc {
|
||||
guard self.collisionHash == other.collisionHash else {
|
||||
self = _Node.build(
|
||||
level: level,
|
||||
child1: self, self.collisionHash,
|
||||
child2: other, other.collisionHash)
|
||||
return
|
||||
}
|
||||
var isUnique = self.isUnique()
|
||||
return try other.read { r in
|
||||
let originalItemCount = self.count
|
||||
for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) {
|
||||
let rp = r.itemPtr(at: rs)
|
||||
let lslot = self.read { l in
|
||||
let litems = l.reverseItems
|
||||
return litems
|
||||
.suffix(originalItemCount)
|
||||
.firstIndex { $0.key == rp.pointee.key }
|
||||
.map { _Slot(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)
|
||||
}
|
||||
isUnique = true
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
if r.childMap.contains(bucket) {
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
try self._merge(level.descend(), h, r[child: rslot], combine)
|
||||
var node = other.copy()
|
||||
_ = node.replaceChild(at: bucket, rslot, with: self)
|
||||
self = node
|
||||
return
|
||||
}
|
||||
|
||||
var node = other.copy(withFreeSpace: _Node.spaceForNewChild)
|
||||
node.insertChild(self, bucket)
|
||||
self = node
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
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: _Node.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
|
||||
}
|
||||
if self.read({ $0.childMap.contains(bucket) }) {
|
||||
self.ensureUnique(isUnique: isUnique)
|
||||
let delta = try self.update { l in
|
||||
let lslot = l.childMap.slot(of: bucket)
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
let lchild = l.childPtr(at: lslot)
|
||||
let origCount = lchild.pointee.count
|
||||
try lchild.pointee._merge(level.descend(), h, other, combine)
|
||||
return lchild.pointee.count &- origCount
|
||||
}
|
||||
assert(delta >= 0)
|
||||
self.count &+= delta
|
||||
return
|
||||
}
|
||||
self.ensureUnique(
|
||||
isUnique: isUnique, withFreeSpace: _Node.spaceForNewChild)
|
||||
self.insertChild(other, bucket)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,7 @@ extension _Node {
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> Builder {
|
||||
// FIXME: Consider preserving `self` when nothing needs to be removed.
|
||||
) -> Builder? {
|
||||
if self.raw.storage === other.raw.storage { return .empty }
|
||||
|
||||
if self.isCollisionNode || other.isCollisionNode {
|
||||
@@ -26,50 +25,82 @@ extension _Node {
|
||||
return self.read { l in
|
||||
other.read { r in
|
||||
var result: Builder = .empty
|
||||
for (bucket, _) in l.itemMap.intersection(r.itemMap) {
|
||||
let lslot = l.itemMap.slot(of: bucket)
|
||||
let rslot = r.itemMap.slot(of: bucket)
|
||||
var removing = false
|
||||
|
||||
for (bucket, lslot) in l.itemMap {
|
||||
let lp = l.itemPtr(at: lslot)
|
||||
if lp.pointee.key != r[item: rslot].key {
|
||||
let hashPrefix = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewItem(level, lp.pointee, hashPrefix)
|
||||
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 {
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewItem(level, lp.pointee, h)
|
||||
}
|
||||
else if !include, !removing {
|
||||
removing = true
|
||||
result.copyItems(level, hashPrefix, from: l, upTo: bucket)
|
||||
}
|
||||
}
|
||||
|
||||
for (bucket, _) in l.itemMap.intersection(r.childMap) {
|
||||
let lslot = l.itemMap.slot(of: bucket)
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
let lp = l.itemPtr(at: lslot)
|
||||
let h = _Hash(lp.pointee.key)
|
||||
if !r[child: rslot].containsKey(level.descend(), lp.pointee.key, h) {
|
||||
let hashPrefix = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewItem(level, lp.pointee, hashPrefix)
|
||||
for (bucket, lslot) in l.childMap {
|
||||
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]
|
||||
.removing2(level.descend(), rp.pointee.key, h)?.replacement
|
||||
if let child = child {
|
||||
assert(child.count < self.count)
|
||||
if !removing {
|
||||
removing = true
|
||||
result.copyItemsAndChildren(
|
||||
level, hashPrefix, from: l, upTo: bucket)
|
||||
}
|
||||
result.addNewChildBranch(level, child)
|
||||
}
|
||||
else if removing {
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewChildBranch(level, .node(l[child: lslot], h))
|
||||
}
|
||||
}
|
||||
else if r.childMap.contains(bucket) {
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
let child = l[child: lslot].subtracting(
|
||||
level.descend(),
|
||||
hashPrefix.appending(bucket, at: level),
|
||||
r[child: rslot])
|
||||
if let child = child {
|
||||
assert(child.count < self.count)
|
||||
if !removing {
|
||||
removing = true
|
||||
result.copyItemsAndChildren(
|
||||
level, hashPrefix, from: l, upTo: bucket)
|
||||
}
|
||||
result.addNewChildBranch(level, child)
|
||||
}
|
||||
else if removing {
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewChildBranch(level, .node(l[child: lslot], h))
|
||||
}
|
||||
}
|
||||
else if removing {
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewChildBranch(level, .node(l[child: lslot], h))
|
||||
}
|
||||
}
|
||||
|
||||
for (bucket, _) in l.childMap.intersection(r.itemMap) {
|
||||
let lslot = l.childMap.slot(of: bucket)
|
||||
let rslot = r.itemMap.slot(of: bucket)
|
||||
let rp = r.itemPtr(at: rslot)
|
||||
let h = _Hash(rp.pointee.key)
|
||||
let node = (
|
||||
l[child: lslot]
|
||||
.removing(level.descend(), rp.pointee.key, h)?.replacement
|
||||
?? l[child: lslot])
|
||||
let branch = Builder(
|
||||
level.descend(), node, hashPrefix.appending(bucket, at: level))
|
||||
result.addNewChildBranch(level, branch)
|
||||
}
|
||||
|
||||
for (bucket, _) in l.childMap.intersection(r.childMap) {
|
||||
let lslot = l.childMap.slot(of: bucket)
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
let branch = l[child: lslot].subtracting(
|
||||
level.descend(),
|
||||
hashPrefix.appending(bucket, at: level),
|
||||
r[child: rslot])
|
||||
result.addNewChildBranch(level, branch)
|
||||
}
|
||||
guard removing else { return nil }
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -80,21 +111,32 @@ extension _Node {
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> Builder {
|
||||
) -> Builder? {
|
||||
let lc = self.isCollisionNode
|
||||
let rc = other.isCollisionNode
|
||||
if lc && rc {
|
||||
return read { l in
|
||||
other.read { r in
|
||||
guard l.collisionHash == r.collisionHash else { return .empty }
|
||||
guard l.collisionHash == r.collisionHash else {
|
||||
return nil
|
||||
}
|
||||
var result: Builder = .empty
|
||||
let litems = l.reverseItems
|
||||
var removing = false
|
||||
|
||||
let ritems = r.reverseItems
|
||||
for i in litems.indices {
|
||||
if !ritems.contains(where: { $0.key == litems[i].key }) {
|
||||
result.addNewCollision(litems[i], l.collisionHash)
|
||||
for lslot: _Slot in stride(from: .zero, to: l.itemsEndSlot, by: 1) {
|
||||
let lp = l.itemPtr(at: lslot)
|
||||
let include = !ritems.contains { $0.key == lp.pointee.key }
|
||||
if include, removing {
|
||||
result.addNewCollision(lp.pointee, l.collisionHash)
|
||||
}
|
||||
else if !include, !removing {
|
||||
removing = true
|
||||
result.copyCollisions(from: l, upTo: lslot)
|
||||
}
|
||||
}
|
||||
guard removing else { return nil }
|
||||
assert(result.count < self.count)
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -112,25 +154,19 @@ extension _Node {
|
||||
if r.itemMap.contains(bucket) {
|
||||
let rslot = r.itemMap.slot(of: bucket)
|
||||
let ritem = r.itemPtr(at: rslot)
|
||||
let res = l.find(level, ritem.pointee.key, _Hash(ritem.pointee.key))
|
||||
guard let res = res else {
|
||||
return .node(self, l.collisionHash)
|
||||
}
|
||||
assert(!res.descend)
|
||||
var node = self.copy()
|
||||
node.removeItem(at: res.slot, .invalid) {
|
||||
_ = $0.deinitialize(count: 1)
|
||||
}
|
||||
return Builder(level, node, l.collisionHash)
|
||||
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, hashPrefix.appending(bucket, at: level), res.slot
|
||||
).replacement
|
||||
}
|
||||
if r.childMap.contains(bucket) {
|
||||
else if r.childMap.contains(bucket) {
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
return subtracting(
|
||||
level.descend(),
|
||||
hashPrefix.appending(bucket, at: level),
|
||||
r[child: rslot])
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
return self.subtracting(level.descend(), h, r[child: rslot])
|
||||
}
|
||||
return .empty
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -145,19 +181,24 @@ extension _Node {
|
||||
let litem = l.itemPtr(at: lslot)
|
||||
let h = _Hash(litem.pointee.key)
|
||||
let res = r.find(level, litem.pointee.key, h)
|
||||
if res != nil { return .empty }
|
||||
return .item(litem.pointee, h)
|
||||
if res == nil { return nil }
|
||||
return self._removingItemFromLeaf(
|
||||
level, hashPrefix.appending(bucket, at: level), lslot
|
||||
).replacement
|
||||
}
|
||||
if l.childMap.contains(bucket) {
|
||||
let lslot = l.itemMap.slot(of: bucket)
|
||||
return subtracting(
|
||||
let lslot = l.childMap.slot(of: bucket)
|
||||
let branch = l[child: lslot].subtracting(
|
||||
level.descend(),
|
||||
hashPrefix.appending(bucket, at: level),
|
||||
l[child: lslot])
|
||||
other)
|
||||
guard let branch = branch else { return nil }
|
||||
var result = self._removingChild(level, hashPrefix, bucket, lslot)
|
||||
result.addNewChildBranch(level, branch)
|
||||
return result
|
||||
}
|
||||
return .empty
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 _Node {
|
||||
@inlinable
|
||||
internal func symmetricDifference(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> Builder? {
|
||||
guard self.count > 0 else { return .node(other, hashPrefix) }
|
||||
guard other.count > 0 else { return nil }
|
||||
return _symmetricDifference(level, hashPrefix, other)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _symmetricDifference(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> Builder {
|
||||
assert(self.count > 0 && other.count > 0)
|
||||
|
||||
if self.raw.storage === other.raw.storage {
|
||||
return .empty
|
||||
}
|
||||
if self.isCollisionNode || other.isCollisionNode {
|
||||
return _symmetricDifference_slow(level, hashPrefix, other)
|
||||
}
|
||||
|
||||
return self.read { l in
|
||||
other.read { r in
|
||||
var result: Builder = .empty
|
||||
|
||||
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 = _Node.build(
|
||||
level: level.descend(),
|
||||
item1: lp.pointee, h1,
|
||||
item2: { $0.initialize(to: rp.pointee) }, h2)
|
||||
result.addNewChildBranch(level, .node(child.top, h1))
|
||||
}
|
||||
}
|
||||
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
|
||||
.removing2(level.descend(), lp.pointee.key, h)?.replacement
|
||||
if let child = child {
|
||||
result.addNewChildBranch(level, child)
|
||||
}
|
||||
else {
|
||||
let child2 = rp.pointee.inserting(level.descend(), lp.pointee, h)
|
||||
assert(child2.inserted)
|
||||
result.addNewChildBranch(level, .node(child2.node, h))
|
||||
}
|
||||
}
|
||||
else {
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewItem(level, lp.pointee, h)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
.removing2(level.descend(), rp.pointee.key, h)?.replacement
|
||||
if let child = child {
|
||||
result.addNewChildBranch(level, child)
|
||||
}
|
||||
else {
|
||||
let child2 = lp.pointee.inserting(level.descend(), rp.pointee, h)
|
||||
assert(child2.inserted)
|
||||
result.addNewChildBranch(level, .node(child2.node, h))
|
||||
}
|
||||
}
|
||||
else if r.childMap.contains(bucket) {
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
let hp = hashPrefix.appending(bucket, at: level)
|
||||
let b = l[child: lslot]._symmetricDifference(
|
||||
level.descend(), hp, r[child: rslot])
|
||||
result.addNewChildBranch(level, b)
|
||||
}
|
||||
else {
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewChildBranch(level, .node(lp.pointee, h))
|
||||
}
|
||||
}
|
||||
|
||||
let seen = l.itemMap.union(l.childMap)
|
||||
for (bucket, rslot) in r.itemMap {
|
||||
guard !seen.contains(bucket) else { continue }
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewItem(level, r[item: rslot], h)
|
||||
}
|
||||
for (bucket, rslot) in r.childMap {
|
||||
guard !seen.contains(bucket) else { continue }
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
result.addNewChildBranch(level, .node(r[child: rslot], h))
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable @inline(never)
|
||||
internal func _symmetricDifference_slow(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> Builder {
|
||||
switch (self.isCollisionNode, other.isCollisionNode) {
|
||||
case (true, true):
|
||||
return self._symmetricDifference_slow_both(level, hashPrefix, other)
|
||||
case (true, false):
|
||||
return self._symmetricDifference_slow_left(level, hashPrefix, other)
|
||||
case (false, _):
|
||||
return other._symmetricDifference_slow_left(level, hashPrefix, self)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _symmetricDifference_slow_both(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> Builder {
|
||||
read { l in
|
||||
other.read { r in
|
||||
guard l.collisionHash == r.collisionHash else {
|
||||
let node = _Node.build(
|
||||
level: level,
|
||||
child1: self, l.collisionHash,
|
||||
child2: other, r.collisionHash)
|
||||
return .node(node, l.collisionHash)
|
||||
}
|
||||
var result: Builder = .empty
|
||||
let ritems = r.reverseItems
|
||||
for ls: _Slot 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(lp.pointee, l.collisionHash)
|
||||
}
|
||||
}
|
||||
// FIXME: Consider remembering slots of shared items in r by
|
||||
// caching them in a bitset.
|
||||
let litems = l.reverseItems
|
||||
for rs: _Slot in stride(from: .zero, to: r.itemsEndSlot, by: 1) {
|
||||
let rp = r.itemPtr(at: rs)
|
||||
let include = !litems.contains(where: { $0.key == rp.pointee.key })
|
||||
if include {
|
||||
result.addNewCollision(rp.pointee, r.collisionHash)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _symmetricDifference_slow_left(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> Builder {
|
||||
// `self` is a collision node on a compressed path. The other tree might
|
||||
// have the same set of collisions, just expanded a bit deeper.
|
||||
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 litems = l.reverseItems
|
||||
if let li = litems.firstIndex(where: { $0.key == rp.pointee.key }) {
|
||||
if l.itemCount == 2 {
|
||||
var node = other.copy()
|
||||
node.replaceItem(at: bucket, rslot, with: litems[1 &- li])
|
||||
return .node(node, l.collisionHash)
|
||||
}
|
||||
let lslot = _Slot(litems.count &- 1 &- li)
|
||||
var child = self.copy()
|
||||
_ = child.removeItem(at: lslot, .invalid)
|
||||
var node = other.copy(withFreeSpace: _Node.spaceForSpawningChild)
|
||||
_ = node.removeItem(at: rslot, bucket)
|
||||
node.insertChild(child, bucket)
|
||||
return .node(node, hashPrefix)
|
||||
}
|
||||
var node = other.copy(withFreeSpace: _Node.spaceForSpawningChild)
|
||||
let item = node.removeItem(at: rslot, bucket)
|
||||
let child = self.copyNodeAndAppendCollision {
|
||||
$0.initialize(to: item)
|
||||
}
|
||||
node.insertChild(child.node, bucket)
|
||||
return .node(node, hashPrefix)
|
||||
}
|
||||
if r.childMap.contains(bucket) {
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
let rp = r.childPtr(at: rslot)
|
||||
let hp = hashPrefix.appending(bucket, at: level)
|
||||
let child = rp.pointee._symmetricDifference(
|
||||
level.descend(), hp, self)
|
||||
return other.replacingChild(level, hp, rslot, with: child)
|
||||
}
|
||||
var node = other.copy(withFreeSpace: _Node.spaceForNewChild)
|
||||
node.insertChild(self, bucket)
|
||||
return .node(node, hashPrefix)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 _Node {
|
||||
@inlinable
|
||||
internal func union(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> (copied: Bool, node: _Node) {
|
||||
guard self.count > 0 else { return (true, other) }
|
||||
guard other.count > 0 else { return (false, self) }
|
||||
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
|
||||
let r = copy.updateValue(
|
||||
level, forKey: lp.pointee.key, _Hash(lp.pointee.key)
|
||||
) {
|
||||
$0.initialize(to: lp.pointee)
|
||||
}
|
||||
if !r.inserted {
|
||||
UnsafeHandle.update(r.leaf) {
|
||||
$0[item: r.slot] = lp.pointee
|
||||
}
|
||||
}
|
||||
return (true, copy)
|
||||
}
|
||||
}
|
||||
return _union(level, hashPrefix, other)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _union(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> (copied: Bool, node: _Node) {
|
||||
if self.raw.storage === other.raw.storage {
|
||||
return (false, self)
|
||||
}
|
||||
|
||||
if self.isCollisionNode || other.isCollisionNode {
|
||||
return _union_slow(level, hashPrefix, other)
|
||||
}
|
||||
|
||||
return self.read { l in
|
||||
other.read { r in
|
||||
var node = self
|
||||
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) })
|
||||
// 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: _Node.spaceForSpawningChild)
|
||||
let item = node.removeItem(at: bucket)
|
||||
let r = rp.pointee.inserting(level.descend(), item, _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].inserting(level.descend(), rp.pointee, 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(),
|
||||
hashPrefix.appending(bucket, at: level),
|
||||
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], at: bucket)
|
||||
copied = true
|
||||
}
|
||||
for (bucket, _) in r.childMap.subtracting(seen) {
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
node.ensureUnique(
|
||||
isUnique: copied, withFreeSpace: _Node.spaceForNewChild)
|
||||
copied = true
|
||||
node.insertChild(r[child: rslot], bucket)
|
||||
}
|
||||
|
||||
return (copied, node)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable @inline(never)
|
||||
internal func _union_slow(
|
||||
_ level: _Level,
|
||||
_ hashPrefix: _Hash,
|
||||
_ other: _Node
|
||||
) -> (copied: Bool, node: _Node) {
|
||||
let lc = self.isCollisionNode
|
||||
let rc = other.isCollisionNode
|
||||
if lc && rc {
|
||||
return read { l in
|
||||
other.read { r in
|
||||
guard l.collisionHash == r.collisionHash else {
|
||||
let node = _Node.build(
|
||||
level: level,
|
||||
child1: self, l.collisionHash,
|
||||
child2: other, r.collisionHash)
|
||||
return (true, node)
|
||||
}
|
||||
var copied = false
|
||||
var node = self
|
||||
let litems = l.reverseItems
|
||||
for rs: _Slot 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)
|
||||
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)
|
||||
}
|
||||
let node = other.copyNodeAndPushItemIntoNewChild(
|
||||
level: level,
|
||||
self,
|
||||
at: bucket,
|
||||
itemSlot: rslot)
|
||||
return (true, node)
|
||||
}
|
||||
|
||||
if r.childMap.contains(bucket) {
|
||||
let rslot = r.childMap.slot(of: bucket)
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
let res = self._union(level.descend(), h, r[child: rslot])
|
||||
var node = other.copy()
|
||||
let delta = node.replaceChild(at: bucket, rslot, with: res.node)
|
||||
assert(delta >= 0)
|
||||
return (true, node)
|
||||
}
|
||||
|
||||
var node = other.copy(withFreeSpace: _Node.spaceForNewChild)
|
||||
node.insertChild(self, bucket)
|
||||
return (true, node)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
assert(!l.hasSingletonItem) // Handled up front above
|
||||
let node = self.copyNodeAndPushItemIntoNewChild(
|
||||
level: level,
|
||||
other,
|
||||
at: bucket,
|
||||
itemSlot: lslot)
|
||||
return (true, node)
|
||||
}
|
||||
if l.childMap.contains(bucket) {
|
||||
let lslot = l.childMap.slot(of: bucket)
|
||||
let h = hashPrefix.appending(bucket, at: level)
|
||||
let child = l[child: lslot]._union(level.descend(), h, other)
|
||||
guard child.copied else { return (false, self) }
|
||||
var node = self.copy()
|
||||
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.copy(withFreeSpace: _Node.spaceForNewChild)
|
||||
node.insertChild(other, bucket)
|
||||
return (true, node)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,24 +14,117 @@ import _CollectionsUtilities
|
||||
extension _Node {
|
||||
@inlinable
|
||||
internal mutating func insert(
|
||||
_ item: __owned Element,
|
||||
_ level: _Level,
|
||||
_ hash: _Hash
|
||||
) -> Bool {
|
||||
let r = update(item.key, level, hash)
|
||||
guard r.inserted else { return false }
|
||||
UnsafeHandle.update(r.leaf) {
|
||||
let p = $0.itemPtr(at: r.slot)
|
||||
p.initialize(to: item)
|
||||
_ key: Key,
|
||||
_ hash: _Hash,
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) {
|
||||
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 = _Node.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
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal mutating func update(
|
||||
_ key: Key,
|
||||
internal func inserting(
|
||||
_ level: _Level,
|
||||
_ item: __owned Element,
|
||||
_ hash: _Hash
|
||||
) -> (inserted: Bool, node: _Node, leaf: _UnmanagedNode, slot: _Slot) {
|
||||
inserting(level, item.key, hash, { $0.initialize(to: item) })
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func inserting(
|
||||
_ level: _Level,
|
||||
_ key: Key,
|
||||
_ hash: _Hash,
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) -> (inserted: Bool, node: _Node, leaf: _UnmanagedNode, slot: _Slot) {
|
||||
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 = _Node.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: _Level,
|
||||
forKey key: Key,
|
||||
_ hash: _Hash,
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) {
|
||||
defer { _invariantCheck() }
|
||||
let isUnique = self.isUnique()
|
||||
@@ -41,31 +134,33 @@ extension _Node {
|
||||
ensureUnique(isUnique: isUnique)
|
||||
return (false, unmanaged, slot)
|
||||
case .insert(let bucket, let slot):
|
||||
ensureUniqueAndInsertItem(isUnique: isUnique, slot, bucket) { _ in }
|
||||
ensureUniqueAndInsertItem(
|
||||
isUnique: isUnique, at: bucket, itemSlot: slot, inserter)
|
||||
return (true, unmanaged, slot)
|
||||
case .appendCollision:
|
||||
ensureUniqueAndAppendCollision(isUnique: isUnique) { _ in }
|
||||
return (true, unmanaged, _Slot(self.count &- 1))
|
||||
let slot = ensureUniqueAndAppendCollision(isUnique: isUnique, inserter)
|
||||
return (true, unmanaged, slot)
|
||||
case .spawnChild(let bucket, let slot):
|
||||
let r = ensureUniqueAndSpawnChild(
|
||||
isUnique: isUnique,
|
||||
level: level,
|
||||
replacing: slot, bucket,
|
||||
replacing: bucket,
|
||||
itemSlot: slot,
|
||||
newHash: hash,
|
||||
inserter: { _ in }
|
||||
)
|
||||
inserter)
|
||||
return (true, r.leaf, r.slot)
|
||||
case .expansion:
|
||||
let r = _Node.build(
|
||||
level: level,
|
||||
item1: { _ in }, hash,
|
||||
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].update(key, level.descend(), hash)
|
||||
$0[child: slot].updateValue(
|
||||
level.descend(), forKey: key, hash, inserter)
|
||||
}
|
||||
if r.inserted { count &+= 1 }
|
||||
return r
|
||||
@@ -78,10 +173,14 @@ extension _Node {
|
||||
internal mutating func ensureUniqueAndInsertItem(
|
||||
isUnique: Bool,
|
||||
_ item: Element,
|
||||
_ bucket: _Bucket
|
||||
at bucket: _Bucket
|
||||
) {
|
||||
let slot = self.read { $0.itemMap.slot(of: bucket) }
|
||||
ensureUniqueAndInsertItem(isUnique: isUnique, slot, bucket) {
|
||||
ensureUniqueAndInsertItem(
|
||||
isUnique: isUnique,
|
||||
at: bucket,
|
||||
itemSlot: slot
|
||||
) {
|
||||
$0.initialize(to: item)
|
||||
}
|
||||
}
|
||||
@@ -89,18 +188,19 @@ extension _Node {
|
||||
@inlinable
|
||||
internal mutating func ensureUniqueAndInsertItem(
|
||||
isUnique: Bool,
|
||||
_ slot: _Slot,
|
||||
_ bucket: _Bucket,
|
||||
inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
at bucket: _Bucket,
|
||||
itemSlot slot: _Slot,
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) {
|
||||
assert(!isCollisionNode)
|
||||
|
||||
if !isUnique {
|
||||
self = copyNodeAndInsertItem(at: slot, bucket, inserter: inserter)
|
||||
self = copyNodeAndInsertItem(
|
||||
at: bucket, itemSlot: slot, inserter)
|
||||
return
|
||||
}
|
||||
if !hasFreeSpace(Self.spaceForNewItem) {
|
||||
moveNodeAndInsertItem(at: slot, bucket, inserter: inserter)
|
||||
resizeNodeAndInsertItem(at: bucket, itemSlot: slot, inserter)
|
||||
return
|
||||
}
|
||||
// In-place insert.
|
||||
@@ -111,19 +211,32 @@ extension _Node {
|
||||
self.count &+= 1
|
||||
}
|
||||
|
||||
@inlinable @inline(__always)
|
||||
internal func copyNodeAndInsertItem(
|
||||
at bucket: _Bucket,
|
||||
_ item: __owned Element
|
||||
) -> _Node {
|
||||
let slot = read { $0.itemMap.slot(of: bucket) }
|
||||
return copyNodeAndInsertItem(at: bucket, itemSlot: slot) {
|
||||
$0.initialize(to: item)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable @inline(never)
|
||||
internal func copyNodeAndInsertItem(
|
||||
at slot: _Slot,
|
||||
_ bucket: _Bucket,
|
||||
inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
at bucket: _Bucket,
|
||||
itemSlot slot: _Slot,
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) -> _Node {
|
||||
assert(!isCollisionNode)
|
||||
let (itemMap, childMap) = (
|
||||
self.raw.storage.header.bitmapsForInsertingItem(at: slot, bucket))
|
||||
let c = self.count
|
||||
return read { src in
|
||||
Self.allocate(
|
||||
itemMap: itemMap, childMap: childMap, count: c &+ 1
|
||||
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)
|
||||
|
||||
@@ -136,23 +249,25 @@ extension _Node {
|
||||
.initializeAll(fromContentsOf: srcItems.prefix(rest))
|
||||
|
||||
inserter(dstItems.baseAddress! + rest)
|
||||
}
|
||||
}.node
|
||||
}.node
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable @inline(never)
|
||||
internal mutating func moveNodeAndInsertItem(
|
||||
at slot: _Slot,
|
||||
_ bucket: _Bucket,
|
||||
inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
internal mutating func resizeNodeAndInsertItem(
|
||||
at bucket: _Bucket,
|
||||
itemSlot slot: _Slot,
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) {
|
||||
assert(!isCollisionNode)
|
||||
let (itemMap, childMap) = (
|
||||
self.raw.storage.header.bitmapsForInsertingItem(at: slot, bucket))
|
||||
let c = self.count
|
||||
self = update { src in
|
||||
Self.allocate(
|
||||
itemMap: itemMap, childMap: childMap, count: c &+ 1
|
||||
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)
|
||||
|
||||
@@ -167,8 +282,8 @@ extension _Node {
|
||||
inserter(dstItems.baseAddress! + rest)
|
||||
|
||||
src.clear()
|
||||
}
|
||||
}.node
|
||||
}.node
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,7 +292,7 @@ extension _Node {
|
||||
internal mutating func ensureUniqueAndAppendCollision(
|
||||
isUnique: Bool,
|
||||
_ item: Element
|
||||
) {
|
||||
) -> _Slot {
|
||||
ensureUniqueAndAppendCollision(isUnique: isUnique) {
|
||||
$0.initialize(to: item)
|
||||
}
|
||||
@@ -186,16 +301,16 @@ extension _Node {
|
||||
@inlinable
|
||||
internal mutating func ensureUniqueAndAppendCollision(
|
||||
isUnique: Bool,
|
||||
inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) {
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) -> _Slot {
|
||||
assert(isCollisionNode)
|
||||
if !isUnique {
|
||||
self = copyNodeAndAppendCollision(inserter: inserter)
|
||||
return
|
||||
let r = copyNodeAndAppendCollision(inserter)
|
||||
self = r.node
|
||||
return r.slot
|
||||
}
|
||||
if !hasFreeSpace(Self.spaceForNewItem) {
|
||||
moveNodeAndAppendCollision(inserter: inserter)
|
||||
return
|
||||
return resizeNodeAndAppendCollision(inserter)
|
||||
}
|
||||
// In-place insert.
|
||||
update {
|
||||
@@ -203,16 +318,17 @@ extension _Node {
|
||||
inserter(p)
|
||||
}
|
||||
self.count &+= 1
|
||||
return _Slot(self.count &- 1)
|
||||
}
|
||||
|
||||
@inlinable @inline(never)
|
||||
internal func copyNodeAndAppendCollision(
|
||||
inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) -> _Node {
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) -> (node: _Node, slot: _Slot) {
|
||||
assert(isCollisionNode)
|
||||
assert(self.count == read { $0.collisionCount })
|
||||
let c = self.count
|
||||
return read { src in
|
||||
let node = read { src in
|
||||
Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in
|
||||
let srcItems = src.reverseItems
|
||||
assert(dstItems.count == srcItems.count + 1)
|
||||
@@ -220,12 +336,13 @@ extension _Node {
|
||||
inserter(dstItems.baseAddress!)
|
||||
}.node
|
||||
}
|
||||
return (node, _Slot(c))
|
||||
}
|
||||
|
||||
@inlinable @inline(never)
|
||||
internal mutating func moveNodeAndAppendCollision(
|
||||
inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) {
|
||||
internal mutating func resizeNodeAndAppendCollision(
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) -> _Slot {
|
||||
assert(isCollisionNode)
|
||||
assert(self.count == read { $0.collisionCount })
|
||||
let c = self.count
|
||||
@@ -239,6 +356,178 @@ extension _Node {
|
||||
src.clear()
|
||||
}.node
|
||||
}
|
||||
return _Slot(c)
|
||||
}
|
||||
}
|
||||
|
||||
extension _Node {
|
||||
@inlinable
|
||||
internal func _copyNodeAndReplaceItemWithNewChild(
|
||||
level: _Level,
|
||||
_ newChild: __owned _Node,
|
||||
at bucket: _Bucket,
|
||||
itemSlot: _Slot
|
||||
) -> _Node {
|
||||
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: _Level,
|
||||
_ newChild: __owned _Node,
|
||||
at bucket: _Bucket,
|
||||
itemSlot: _Slot
|
||||
) {
|
||||
let c = self.count
|
||||
let node = 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 _Node {
|
||||
@inlinable
|
||||
internal mutating func ensureUniqueAndPushItemIntoNewChild(
|
||||
isUnique: Bool,
|
||||
level: _Level,
|
||||
_ newChild: _Node,
|
||||
at bucket: _Bucket,
|
||||
itemSlot: _Slot
|
||||
) {
|
||||
if !isUnique {
|
||||
self = copyNodeAndPushItemIntoNewChild(
|
||||
level: level,
|
||||
newChild,
|
||||
at: bucket,
|
||||
itemSlot: itemSlot)
|
||||
return
|
||||
}
|
||||
if !hasFreeSpace(Self.spaceForSpawningChild) {
|
||||
resizeNodeAndPushItemIntoNewChild(
|
||||
level: level,
|
||||
newChild,
|
||||
at: bucket,
|
||||
itemSlot: itemSlot)
|
||||
return
|
||||
}
|
||||
|
||||
assert(!isCollisionNode)
|
||||
let item = removeItem(at: itemSlot, bucket)
|
||||
let hash = _Hash(item.key)
|
||||
let r = newChild.inserting(level.descend(), item, hash)
|
||||
if self.count == 0, r.node.isCollisionNode {
|
||||
// Compression
|
||||
self = newChild
|
||||
} else {
|
||||
insertChild(r.node, bucket)
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable @inline(never)
|
||||
internal func copyNodeAndPushItemIntoNewChild(
|
||||
level: _Level,
|
||||
_ newChild: __owned _Node,
|
||||
at bucket: _Bucket,
|
||||
itemSlot: _Slot
|
||||
) -> _Node {
|
||||
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)
|
||||
}
|
||||
|
||||
@inlinable @inline(never)
|
||||
internal mutating func resizeNodeAndPushItemIntoNewChild(
|
||||
level: _Level,
|
||||
_ newChild: __owned _Node,
|
||||
at bucket: _Bucket,
|
||||
itemSlot: _Slot
|
||||
) {
|
||||
assert(!isCollisionNode)
|
||||
let item = update { $0.itemPtr(at: itemSlot).move() }
|
||||
let hash = _Hash(item.key)
|
||||
let r = newChild.inserting(level, item, hash)
|
||||
_resizeNodeAndReplaceItemWithNewChild(
|
||||
level: level,
|
||||
r.node,
|
||||
at: bucket,
|
||||
itemSlot: itemSlot)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,12 +536,13 @@ extension _Node {
|
||||
internal mutating func ensureUniqueAndSpawnChild(
|
||||
isUnique: Bool,
|
||||
level: _Level,
|
||||
replacing slot: _Slot,
|
||||
_ bucket: _Bucket,
|
||||
replacing bucket: _Bucket,
|
||||
itemSlot: _Slot,
|
||||
newHash: _Hash,
|
||||
inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) -> (leaf: _UnmanagedNode, slot: _Slot) {
|
||||
let existingHash = read { _Hash($0[item: slot].key) }
|
||||
let existingHash = read { _Hash($0[item: itemSlot].key) }
|
||||
assert(existingHash.isEqual(to: newHash, upTo: level))
|
||||
if newHash == existingHash, hasSingletonItem {
|
||||
// Convert current node to a collision node.
|
||||
self = _Node._collisionNode(newHash, read { $0[item: .zero] }, inserter)
|
||||
@@ -262,23 +552,25 @@ extension _Node {
|
||||
if !isUnique {
|
||||
let r = copyNodeAndSpawnChild(
|
||||
level: level,
|
||||
replacing: slot, bucket,
|
||||
replacing: bucket,
|
||||
itemSlot: itemSlot,
|
||||
existingHash: existingHash,
|
||||
newHash: newHash,
|
||||
inserter: inserter)
|
||||
inserter)
|
||||
self = r.node
|
||||
return (r.leaf, r.slot)
|
||||
}
|
||||
if !hasFreeSpace(Self.spaceForSpawningChild) {
|
||||
return moveNodeAndSpawnChild(
|
||||
return resizeNodeAndSpawnChild(
|
||||
level: level,
|
||||
replacing: slot, bucket,
|
||||
replacing: bucket,
|
||||
itemSlot: itemSlot,
|
||||
existingHash: existingHash,
|
||||
newHash: newHash,
|
||||
inserter: inserter)
|
||||
inserter)
|
||||
}
|
||||
|
||||
let existing = removeItem(at: slot, bucket) { $0.move() }
|
||||
let existing = removeItem(at: itemSlot, bucket)
|
||||
let r = _Node.build(
|
||||
level: level.descend(),
|
||||
item1: existing, existingHash,
|
||||
@@ -290,96 +582,49 @@ extension _Node {
|
||||
@inlinable @inline(never)
|
||||
internal func copyNodeAndSpawnChild(
|
||||
level: _Level,
|
||||
replacing slot: _Slot,
|
||||
_ bucket: _Bucket,
|
||||
replacing bucket: _Bucket,
|
||||
itemSlot: _Slot,
|
||||
existingHash: _Hash,
|
||||
newHash: _Hash,
|
||||
inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) -> (node: _Node, leaf: _UnmanagedNode, slot: _Slot) {
|
||||
let (itemMap, childMap) = (
|
||||
self.raw.storage.header.bitmapsForSpawningChild(at: slot, bucket))
|
||||
let c = self.count
|
||||
let childSlot = childMap.slot(of: bucket)
|
||||
let r = read { src in
|
||||
Self.allocate(
|
||||
itemMap: itemMap, childMap: childMap, count: c &+ 1
|
||||
) { dstChildren, dstItems in
|
||||
let srcChildren = src.children
|
||||
let srcItems = src.reverseItems
|
||||
let i = srcItems.count &- 1 &- slot.value
|
||||
|
||||
// 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))
|
||||
|
||||
let r = _Node.build(
|
||||
level: level.descend(),
|
||||
item1: srcItems[i], existingHash,
|
||||
item2: inserter, newHash)
|
||||
dstChildren.initializeElement(at: childSlot.value, to: r.top)
|
||||
|
||||
// Initialize items.
|
||||
dstItems.prefix(i).initializeAll(fromContentsOf: srcItems.prefix(i))
|
||||
let rest2 = dstItems.count &- i
|
||||
dstItems.suffix(rest2)
|
||||
.initializeAll(fromContentsOf: srcItems.suffix(rest2))
|
||||
|
||||
return (leaf: r.leaf, slot: r.slot2)
|
||||
}
|
||||
let r = read {
|
||||
_Node.build(
|
||||
level: level.descend(),
|
||||
item1: $0[item: itemSlot], existingHash,
|
||||
item2: inserter, newHash)
|
||||
}
|
||||
return (r.node, r.result.leaf, r.result.slot)
|
||||
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 moveNodeAndSpawnChild(
|
||||
internal mutating func resizeNodeAndSpawnChild(
|
||||
level: _Level,
|
||||
replacing slot: _Slot,
|
||||
_ bucket: _Bucket,
|
||||
replacing bucket: _Bucket,
|
||||
itemSlot: _Slot,
|
||||
existingHash: _Hash,
|
||||
newHash: _Hash,
|
||||
inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
_ inserter: (UnsafeMutablePointer<Element>) -> Void
|
||||
) -> (leaf: _UnmanagedNode, slot: _Slot) {
|
||||
let (itemMap, childMap) = (
|
||||
self.raw.storage.header.bitmapsForSpawningChild(at: slot, bucket))
|
||||
let c = self.count
|
||||
let childSlot = childMap.slot(of: bucket)
|
||||
let r = update { src in
|
||||
Self.allocate(
|
||||
itemMap: itemMap, childMap: childMap, count: c &+ 1
|
||||
) { dstChildren, dstItems in
|
||||
let srcChildren = src.children
|
||||
let srcItems = src.reverseItems
|
||||
let i = srcItems.count &- 1 &- slot.value
|
||||
|
||||
// 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))
|
||||
|
||||
let r = _Node.build(
|
||||
level: level.descend(),
|
||||
item1: srcItems.moveElement(from: i), existingHash,
|
||||
item2: inserter, newHash)
|
||||
dstChildren.initializeElement(at: childSlot.value, to: r.top)
|
||||
|
||||
// Initialize items.
|
||||
dstItems.prefix(i).moveInitializeAll(fromContentsOf: srcItems.prefix(i))
|
||||
let rest2 = dstItems.count &- i
|
||||
dstItems.suffix(rest2)
|
||||
.moveInitializeAll(fromContentsOf: srcItems.suffix(rest2))
|
||||
|
||||
src.clear()
|
||||
return (leaf: r.leaf, slot: r.slot2)
|
||||
}
|
||||
let r = update {
|
||||
_Node.build(
|
||||
level: level.descend(),
|
||||
item1: $0.itemPtr(at: itemSlot).move(), existingHash,
|
||||
item2: inserter, newHash)
|
||||
}
|
||||
r.node._invariantCheck()
|
||||
self = r.node
|
||||
return (r.result.leaf, r.result.slot)
|
||||
_resizeNodeAndReplaceItemWithNewChild(
|
||||
level: level,
|
||||
r.top,
|
||||
at: bucket,
|
||||
itemSlot: itemSlot)
|
||||
_invariantCheck()
|
||||
return (r.leaf, r.slot2)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,9 +127,10 @@ extension _Node {
|
||||
_finalizeRemoval(.top, state.hash, at: state.path)
|
||||
case (false, true):
|
||||
// Insertion
|
||||
let inserted = insert(
|
||||
(state.key, state.value.unsafelyUnwrapped), .top, state.hash)
|
||||
assert(inserted)
|
||||
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
|
||||
@@ -206,7 +207,9 @@ extension _Node {
|
||||
inserted: false)
|
||||
|
||||
case .insert(let bucket, let slot):
|
||||
ensureUniqueAndInsertItem(isUnique: isUnique, slot, bucket) { _ in }
|
||||
ensureUniqueAndInsertItem(
|
||||
isUnique: isUnique, at: bucket, itemSlot: slot
|
||||
) { _ in }
|
||||
return DefaultedValueUpdateState(
|
||||
(key, defaultValue()),
|
||||
in: unmanaged,
|
||||
@@ -214,18 +217,19 @@ extension _Node {
|
||||
inserted: true)
|
||||
|
||||
case .appendCollision:
|
||||
ensureUniqueAndAppendCollision(isUnique: isUnique) { _ in }
|
||||
let slot = ensureUniqueAndAppendCollision(isUnique: isUnique) { _ in }
|
||||
return DefaultedValueUpdateState(
|
||||
(key, defaultValue()),
|
||||
in: unmanaged,
|
||||
at: _Slot(self.count &- 1),
|
||||
at: slot,
|
||||
inserted: true)
|
||||
|
||||
case .spawnChild(let bucket, let slot):
|
||||
let r = ensureUniqueAndSpawnChild(
|
||||
isUnique: isUnique,
|
||||
level: level,
|
||||
replacing: slot, bucket,
|
||||
replacing: bucket,
|
||||
itemSlot: slot,
|
||||
newHash: hash) { _ in }
|
||||
return DefaultedValueUpdateState(
|
||||
(key, defaultValue()),
|
||||
|
||||
@@ -64,6 +64,20 @@ extension _Node {
|
||||
level, r.slot, hash[level], r2.replacement),
|
||||
r2.old)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func removing2(
|
||||
_ level: _Level, _ key: Key, _ hash: _Hash
|
||||
) -> (replacement: Builder, old: Element)? {
|
||||
guard let r = find(level, key, hash) else { return nil }
|
||||
guard r.descend else {
|
||||
return _removingItemFromLeaf(level, hash, r.slot)
|
||||
}
|
||||
let r2 = read { $0[child: r.slot].removing2(level.descend(), key, hash) }
|
||||
guard let r2 = r2 else { return nil }
|
||||
let result = self.replacingChild(level, hash, r.slot, with: r2.replacement)
|
||||
return (result, r2.old)
|
||||
}
|
||||
}
|
||||
|
||||
extension _Node {
|
||||
@@ -150,13 +164,75 @@ extension _Node {
|
||||
return read { (replacement: $0[child: .zero], old: $0[item: .zero]) }
|
||||
}
|
||||
var node = self.copy()
|
||||
let old = node.removeItem(at: slot, bucket) { $0.move() }
|
||||
let old = node.removeItem(at: slot, bucket)
|
||||
if level.isAtRoot, node.isCollisionNode, node.hasSingletonItem {
|
||||
node._convertToRegularNode()
|
||||
}
|
||||
node._invariantCheck()
|
||||
return (node, old)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func _removingItemFromLeaf(
|
||||
_ level: _Level, _ hash: _Hash, _ slot: _Slot
|
||||
) -> (replacement: Builder, old: Element) {
|
||||
read {
|
||||
assert($0.isCollisionNode || $0.itemMap.contains(hash[level]))
|
||||
assert(!$0.isCollisionNode || slot.value < $0.collisionCount )
|
||||
assert($0.isCollisionNode || slot == $0.itemMap.slot(of: hash[level]))
|
||||
let willAtrophy = (
|
||||
$0.itemCount == 1
|
||||
&& $0.childCount == 1
|
||||
&& $0[child: .zero].isCollisionNode)
|
||||
if willAtrophy {
|
||||
let child = $0[child: .zero]
|
||||
let old = $0[item: .zero]
|
||||
return (.node(child, child.collisionHash), old)
|
||||
}
|
||||
let willEvaporate = ($0.itemCount == 2 && $0.childCount == 0)
|
||||
if willEvaporate {
|
||||
let remainder = $0[item: _Slot(1 &- slot.value)]
|
||||
let old = $0[item: slot]
|
||||
return (.item(remainder, hash), old)
|
||||
}
|
||||
var node = self.copy()
|
||||
let old = node.removeItem(at: slot, hash[level])
|
||||
node._invariantCheck()
|
||||
return (.node(node, hash), old)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension _Node {
|
||||
@inlinable
|
||||
internal func _removingChild(
|
||||
_ level: _Level, _ hashPrefix: _Hash, _ bucket: _Bucket, _ slot: _Slot
|
||||
) -> Builder {
|
||||
read {
|
||||
assert(!$0.isCollisionNode && $0.childMap.contains(bucket))
|
||||
let willAtrophy = (
|
||||
$0.itemCount == 0
|
||||
&& $0.childCount == 2
|
||||
&& $0[child: _Slot(1 &- slot.value)].isCollisionNode
|
||||
)
|
||||
if willAtrophy {
|
||||
let child = $0[child: _Slot(1 &- slot.value)]
|
||||
return .node(child, child.collisionHash)
|
||||
}
|
||||
let willTurnIntoItem = ($0.itemCount == 1 && $0.childCount == 1)
|
||||
if willTurnIntoItem {
|
||||
return .item($0[item: .zero], hashPrefix)
|
||||
}
|
||||
let willEvaporate = ($0.itemCount == 0 && $0.childCount == 1)
|
||||
if willEvaporate {
|
||||
return .empty
|
||||
}
|
||||
var node = self.copy()
|
||||
_ = node.removeChild(at: slot, bucket)
|
||||
node._invariantCheck()
|
||||
return .node(node, hashPrefix)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension _Node {
|
||||
@@ -173,7 +249,7 @@ extension _Node {
|
||||
let bucket = bucket(&self)
|
||||
var child = self.removeChild(at: slot, bucket)
|
||||
let item = child.removeSingletonItem()
|
||||
insertItem(item, bucket)
|
||||
insertItem(item, at: bucket)
|
||||
}
|
||||
if isAtrophied {
|
||||
self = removeSingletonChild()
|
||||
@@ -192,7 +268,7 @@ extension _Node {
|
||||
var node = copy(withFreeSpace: Self.spaceForInlinedChild)
|
||||
_ = node.removeChild(at: slot, bucket)
|
||||
let item = newChild.removeSingletonItem()
|
||||
node.insertItem(item, bucket)
|
||||
node.insertItem(item, at: bucket)
|
||||
node._invariantCheck()
|
||||
return node
|
||||
}
|
||||
|
||||
@@ -255,7 +255,7 @@ extension _Node.UnsafeHandle {
|
||||
|
||||
@inlinable
|
||||
internal func itemPtr(at slot: _Slot) -> UnsafeMutablePointer<Element> {
|
||||
assert(slot.value < itemCount)
|
||||
assert(slot.value <= itemCount)
|
||||
return _itemsEnd.advanced(by: -1 &- slot.value)
|
||||
}
|
||||
|
||||
|
||||
@@ -120,33 +120,3 @@ extension _StorageHeader {
|
||||
bytesFree = byteCapacity
|
||||
}
|
||||
}
|
||||
|
||||
extension _StorageHeader {
|
||||
@inlinable
|
||||
internal func bitmapsForInsertingItem(
|
||||
at slot: _Slot,
|
||||
_ bucket: _Bucket
|
||||
) -> (itemMap: _Bitmap, childMap: _Bitmap) {
|
||||
assert(!isCollisionNode)
|
||||
assert(!bucket.isInvalid)
|
||||
assert(!itemMap.contains(bucket) && !childMap.contains(bucket))
|
||||
var itemMap = self.itemMap
|
||||
itemMap.insert(bucket)
|
||||
assert(itemMap.slot(of: bucket) == slot)
|
||||
return (itemMap, childMap)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
internal func bitmapsForSpawningChild(
|
||||
at slot: _Slot,
|
||||
_ bucket: _Bucket
|
||||
) -> (itemMap: _Bitmap, childMap: _Bitmap) {
|
||||
assert(!isCollisionNode)
|
||||
assert(itemMap.contains(bucket))
|
||||
var itemMap = self.itemMap
|
||||
var childMap = self.childMap
|
||||
itemMap.remove(bucket)
|
||||
childMap.insert(bucket)
|
||||
return (itemMap, childMap)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ extension PersistentDictionary {
|
||||
_ isIncluded: (Element) throws -> Bool
|
||||
) rethrows -> Self {
|
||||
let result = try _root.filter(.top, .emptyPrefix, isIncluded)
|
||||
guard let result = result else { return self }
|
||||
return PersistentDictionary(_new: result.finalize(.top))
|
||||
}
|
||||
}
|
||||
+6
-4
@@ -35,10 +35,12 @@ extension PersistentDictionary {
|
||||
uniqueKeysWithValues keysAndValues: S
|
||||
) where S.Element == (Key, Value) {
|
||||
self.init()
|
||||
for (key, value) in keysAndValues {
|
||||
let hash = _Hash(key)
|
||||
let inserted = _root.insert((key, value), .top, hash)
|
||||
precondition(inserted, "Duplicate key: '\(key)'")
|
||||
for item in keysAndValues {
|
||||
let hash = _Hash(item.0)
|
||||
let r = _root.insert(.top, item.0, hash) {
|
||||
$0.initialize(to: item)
|
||||
}
|
||||
precondition(r.inserted, "Duplicate key: '\(item.0)'")
|
||||
}
|
||||
_invariantCheck()
|
||||
}
|
||||
|
||||
@@ -67,9 +67,7 @@ extension PersistentDictionary.Keys: Sequence {
|
||||
) -> Bool? {
|
||||
_base._root.containsKey(.top, element, _Hash(element))
|
||||
}
|
||||
}
|
||||
|
||||
extension PersistentDictionary.Keys: _FastMembershipCheckable {
|
||||
@inlinable
|
||||
public func contains(_ element: Element) -> Bool {
|
||||
_base._root.containsKey(.top, element, _Hash(element))
|
||||
|
||||
+19
-1
@@ -10,12 +10,20 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension PersistentDictionary {
|
||||
@inlinable
|
||||
public mutating func merge(
|
||||
_ keysAndValues: Self,
|
||||
uniquingKeysWith combine: (Value, Value) throws -> Value
|
||||
) rethrows {
|
||||
_invalidateIndices()
|
||||
try _root.merge(.top, .emptyPrefix, keysAndValues._root, combine)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public mutating func merge<S: Sequence>(
|
||||
_ keysAndValues: __owned S,
|
||||
uniquingKeysWith combine: (Value, Value) throws -> Value
|
||||
) rethrows where S.Element == (Key, Value) {
|
||||
// FIXME: Do a structural merge
|
||||
for (key, value) in keysAndValues {
|
||||
try self.updateValue(forKey: key) { target in
|
||||
if let old = target {
|
||||
@@ -38,6 +46,16 @@ extension PersistentDictionary {
|
||||
uniquingKeysWith: combine)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func merging(
|
||||
_ other: Self,
|
||||
uniquingKeysWith combine: (Value, Value) throws -> Value
|
||||
) rethrows -> Self {
|
||||
var copy = self
|
||||
try copy.merge(other, uniquingKeysWith: combine)
|
||||
return copy
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func merging<S: Sequence>(
|
||||
_ other: __owned S,
|
||||
|
||||
@@ -279,14 +279,13 @@ extension PersistentDictionary {
|
||||
_ value: __owned Value, forKey key: Key
|
||||
) -> Value? {
|
||||
let hash = _Hash(key)
|
||||
let r = _root.update(key, .top, hash)
|
||||
let r = _root.updateValue(.top, forKey: key, hash) {
|
||||
$0.initialize(to: (key, value))
|
||||
}
|
||||
_invalidateIndices()
|
||||
if r.inserted { return nil }
|
||||
return _Node.UnsafeHandle.update(r.leaf) {
|
||||
let p = $0.itemPtr(at: r.slot)
|
||||
if r.inserted {
|
||||
p.initialize(to: (key, value))
|
||||
return nil
|
||||
}
|
||||
let old = p.pointee.value
|
||||
p.pointee.value = value
|
||||
return old
|
||||
@@ -294,19 +293,19 @@ extension PersistentDictionary {
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@discardableResult
|
||||
internal mutating func _updateValue(
|
||||
_ value: __owned Value, forKey key: Key
|
||||
) {
|
||||
) -> Bool {
|
||||
let hash = _Hash(key)
|
||||
let r = _root.update(key, .top, hash)
|
||||
return _Node.UnsafeHandle.update(r.leaf) {
|
||||
let p = $0.itemPtr(at: r.slot)
|
||||
if r.inserted {
|
||||
p.initialize(to: (key, value))
|
||||
} else {
|
||||
p.pointee.value = value
|
||||
}
|
||||
let r = _root.updateValue(.top, forKey: key, hash) {
|
||||
$0.initialize(to: (key, value))
|
||||
}
|
||||
if r.inserted { return true }
|
||||
_Node.UnsafeHandle.update(r.leaf) {
|
||||
$0[item: r.slot].value = value
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// fluid/immutable API
|
||||
@@ -333,13 +332,11 @@ extension PersistentDictionary {
|
||||
with body: (inout Value) throws -> R
|
||||
) rethrows -> R {
|
||||
let hash = _Hash(key)
|
||||
let r = _root.update(key, .top, hash)
|
||||
let r = _root.updateValue(.top, forKey: key, hash) {
|
||||
$0.initialize(to: (key, defaultValue()))
|
||||
}
|
||||
return try _Node.UnsafeHandle.update(r.leaf) {
|
||||
let p = $0.itemPtr(at: r.slot)
|
||||
if r.inserted {
|
||||
p.initialize(to: (key, defaultValue()))
|
||||
}
|
||||
return try body(&p.pointee.value)
|
||||
try body(&$0[item: r.slot].value)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ extension PersistentSet {
|
||||
let result = try _root.filter(.top, .emptyPrefix) {
|
||||
try isIncluded($0.key)
|
||||
}
|
||||
guard let result = result else { return self }
|
||||
return PersistentSet(_new: result.finalize(.top))
|
||||
}
|
||||
}
|
||||
@@ -11,29 +11,27 @@
|
||||
|
||||
import _CollectionsUtilities
|
||||
|
||||
extension PersistentSet: _FastMembershipCheckable {
|
||||
extension PersistentSet: SetAlgebra {
|
||||
@inlinable
|
||||
public func contains(_ item: Element) -> Bool {
|
||||
_root.containsKey(.top, item, _Hash(item))
|
||||
}
|
||||
}
|
||||
|
||||
extension PersistentSet: SetAlgebra {
|
||||
@discardableResult
|
||||
@inlinable
|
||||
public mutating func insert(
|
||||
_ newMember: __owned Element
|
||||
) -> (inserted: Bool, memberAfterInsert: Element) {
|
||||
let hash = _Hash(newMember)
|
||||
_invalidateIndices()
|
||||
let r = _root.update(newMember, .top, hash)
|
||||
return _Node.UnsafeHandle.update(r.leaf) {
|
||||
let p = $0.itemPtr(at: r.slot)
|
||||
if r.inserted {
|
||||
p.initialize(to: (newMember, ()))
|
||||
return (true, newMember)
|
||||
}
|
||||
return (false, p.pointee.key)
|
||||
let r = _root.insert(.top, newMember, hash) {
|
||||
$0.initialize(to: (newMember, ()))
|
||||
}
|
||||
if r.inserted {
|
||||
_invalidateIndices()
|
||||
return (true, newMember)
|
||||
}
|
||||
return _Node.UnsafeHandle.read(r.leaf) {
|
||||
(false, $0[item: r.slot].key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,16 +39,12 @@ extension PersistentSet: SetAlgebra {
|
||||
@inlinable
|
||||
internal mutating func _insert(_ newMember: __owned Element) -> Bool {
|
||||
let hash = _Hash(newMember)
|
||||
let r = _root.update(newMember, .top, hash)
|
||||
guard r.inserted else { return false }
|
||||
_Node.UnsafeHandle.update(r.leaf) {
|
||||
let p = $0.itemPtr(at: r.slot)
|
||||
p.initialize(to: (newMember, ()))
|
||||
let r = _root.insert(.top, newMember, hash) {
|
||||
$0.initialize(to: (newMember, ()))
|
||||
}
|
||||
return true
|
||||
return r.inserted
|
||||
}
|
||||
|
||||
|
||||
@discardableResult
|
||||
@inlinable
|
||||
public mutating func remove(_ member: Element) -> Element? {
|
||||
@@ -63,15 +57,14 @@ extension PersistentSet: SetAlgebra {
|
||||
@inlinable
|
||||
public mutating func update(with newMember: __owned Element) -> Element? {
|
||||
let hash = _Hash(newMember)
|
||||
let r = _root.update(newMember, .top, hash)
|
||||
let r = _root.updateValue(.top, forKey: newMember, hash) {
|
||||
$0.initialize(to: (newMember, ()))
|
||||
}
|
||||
if r.inserted { return nil }
|
||||
return _Node.UnsafeHandle.update(r.leaf) {
|
||||
let p = $0.itemPtr(at: r.slot)
|
||||
if r.inserted {
|
||||
p.initialize(to: (newMember, ()))
|
||||
return nil
|
||||
}
|
||||
let old = p.pointee.key
|
||||
p.pointee = (newMember, ())
|
||||
let old = p.move().key
|
||||
p.initialize(to: (newMember, ()))
|
||||
return old
|
||||
}
|
||||
}
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 PersistentSet {
|
||||
@inlinable
|
||||
public func inserting(_ newMember: __owned Element) -> Self {
|
||||
let hash = _Hash(newMember)
|
||||
let r = _root.inserting(.top, (newMember, ()), hash)
|
||||
return PersistentSet(_new: r.node)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func removing(_ member: Element) -> Self {
|
||||
let hash = _Hash(member)
|
||||
let r = _root.removing(.top, member, hash)
|
||||
guard let r = r else { return self }
|
||||
return PersistentSet(_new: r.replacement)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func updating(with newMember: __owned Element) -> Self {
|
||||
var copy = self
|
||||
copy.update(with: newMember)
|
||||
return copy
|
||||
}
|
||||
}
|
||||
+17
@@ -10,6 +10,23 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension PersistentSet {
|
||||
/// Removes the elements of this set that aren't also in the given one.
|
||||
///
|
||||
/// var a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [0, 2, 4, 6]
|
||||
/// a.formIntersection(b)
|
||||
/// // `a` is now some permutation of `[2, 4]`
|
||||
///
|
||||
/// The result will only contain instances that were originally in `self`.
|
||||
/// (This matters if equal members can be distinguished by comparing their
|
||||
/// identities, or by some other means.)
|
||||
///
|
||||
/// - Parameter other: An arbitrary set of elements.
|
||||
/// - Complexity: Expected complexity is O(`self.count` + `other.count`) in
|
||||
/// the worst case, if `Element` properly implements hashing.
|
||||
/// However, the implementation is careful to make the best use of
|
||||
/// hash tree structure to minimize work when possible, e.g. by linking
|
||||
/// parts of the input trees directly into the result.
|
||||
@inlinable
|
||||
public mutating func formIntersection(_ other: Self) {
|
||||
self = intersection(other)
|
||||
|
||||
+14
@@ -10,6 +10,20 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension PersistentSet {
|
||||
/// Replace this set with the elements contained in this set or the given
|
||||
/// set, but not both.
|
||||
///
|
||||
/// var a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [0, 2, 4, 6]
|
||||
/// a.formSymmetricDifference(b)
|
||||
/// // `a` is now some permutation of `[0, 1, 3, 6]`
|
||||
///
|
||||
/// - Parameter other: An arbitrary set of elements.
|
||||
/// - Complexity: Expected complexity is O(`self.count` + `other.count`) in
|
||||
/// the worst case, if `Element` properly implements hashing.
|
||||
/// However, the implementation is careful to make the best use of
|
||||
/// hash tree structure to minimize work when possible, e.g. by linking
|
||||
/// parts of the input trees directly into the result.
|
||||
@inlinable
|
||||
public mutating func formSymmetricDifference(_ other: __owned Self) {
|
||||
self = symmetricDifference(other)
|
||||
|
||||
@@ -10,6 +10,24 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension PersistentSet {
|
||||
/// Adds the elements of the given set to this set.
|
||||
///
|
||||
/// var a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [0, 2, 4, 6]
|
||||
/// a.formUnion(b)
|
||||
/// // `a` is now some permutation of `[0, 1, 2, 3, 4, 6]`
|
||||
///
|
||||
/// For values that are members of both sets, this operation preserves the
|
||||
/// instances that were originally in `self`. (This matters if equal members
|
||||
/// can be distinguished by comparing their identities, or by some other
|
||||
/// means.)
|
||||
///
|
||||
/// - Parameter other: The set of elements to insert.
|
||||
/// - Complexity: Expected complexity is O(`self.count` + `other.count`) in
|
||||
/// the worst case, if `Element` properly implements hashing.
|
||||
/// However, the implementation is careful to make the best use of
|
||||
/// hash tree structure to minimize work when possible, e.g. by linking
|
||||
/// parts of the input trees directly into the result.
|
||||
@inlinable
|
||||
public mutating func formUnion(_ other: __owned Self) {
|
||||
self = union(other)
|
||||
|
||||
+23
-2
@@ -10,9 +10,30 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension PersistentSet {
|
||||
/// Returns a new set with the elements that are common to both this set and
|
||||
/// the provided other one.
|
||||
///
|
||||
/// var a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [0, 2, 4, 6]
|
||||
/// let c = a.intersection(b)
|
||||
/// // `c` is some permutation of `[2, 4]`
|
||||
///
|
||||
/// The result will only contain instances that were originally in `self`.
|
||||
/// (This matters if equal members can be distinguished by comparing their
|
||||
/// identities, or by some other means.)
|
||||
///
|
||||
/// - Parameter other: An arbitrary set of elements.
|
||||
/// - Complexity: Expected complexity is O(`self.count` + `other.count`) in
|
||||
/// the worst case, if `Element` properly implements hashing.
|
||||
/// However, the implementation is careful to make the best use of
|
||||
/// hash tree structure to minimize work when possible, e.g. by linking
|
||||
/// parts of the input trees directly into the result.
|
||||
@inlinable
|
||||
public func intersection(_ other: Self) -> Self {
|
||||
let result = _root.intersection(.top, .emptyPrefix, other._root)
|
||||
return Self(_new: result.finalize(.top))
|
||||
let builder = _root.intersection(.top, .emptyPrefix, other._root)
|
||||
guard let builder = builder else { return self }
|
||||
let root = builder.finalize(.top)
|
||||
root._fullInvariantCheck(.top, .emptyPrefix)
|
||||
return Self(_new: root)
|
||||
}
|
||||
}
|
||||
+45
-2
@@ -10,19 +10,62 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension PersistentSet {
|
||||
/// Returns a Boolean value that indicates whether the set has no members in
|
||||
/// common with the given set.
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [5, 6]
|
||||
/// a.isDisjoint(with: b) // true
|
||||
///
|
||||
/// - Parameter other: Another set.
|
||||
///
|
||||
/// - Returns: `true` if `self` has no elements in common with `other`;
|
||||
/// otherwise, `false`.
|
||||
///
|
||||
/// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on
|
||||
/// average, if `Element` implements high-quality hashing.
|
||||
@inlinable
|
||||
public func isDisjoint(with other: Self) -> Bool {
|
||||
self._root.isDisjoint(.top, with: other._root)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
/// Returns a Boolean value that indicates whether the set has no members in
|
||||
/// common with the given set.
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [5, 6]
|
||||
/// a.isDisjoint(with: b) // true
|
||||
///
|
||||
/// - Parameter other: The keys view of a persistent dictionary.
|
||||
///
|
||||
/// - Returns: `true` if `self` has no elements in common with `other`;
|
||||
/// otherwise, `false`.
|
||||
///
|
||||
/// - Complexity: Expected to be O(min(`self.count`, `other.count`)) on
|
||||
/// average, if `Element` implements high-quality hashing.
|
||||
@inlinable
|
||||
public func isDisjoint<Value>(
|
||||
with other: PersistentDictionary<Element, Value>.Keys
|
||||
) -> Bool {
|
||||
self._root.isDisjoint(.top, with: other._base._root)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
/// Returns a Boolean value that indicates whether the set has no members in
|
||||
/// common with the given set.
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [5, 6]
|
||||
/// a.isDisjoint(with: b) // true
|
||||
///
|
||||
/// - Parameter other: A sequence of elements, some of whose elements may
|
||||
/// appear more than once.
|
||||
///
|
||||
/// - Returns: `true` if `self` has no elements in common with `other`;
|
||||
/// otherwise, `false`.
|
||||
///
|
||||
/// - Complexity: In the worst case, this makes O(*n*) calls to
|
||||
/// `self.contains`, where *n* is the length of the sequence.
|
||||
@inlinable
|
||||
public func isDisjoint<S: Sequence>(with other: S) -> Bool
|
||||
where S.Element == Element
|
||||
{
|
||||
|
||||
+72
-12
@@ -12,12 +12,52 @@
|
||||
import _CollectionsUtilities
|
||||
|
||||
extension PersistentSet {
|
||||
/// Returns a Boolean value that indicates whether the set is a strict subset
|
||||
/// of the given set.
|
||||
///
|
||||
/// Set *A* is a strict subset of another set *B* if every member of *A* is
|
||||
/// also a member of *B* and *B* contains at least one element that is not a
|
||||
/// member of *A*. (Ignoring the order the elements appear in the sets.)
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// b.isStrictSubset(of: a) // true
|
||||
///
|
||||
/// - Parameter other: Another set.
|
||||
///
|
||||
/// - Returns: `true` if `self` is a strict subset of `other`; otherwise,
|
||||
/// `false`.
|
||||
///
|
||||
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
|
||||
/// implements high-quality hashing. The implementation is careful to make
|
||||
/// the best use of hash tree structure to minimize work when possible,
|
||||
/// e.g. by skipping over parts of the input trees.
|
||||
@inlinable
|
||||
public func isStrictSubset(of other: Self) -> Bool {
|
||||
guard self.count < other.count else { return false }
|
||||
return isSubset(of: other)
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether the set is a strict subset
|
||||
/// of the given set.
|
||||
///
|
||||
/// Set *A* is a strict subset of another set *B* if every member of *A* is
|
||||
/// also a member of *B* and *B* contains at least one element that is not a
|
||||
/// member of *A*. (Ignoring the order the elements appear in the sets.)
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// b.isStrictSubset(of: a) // true
|
||||
///
|
||||
/// - Parameter other: The keys view of a persistent dictionary.
|
||||
///
|
||||
/// - Returns: `true` if `self` is a strict subset of `other`; otherwise,
|
||||
/// `false`.
|
||||
///
|
||||
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
|
||||
/// implements high-quality hashing. The implementation is careful to make
|
||||
/// the best use of hash tree structure to minimize work when possible,
|
||||
/// e.g. by skipping over parts of the input trees.
|
||||
@inlinable
|
||||
public func isStrictSubset<Value>(
|
||||
of other: PersistentDictionary<Element, Value>.Keys
|
||||
@@ -26,23 +66,43 @@ extension PersistentSet {
|
||||
return isSubset(of: other)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func isStrictSubset<S: Sequence & _FastMembershipCheckable>(
|
||||
of other: S
|
||||
) -> Bool
|
||||
where S.Element == Element {
|
||||
guard self.isSubset(of: other) else { return false }
|
||||
return !other.allSatisfy { self.contains($0) }
|
||||
}
|
||||
|
||||
|
||||
/// Returns a Boolean value that indicates whether the set is a strict subset
|
||||
/// of the given set.
|
||||
///
|
||||
/// Set *A* is a strict subset of another set *B* if every member of *A* is
|
||||
/// also a member of *B* and *B* contains at least one element that is not a
|
||||
/// member of *A*. (Ignoring the order the elements appear in the sets.)
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// b.isStrictSubset(of: a) // true
|
||||
///
|
||||
/// - Parameter other: A sequence of elements, some of whose elements may
|
||||
/// appear more than once.
|
||||
///
|
||||
/// - Returns: `true` if `self` is a strict subset of `other`; otherwise,
|
||||
/// `false`.
|
||||
///
|
||||
/// - Complexity: In the worst case, this makes O(*n*) calls to
|
||||
/// `self.contains` (where *n* is the number of elements in `other`),
|
||||
/// and it constructs a temporary persistent set containing every
|
||||
/// element of the sequence.
|
||||
@inlinable
|
||||
public func isStrictSubset<S: Sequence>(of other: S) -> Bool
|
||||
where S.Element == Element
|
||||
{
|
||||
if other.underestimatedCount > self.count {
|
||||
return isSubset(of: other)
|
||||
var it = self.makeIterator()
|
||||
guard let first = it.next() else {
|
||||
return other.contains(where: { _ in true })
|
||||
}
|
||||
if let match = other._customContainsEquatableElement(first) {
|
||||
guard match else { return false }
|
||||
while let item = it.next() {
|
||||
guard other.contains(item) else { return false }
|
||||
}
|
||||
return !other.allSatisfy { self.contains($0) }
|
||||
}
|
||||
|
||||
// FIXME: Would making this a BitSet of seen positions be better?
|
||||
var seen: PersistentSet? = []
|
||||
var isStrict = false
|
||||
|
||||
+73
-12
@@ -12,12 +12,52 @@
|
||||
import _CollectionsUtilities
|
||||
|
||||
extension PersistentSet {
|
||||
/// Returns a Boolean value that indicates whether the set is a strict
|
||||
/// superset of the given set.
|
||||
///
|
||||
/// Set *A* is a strict superset of another set *B* if every member of *B* is
|
||||
/// also a member of *A* and *A* contains at least one element that is *not*
|
||||
/// a member of *B*. (Ignoring the order the elements appear in the sets.)
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// a.isStrictSuperset(of: b.unordered) // true
|
||||
///
|
||||
/// - Parameter other: Another set.
|
||||
///
|
||||
/// - Returns: `true` if `self` is a strict superset of `other`; otherwise,
|
||||
/// `false`.
|
||||
///
|
||||
/// - Complexity: Expected to be O(`other.count`) on average, if `Element`
|
||||
/// implements high-quality hashing. The implementation is careful to make
|
||||
/// the best use of hash tree structure to minimize work when possible,
|
||||
/// e.g. by skipping over parts of the input trees.
|
||||
@inlinable
|
||||
public func isStrictSuperset(of other: Self) -> Bool {
|
||||
guard self.count > other.count else { return false }
|
||||
return other._root.isSubset(.top, of: self._root)
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether the set is a strict
|
||||
/// superset of the given set.
|
||||
///
|
||||
/// Set *A* is a strict subset of another set *B* if every member of *A* is
|
||||
/// also a member of *B* and *B* contains at least one element that is not a
|
||||
/// member of *A*. (Ignoring the order the elements appear in the sets.)
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// a.isStrictSuperset(of: b.unordered) // true
|
||||
///
|
||||
/// - Parameter other: The keys view of a persistent dictionary.
|
||||
///
|
||||
/// - Returns: `true` if `self` is a strict subset of `other`; otherwise,
|
||||
/// `false`.
|
||||
///
|
||||
/// - Complexity: Expected to be O(`other.count`) on average, if `Element`
|
||||
/// implements high-quality hashing. The implementation is careful to make
|
||||
/// the best use of hash tree structure to minimize work when possible,
|
||||
/// e.g. by skipping over parts of the input trees.
|
||||
@inlinable
|
||||
public func isStrictSuperset<Value>(
|
||||
of other: PersistentDictionary<Element, Value>.Keys
|
||||
@@ -26,24 +66,45 @@ extension PersistentSet {
|
||||
return other._base._root.isSubset(.top, of: self._root)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func isStrictSuperset<S: Sequence & _FastMembershipCheckable>(
|
||||
of other: S
|
||||
) -> Bool
|
||||
where S.Element == Element
|
||||
{
|
||||
if self.count < other.underestimatedCount { return false }
|
||||
if !other.allSatisfy({ self.contains($0) }) { return false }
|
||||
return !self.allSatisfy { other.contains($0) }
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether the set is a strict
|
||||
/// superset of the given set.
|
||||
///
|
||||
/// Set *A* is a strict subset of another set *B* if every member of *A* is
|
||||
/// also a member of *B* and *B* contains at least one element that is not a
|
||||
/// member of *A*. (Ignoring the order the elements appear in the sets.)
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// a.isStrictSuperset(of: b.unordered) // true
|
||||
///
|
||||
/// - Parameter other: A sequence of elements, some of whose elements may
|
||||
/// appear more than once.
|
||||
///
|
||||
/// - Returns: `true` if `self` is a strict subset of `other`; otherwise,
|
||||
/// `false`.
|
||||
///
|
||||
/// - Complexity: In the worst case, this makes O(*n*) calls to
|
||||
/// `self.contains` (where *n* is the number of elements in `other`),
|
||||
/// and it constructs a temporary persistent set containing every
|
||||
/// element of the sequence.
|
||||
@inlinable
|
||||
public func isStrictSuperset<S: Sequence>(of other: S) -> Bool
|
||||
where S.Element == Element
|
||||
{
|
||||
guard self.count >= other.underestimatedCount else {
|
||||
var it = self.makeIterator()
|
||||
guard let first = it.next() else {
|
||||
return other.contains(where: { _ in true })
|
||||
}
|
||||
if let match = other._customContainsEquatableElement(first) {
|
||||
// Fast path: the sequence has fast containment checks.
|
||||
guard other.allSatisfy({ self.contains($0) }) else { return false }
|
||||
guard match else { return true }
|
||||
while let item = it.next() {
|
||||
guard other.contains(item) else { return true }
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// FIXME: Would making this a BitSet of seen positions be better?
|
||||
var seen: PersistentSet = []
|
||||
for item in other {
|
||||
|
||||
+66
-16
@@ -12,11 +12,47 @@
|
||||
import _CollectionsUtilities
|
||||
|
||||
extension PersistentSet {
|
||||
/// Returns a Boolean value that indicates whether this set is a subset of
|
||||
/// the given set.
|
||||
///
|
||||
/// Set *A* is a subset of another set *B* if every member of *A* is also a
|
||||
/// member of *B*, ignoring the order they appear in the two sets.
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// b.isSubset(of: a) // true
|
||||
///
|
||||
/// - Parameter other: Another set.
|
||||
///
|
||||
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
|
||||
///
|
||||
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
|
||||
/// implements high-quality hashing. The implementation is careful to make
|
||||
/// the best use of hash tree structure to minimize work when possible,
|
||||
/// e.g. by skipping over parts of the input trees.
|
||||
@inlinable
|
||||
public func isSubset(of other: Self) -> Bool {
|
||||
self._root.isSubset(.top, of: other._root)
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether this set is a subset of
|
||||
/// the given set.
|
||||
///
|
||||
/// Set *A* is a subset of another set *B* if every member of *A* is also a
|
||||
/// member of *B*, ignoring the order they appear in the two sets.
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// b.isSubset(of: a) // true
|
||||
///
|
||||
/// - Parameter other: The keys view of a persistent dictionary.
|
||||
///
|
||||
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
|
||||
///
|
||||
/// - Complexity: Expected to be O(`self.count`) on average, if `Element`
|
||||
/// implements high-quality hashing. The implementation is careful to make
|
||||
/// the best use of hash tree structure to minimize work when possible,
|
||||
/// e.g. by skipping over parts of the input trees.
|
||||
@inlinable
|
||||
public func isSubset<Value>(
|
||||
of other: PersistentDictionary<Element, Value>.Keys
|
||||
@@ -24,26 +60,40 @@ extension PersistentSet {
|
||||
self._root.isSubset(.top, of: other._base._root)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func isSubset<S: _FastMembershipCheckable>(
|
||||
of other: S
|
||||
) -> Bool
|
||||
where S.Element == Element {
|
||||
self.allSatisfy { other.contains($0) }
|
||||
}
|
||||
|
||||
@inlinable
|
||||
public func isSubset<S: Sequence & _FastMembershipCheckable>(
|
||||
of other: S
|
||||
) -> Bool
|
||||
where S.Element == Element {
|
||||
self.allSatisfy { other.contains($0) }
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether this set is a subset of
|
||||
/// the given sequence.
|
||||
///
|
||||
/// Set *A* is a subset of another set *B* if every member of *A* is also a
|
||||
/// member of *B*, ignoring the order they appear in the two sets.
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// b.isSubset(of: a) // true
|
||||
///
|
||||
/// - Parameter other: A sequence of elements, some of whose elements may
|
||||
/// appear more than once.
|
||||
///
|
||||
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
|
||||
///
|
||||
/// - Complexity: In the worst case, this makes O(*n*) calls to
|
||||
/// `self.contains` (where *n* is the number of elements in `other`),
|
||||
/// and it constructs a temporary persistent set containing every
|
||||
/// element of the sequence.
|
||||
@inlinable
|
||||
public func isSubset<S: Sequence>(of other: S) -> Bool
|
||||
where S.Element == Element
|
||||
{
|
||||
var it = self.makeIterator()
|
||||
guard let first = it.next() else { return true }
|
||||
if let match = other._customContainsEquatableElement(first) {
|
||||
// Fast path: the sequence has fast containment checks.
|
||||
guard match else { return false }
|
||||
while let item = it.next() {
|
||||
guard other.contains(item) else { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// FIXME: Would making this a BitSet of seen positions be better?
|
||||
var seen: PersistentSet = []
|
||||
for item in other {
|
||||
|
||||
+54
-4
@@ -10,11 +10,47 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension PersistentSet {
|
||||
/// Returns a Boolean value that indicates whether this set is a superset of
|
||||
/// the given set.
|
||||
///
|
||||
/// Set *A* is a superset of another set *B* if every member of *B* is also a
|
||||
/// member of *A*, ignoring the order they appear in the two sets.
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// a.isSuperset(of: b) // true
|
||||
///
|
||||
/// - Parameter other: Another set.
|
||||
///
|
||||
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
|
||||
///
|
||||
/// - Complexity: Expected to be O(`other.count`) on average, if `Element`
|
||||
/// implements high-quality hashing. The implementation is careful to make
|
||||
/// the best use of hash tree structure to minimize work when possible,
|
||||
/// e.g. by skipping over parts of the input trees.
|
||||
@inlinable
|
||||
public func isSuperset(of other: Self) -> Bool {
|
||||
other._root.isSubset(.top, of: self._root)
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether this set is a superset of
|
||||
/// the given set.
|
||||
///
|
||||
/// Set *A* is a superset of another set *B* if every member of *B* is also a
|
||||
/// member of *A*, ignoring the order they appear in the two sets.
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// a.isSuperset(of: b) // true
|
||||
///
|
||||
/// - Parameter other: The keys view of a persistent dictionary.
|
||||
///
|
||||
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
|
||||
///
|
||||
/// - Complexity: Expected to be O(`other.count`) on average, if `Element`
|
||||
/// implements high-quality hashing. The implementation is careful to make
|
||||
/// the best use of hash tree structure to minimize work when possible,
|
||||
/// e.g. by skipping over parts of the input trees.
|
||||
@inlinable
|
||||
public func isSuperset<Value>(
|
||||
of other: PersistentDictionary<Element, Value>
|
||||
@@ -22,13 +58,27 @@ extension PersistentSet {
|
||||
other._root.isSubset(.top, of: self._root)
|
||||
}
|
||||
|
||||
/// Returns a Boolean value that indicates whether this set is a superset of
|
||||
/// the given set.
|
||||
///
|
||||
/// Set *A* is a superset of another set *B* if every member of *B* is also a
|
||||
/// member of *A*, ignoring the order they appear in the two sets.
|
||||
///
|
||||
/// let a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [4, 2, 1]
|
||||
/// a.isSuperset(of: b) // true
|
||||
///
|
||||
/// - Parameter other: A sequence of elements, some of whose elements may
|
||||
/// appear more than once.
|
||||
///
|
||||
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
|
||||
///
|
||||
/// - Complexity: O(*n*) calls to `self.contains`, where *n* is the number
|
||||
/// of elements in `other`.
|
||||
@inlinable
|
||||
public func isSuperset<S: Sequence>(of other: S) -> Bool
|
||||
where S.Element == Element
|
||||
{
|
||||
guard self.count >= other.underestimatedCount else {
|
||||
return false
|
||||
}
|
||||
return other.allSatisfy { self.contains($0) }
|
||||
other.allSatisfy { self.contains($0) }
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,19 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension PersistentSet {
|
||||
/// Removes the elements of the given set from this set.
|
||||
///
|
||||
/// var a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [0, 2, 4, 6]
|
||||
/// a.subtract(b)
|
||||
/// // `a` is now some permutation of `[1, 3]`
|
||||
///
|
||||
/// - Parameter other: An arbitrary set of elements.
|
||||
/// - Complexity: Expected complexity is O(`self.count` + `other.count`) in
|
||||
/// the worst case, if `Element` properly implements hashing.
|
||||
/// However, the implementation is careful to make the best use of
|
||||
/// hash tree structure to minimize work when possible, e.g. by linking
|
||||
/// parts of the input trees directly into the result.
|
||||
@inlinable
|
||||
public mutating func subtract(_ other: Self) {
|
||||
self = subtracting(other)
|
||||
|
||||
+19
-2
@@ -10,9 +10,26 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension PersistentSet {
|
||||
/// Returns a new set containing the elements of this set that do not occur
|
||||
/// in the given other set.
|
||||
///
|
||||
/// var a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [0, 2, 4, 6]
|
||||
/// let c = a.subtracting(b)
|
||||
/// // `c` is some permutation of `[1, 3]`
|
||||
///
|
||||
/// - Parameter other: An arbitrary set of elements.
|
||||
/// - Complexity: Expected complexity is O(`self.count` + `other.count`) in
|
||||
/// the worst case, if `Element` properly implements hashing.
|
||||
/// However, the implementation is careful to make the best use of
|
||||
/// hash tree structure to minimize work when possible, e.g. by linking
|
||||
/// parts of the input trees directly into the result.
|
||||
@inlinable
|
||||
public __consuming func subtracting(_ other: Self) -> Self {
|
||||
let result = _root.subtracting(.top, .emptyPrefix, other._root)
|
||||
return Self(_new: result.finalize(.top))
|
||||
let builder = _root.subtracting(.top, .emptyPrefix, other._root)
|
||||
guard let builder = builder else { return self }
|
||||
let root = builder.finalize(.top)
|
||||
root._fullInvariantCheck(.top, .emptyPrefix)
|
||||
return Self(_new: root)
|
||||
}
|
||||
}
|
||||
+18
-2
@@ -10,9 +10,25 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
extension PersistentSet {
|
||||
/// Returns a new set with the elements that are either in this set or in
|
||||
/// `other`, but not in both.
|
||||
///
|
||||
/// var a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [0, 2, 4, 6]
|
||||
/// let c = a.symmetricDifference(b)
|
||||
/// // `c` is some permutation of `[0, 1, 3, 6]`
|
||||
///
|
||||
/// - Parameter other: An arbitrary set of elements.
|
||||
/// - Complexity: Expected complexity is O(`self.count` + `other.count`) in
|
||||
/// the worst case, if `Element` properly implements hashing.
|
||||
/// However, the implementation is careful to make the best use of
|
||||
/// hash tree structure to minimize work when possible, e.g. by linking
|
||||
/// parts of the input trees directly into the result.
|
||||
@inlinable
|
||||
public func symmetricDifference(_ other: __owned Self) -> Self {
|
||||
// FIXME: Do this with a structural merge.
|
||||
self.subtracting(self.intersection(other))
|
||||
let branch = _root.symmetricDifference(.top, .emptyPrefix, other._root)
|
||||
guard let branch = branch else { return self }
|
||||
let root = branch.finalize(.top)
|
||||
return PersistentSet(_new: root)
|
||||
}
|
||||
}
|
||||
@@ -9,14 +9,29 @@
|
||||
//
|
||||
//===----------------------------------------------------------------------===//
|
||||
|
||||
/// Returns a new set with the elements of both this and the given set.
|
||||
///
|
||||
/// var a: PersistentSet = [1, 2, 3, 4]
|
||||
/// let b: PersistentSet = [0, 2, 4, 6]
|
||||
/// let c = a.union(b)
|
||||
/// // `c` is some permutation of `[0, 1, 2, 3, 4, 6]`
|
||||
///
|
||||
/// For values that are members of both sets, the result set contains the
|
||||
/// instances that were originally in `self`. (This matters if equal members
|
||||
/// can be distinguished by comparing their identities, or by some other means.)
|
||||
///
|
||||
/// - Parameter other: The set of elements to insert.
|
||||
/// - Complexity: Expected complexity is O(`self.count` + `other.count`) in
|
||||
/// the worst case, if `Element` properly implements hashing.
|
||||
/// However, the implementation is careful to make the best use of
|
||||
/// hash tree structure to minimize work when possible, e.g. by linking
|
||||
/// parts of the input trees directly into the result.
|
||||
extension PersistentSet {
|
||||
@inlinable
|
||||
public func union(_ other: __owned Self) -> Self {
|
||||
// FIXME: Do this with a structural merge.
|
||||
var copy = self
|
||||
for item in other {
|
||||
copy.insert(item)
|
||||
}
|
||||
return copy
|
||||
let r = _root.union(.top, .emptyPrefix, other._root)
|
||||
guard r.copied else { return self }
|
||||
r.node._fullInvariantCheck(.top, .emptyPrefix)
|
||||
return PersistentSet(_new: r.node)
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,12 @@ public class LifetimeTracker {
|
||||
public func instances<S: Sequence>(for items: S) -> [LifetimeTracked<S.Element>] {
|
||||
return items.map { LifetimeTracked($0, for: self) }
|
||||
}
|
||||
|
||||
public func instances<S: Sequence, T>(
|
||||
for items: S, by transform: (S.Element) -> T
|
||||
) -> [LifetimeTracked<T>] {
|
||||
items.map { instance(for: transform($0)) }
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 utility protocol for marking container types (not necessarily
|
||||
/// conforming to `Sequence` or `Collection`) that provide a
|
||||
/// fast `contains` operation.
|
||||
public protocol _FastMembershipCheckable {
|
||||
// FIXME: Add as primary associated type on >=5.7
|
||||
associatedtype Element: Equatable
|
||||
|
||||
/// Returns a Boolean value that indicates whether the given element exists in `self`.
|
||||
///
|
||||
/// - Performance: O(log(*n*)) or better, where *n* is the size
|
||||
/// of `self` (for some definition of "size").
|
||||
func contains(_ item: Element) -> Bool
|
||||
}
|
||||
|
||||
extension Set: _FastMembershipCheckable {}
|
||||
extension Dictionary.Keys: _FastMembershipCheckable {}
|
||||
@@ -875,7 +875,7 @@ class OrderedDictionaryTests: CollectionTestCase {
|
||||
"OrderedDictionary<Int, Int>([0: 1, 2: 3, 4: 5])")
|
||||
}
|
||||
|
||||
func test_customReflectable() {
|
||||
func test_CustomReflectable() {
|
||||
do {
|
||||
let d: OrderedDictionary<Int, Int> = [1: 2, 3: 4, 5: 6]
|
||||
let mirror = Mirror(reflecting: d)
|
||||
|
||||
@@ -54,7 +54,7 @@ struct Collider:
|
||||
/// A type with precisely controlled hash values. This can be used to set up
|
||||
/// hash tables with fully deterministic contents.
|
||||
struct RawCollider:
|
||||
Hashable, CustomStringConvertible, CustomDebugStringConvertible
|
||||
Hashable, CustomStringConvertible
|
||||
{
|
||||
var identity: Int
|
||||
var hash: Hash
|
||||
@@ -93,10 +93,6 @@ struct RawCollider:
|
||||
}
|
||||
|
||||
var description: String {
|
||||
return "\(identity)"
|
||||
}
|
||||
|
||||
var debugDescription: String {
|
||||
"\(identity)-#\(hash)"
|
||||
"\(identity)#\(hash)"
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,12 @@ extension Hash: Equatable {
|
||||
}
|
||||
}
|
||||
|
||||
extension Hash: Hashable {
|
||||
func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(value)
|
||||
}
|
||||
}
|
||||
|
||||
extension Hash: CustomStringConvertible {
|
||||
var description: String {
|
||||
// Print hash values in radix 32 & reversed, so that the path in the hash
|
||||
@@ -48,7 +54,7 @@ extension Hash: CustomStringConvertible {
|
||||
let path = String(repeating: "0", count: Swift.max(0, c - p.count)) + p
|
||||
return String(path.reversed())
|
||||
#else
|
||||
return p
|
||||
return String(p.reversed())
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,6 +12,71 @@
|
||||
import _CollectionsTestSupport
|
||||
import PersistentCollections
|
||||
|
||||
/// A set of items whose subsets will produce a bunch of interesting test
|
||||
/// cases.
|
||||
///
|
||||
/// Note: Try to keep this short. Every new item added here will quadruple
|
||||
/// testing costs.
|
||||
let testItems = [
|
||||
RawCollider(1, "A"),
|
||||
RawCollider(2, "B"),
|
||||
RawCollider(3, "ACA"),
|
||||
RawCollider(4, "ACB"),
|
||||
RawCollider(5, "ACAD"),
|
||||
RawCollider(6, "ACAD"),
|
||||
RawCollider(7, "ACAEB"),
|
||||
RawCollider(8, "ACAEB"),
|
||||
RawCollider(9, "ACAEB"),
|
||||
// RawCollider(10, "ACAEB"),
|
||||
// RawCollider(11, "ADAD"),
|
||||
// RawCollider(12, "ACC"),
|
||||
]
|
||||
|
||||
extension LifetimeTracker {
|
||||
func persistentDictionary<Key, Value, C: Collection>(
|
||||
for items: C,
|
||||
keyTransform: (C.Element) -> Key,
|
||||
valueTransform: (C.Element) -> Value
|
||||
) -> PersistentDictionary<LifetimeTracked<Key>, LifetimeTracked<Value>> {
|
||||
PersistentDictionary(
|
||||
uniqueKeys: instances(for: items, by: keyTransform),
|
||||
values: instances(for: items, by: valueTransform))
|
||||
}
|
||||
|
||||
func persistentDictionary<Value, C: Collection>(
|
||||
for keys: C,
|
||||
by valueTransform: (C.Element) -> Value
|
||||
) -> PersistentDictionary<LifetimeTracked<C.Element>, LifetimeTracked<Value>>
|
||||
where C.Element: Hashable {
|
||||
PersistentDictionary(
|
||||
uniqueKeys: instances(for: keys),
|
||||
values: instances(for: keys, by: valueTransform))
|
||||
}
|
||||
|
||||
func dictionary<Key, Value, C: Collection>(
|
||||
for items: C,
|
||||
keyTransform: (C.Element) -> Key,
|
||||
valueTransform: (C.Element) -> Value
|
||||
) -> Dictionary<LifetimeTracked<Key>, LifetimeTracked<Value>> {
|
||||
Dictionary(
|
||||
uniqueKeysWithValues: zip(
|
||||
instances(for: items, by: keyTransform),
|
||||
instances(for: items, by: valueTransform)))
|
||||
}
|
||||
|
||||
func dictionary<Value, C: Collection>(
|
||||
for keys: C,
|
||||
by valueTransform: (C.Element) -> Value
|
||||
) -> Dictionary<LifetimeTracked<C.Element>, LifetimeTracked<Value>>
|
||||
where C.Element: Hashable {
|
||||
Dictionary(
|
||||
uniqueKeysWithValues: zip(
|
||||
instances(for: keys),
|
||||
instances(for: keys, by: valueTransform)))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// A list of example trees to use while testing persistent hash maps.
|
||||
///
|
||||
/// Each example has a name and a list of path specifications or collisions.
|
||||
@@ -189,13 +254,14 @@ let _fixtures: KeyValuePairs<String, [String]> = [
|
||||
],
|
||||
]
|
||||
|
||||
let fixtures: [RawFixture] = _fixtures.map {
|
||||
RawFixture(title: $0, contents: $1)
|
||||
let fixtures: [Fixture] = _fixtures.map {
|
||||
Fixture(title: $0, contents: $1)
|
||||
}
|
||||
|
||||
struct RawFixture {
|
||||
struct Fixture {
|
||||
let title: String
|
||||
let hashes: [Hash]
|
||||
let itemsInIterationOrder: [RawCollider]
|
||||
let itemsInInsertionOrder: [RawCollider]
|
||||
|
||||
init(title: String, contents: [String]) {
|
||||
self.title = title
|
||||
@@ -208,21 +274,24 @@ struct RawFixture {
|
||||
return path.uppercased() + String(repeating: "0", count: c)
|
||||
}
|
||||
|
||||
var paths: [String] = []
|
||||
var items: [(path: String, item: RawCollider)] = []
|
||||
var seen: Set<String> = []
|
||||
for item in contents {
|
||||
let path: String
|
||||
if let i = item.unicodeScalars.firstIndex(of: "*") {
|
||||
for var path in contents {
|
||||
if let i = path.unicodeScalars.firstIndex(of: "*") {
|
||||
// We need to extend the path of collisions with zeroes to
|
||||
// make sure they sort correctly.
|
||||
let p = String(item.unicodeScalars.prefix(upTo: i))
|
||||
guard let count = Int(item.suffix(from: i).dropFirst(), radix: 10)
|
||||
else { fatalError("Invalid item: '\(item)'") }
|
||||
let p = String(path.unicodeScalars.prefix(upTo: i))
|
||||
guard let count = Int(path.suffix(from: i).dropFirst(), radix: 10)
|
||||
else { fatalError("Invalid item: '\(path)'") }
|
||||
path = normalized(p)
|
||||
paths.append(contentsOf: repeatElement(path, count: count))
|
||||
let hash = Hash(path)!
|
||||
for _ in 0 ..< count {
|
||||
items.append((path, RawCollider(items.count, hash)))
|
||||
}
|
||||
} else {
|
||||
path = normalized(item)
|
||||
paths.append(path)
|
||||
path = normalized(path)
|
||||
let hash = Hash(path)!
|
||||
items.append((path, RawCollider(items.count, hash)))
|
||||
}
|
||||
|
||||
if !seen.insert(path).inserted {
|
||||
@@ -232,93 +301,127 @@ struct RawFixture {
|
||||
|
||||
var seenPrefixes: Set<Substring> = []
|
||||
var collidingPrefixes: Set<Substring> = []
|
||||
for p in paths {
|
||||
assert(p.count == maxDepth)
|
||||
for i in p.indices {
|
||||
let prefix = p[..<i]
|
||||
for p in items {
|
||||
assert(p.path.count == maxDepth)
|
||||
for i in p.path.indices {
|
||||
let prefix = p.path[..<i]
|
||||
if !seenPrefixes.insert(prefix).inserted {
|
||||
collidingPrefixes.insert(prefix)
|
||||
}
|
||||
}
|
||||
if !seenPrefixes.insert(p[...]).inserted {
|
||||
collidingPrefixes.insert(p[...])
|
||||
if !seenPrefixes.insert(p.path[...]).inserted {
|
||||
collidingPrefixes.insert(p.path[...])
|
||||
}
|
||||
}
|
||||
|
||||
self.itemsInInsertionOrder = items.map { $0.item }
|
||||
|
||||
// Sort paths into the order that we expect items will appear in the
|
||||
// dictionary.
|
||||
paths.sort { a, b in
|
||||
var i = a.startIndex
|
||||
var j = b.startIndex
|
||||
while i < a.endIndex && j < b.endIndex {
|
||||
let ac = collidingPrefixes.contains(a[...i])
|
||||
let bc = collidingPrefixes.contains(b[...j])
|
||||
items.sort { a, b in
|
||||
var i = a.path.startIndex
|
||||
var j = b.path.startIndex
|
||||
while i < a.path.endIndex && j < b.path.endIndex {
|
||||
let ac = collidingPrefixes.contains(a.path[...i])
|
||||
let bc = collidingPrefixes.contains(b.path[...j])
|
||||
switch (ac, bc) {
|
||||
case (true, false): return false
|
||||
case (false, true): return true
|
||||
default: break
|
||||
}
|
||||
if a[i] < b[j] { return true }
|
||||
if a[j] > b[j] { return false }
|
||||
a.formIndex(after: &i)
|
||||
b.formIndex(after: &j)
|
||||
if a.path[i] < b.path[j] { return true }
|
||||
if a.path[j] > b.path[j] { return false }
|
||||
a.path.formIndex(after: &i)
|
||||
b.path.formIndex(after: &j)
|
||||
}
|
||||
precondition(i == a.endIndex && j == b.endIndex)
|
||||
precondition(i == a.path.endIndex && j == b.path.endIndex)
|
||||
return false
|
||||
}
|
||||
|
||||
self.hashes = paths.map { Hash($0)! }
|
||||
self.itemsInIterationOrder = items.map { $0.item }
|
||||
}
|
||||
}
|
||||
|
||||
struct Fixture<Key: Hashable, Value> {
|
||||
typealias Element = (key: Key, value: Value)
|
||||
|
||||
let title: String
|
||||
let items: [Element]
|
||||
|
||||
init(
|
||||
_ raw: RawFixture,
|
||||
key keyGenerator: (Int, Hash) -> Key,
|
||||
value valueGenerator: (Int) -> Value
|
||||
) {
|
||||
self.title = raw.title
|
||||
self.items = raw.hashes.enumerated().map { i, hash in
|
||||
(key: keyGenerator(i, hash), value: valueGenerator(i))
|
||||
}
|
||||
}
|
||||
var count: Int { itemsInInsertionOrder.count }
|
||||
}
|
||||
|
||||
func withEachFixture(
|
||||
body: (Fixture<RawCollider, Int>) -> Void
|
||||
_ label: String = "fixture",
|
||||
body: (Fixture) -> Void
|
||||
) {
|
||||
for raw in fixtures {
|
||||
let entry = TestContext.current.push("fixture: \(raw.title)")
|
||||
for fixture in fixtures {
|
||||
let entry = TestContext.current.push("\(label): \(fixture.title)")
|
||||
defer { TestContext.current.pop(entry) }
|
||||
|
||||
let fixture = Fixture<RawCollider, Int>(
|
||||
raw,
|
||||
key: { RawCollider($0, $1) },
|
||||
value: { 100 + $0 })
|
||||
|
||||
body(fixture)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
extension LifetimeTracker {
|
||||
func persistentSet<Element: Hashable>(
|
||||
for fixture: Fixture,
|
||||
with transform: (RawCollider) -> Element
|
||||
) -> (
|
||||
map: PersistentSet<LifetimeTracked<Element>>,
|
||||
ref: [LifetimeTracked<Element>]
|
||||
) {
|
||||
let ref = fixture.itemsInIterationOrder.map { key in
|
||||
self.instance(for: transform(key))
|
||||
}
|
||||
let ref2 = fixture.itemsInInsertionOrder.map { key in
|
||||
self.instance(for: transform(key))
|
||||
}
|
||||
return (PersistentSet(ref2), ref)
|
||||
}
|
||||
|
||||
func persistentSet(
|
||||
for fixture: Fixture
|
||||
) -> (
|
||||
map: PersistentSet<LifetimeTracked<RawCollider>>,
|
||||
ref: [LifetimeTracked<RawCollider>]
|
||||
) {
|
||||
persistentSet(for: fixture) { key in key }
|
||||
}
|
||||
|
||||
func persistentDictionary<Key, Value>(
|
||||
for fixture: Fixture<Key, Value>
|
||||
for fixture: Fixture,
|
||||
keyTransform: (RawCollider) -> Key,
|
||||
valueTransform: (RawCollider) -> Value
|
||||
) -> (
|
||||
map: PersistentDictionary<LifetimeTracked<Key>, LifetimeTracked<Value>>,
|
||||
ref: [(key: LifetimeTracked<Key>, value: LifetimeTracked<Value>)]
|
||||
) {
|
||||
let ref = fixture.items.map { (key, value) in
|
||||
(key: self.instance(for: key), value: self.instance(for: value))
|
||||
let ref = fixture.itemsInIterationOrder.map { item in
|
||||
let key = keyTransform(item)
|
||||
let value = valueTransform(item)
|
||||
return (key: self.instance(for: key), value: self.instance(for: value))
|
||||
}
|
||||
let ref2 = fixture.items.map { (key, value) in
|
||||
(key: self.instance(for: key), value: self.instance(for: value))
|
||||
let ref2 = fixture.itemsInInsertionOrder.map { item in
|
||||
let key = keyTransform(item)
|
||||
let value = valueTransform(item)
|
||||
return (key: self.instance(for: key), value: self.instance(for: value))
|
||||
}
|
||||
return (PersistentDictionary(uniqueKeysWithValues: ref2), ref)
|
||||
}
|
||||
|
||||
func persistentDictionary<Value>(
|
||||
for fixture: Fixture,
|
||||
valueTransform: (Int) -> Value
|
||||
) -> (
|
||||
map: PersistentDictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Value>>,
|
||||
ref: [(key: LifetimeTracked<RawCollider>, value: LifetimeTracked<Value>)]
|
||||
) {
|
||||
persistentDictionary(
|
||||
for: fixture,
|
||||
keyTransform: { $0 },
|
||||
valueTransform: { valueTransform($0.identity) })
|
||||
}
|
||||
|
||||
func persistentDictionary(
|
||||
for fixture: Fixture
|
||||
) -> (
|
||||
map: PersistentDictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Int>>,
|
||||
ref: [(key: LifetimeTracked<RawCollider>, value: LifetimeTracked<Int>)]
|
||||
) {
|
||||
persistentDictionary(for: fixture) { $0 + 1000 }
|
||||
}
|
||||
}
|
||||
@@ -544,7 +544,7 @@ final class PersistentDictionarySmokeTests: CollectionTestCase {
|
||||
}
|
||||
|
||||
func testIteratorEnumeratesAllIfNoCollision() {
|
||||
let upperBound = 1_000_000
|
||||
let upperBound = 1_000
|
||||
|
||||
var map1: PersistentDictionary<Int, String> = [:]
|
||||
for index in 0..<upperBound {
|
||||
|
||||
@@ -264,19 +264,258 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
checkBidirectionalCollection(d, expectedContents: Array(d), by: ==)
|
||||
}
|
||||
|
||||
func test_Keys_BidirectionalCollection_fixtures() {
|
||||
withEachFixture { fixture in
|
||||
withLifetimeTracking { tracker in
|
||||
let (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
checkBidirectionalCollection(
|
||||
d.keys,
|
||||
expectedContents: ref.map { $0.key },
|
||||
by: ==)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_Values_BidirectionalCollection_fixtures() {
|
||||
withEachFixture { fixture in
|
||||
withLifetimeTracking { tracker in
|
||||
let (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
checkBidirectionalCollection(
|
||||
d.values,
|
||||
expectedContents: ref.map { $0.value },
|
||||
by: ==)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *)
|
||||
struct FancyDictionaryKey: CodingKeyRepresentable, Hashable, Codable {
|
||||
var value: Int
|
||||
|
||||
var codingKey: CodingKey { value.codingKey }
|
||||
|
||||
init(_ value: Int) {
|
||||
self.value = value
|
||||
}
|
||||
|
||||
init?<T: CodingKey>(codingKey: T) {
|
||||
guard let value = codingKey.intValue else { return nil}
|
||||
self.init(value)
|
||||
}
|
||||
}
|
||||
|
||||
struct BoringDictionaryKey: Hashable, Codable {
|
||||
var value: Int
|
||||
|
||||
init(_ value: Int) {
|
||||
self.value = value
|
||||
}
|
||||
}
|
||||
|
||||
func test_Encodable() throws {
|
||||
let d1: PersistentDictionary<String, Int> = [
|
||||
"one": 1, "two": 2, "three": 3]
|
||||
let v1: MinimalEncoder.Value = .dictionary([
|
||||
"one": .int(1), "two": .int(2), "three": .int(3)])
|
||||
expectEqual(try MinimalEncoder.encode(d1), v1)
|
||||
|
||||
let d2: PersistentDictionary<Int, String> = [
|
||||
1: "one", 2: "two", 3: "three"]
|
||||
let v2: MinimalEncoder.Value = .dictionary([
|
||||
"1": .string("one"),
|
||||
"2": .string("two"),
|
||||
"3": .string("three"),
|
||||
])
|
||||
expectEqual(try MinimalEncoder.encode(d2), v2)
|
||||
|
||||
if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) {
|
||||
let d3: PersistentDictionary<FancyDictionaryKey, Int16> = [
|
||||
FancyDictionaryKey(1): 10, FancyDictionaryKey(2): 20
|
||||
]
|
||||
let v3: MinimalEncoder.Value = .dictionary([
|
||||
"1": .int16(10), "2": .int16(20)
|
||||
])
|
||||
expectEqual(try MinimalEncoder.encode(d3), v3)
|
||||
}
|
||||
|
||||
let d4: PersistentDictionary<BoringDictionaryKey, UInt8> = [
|
||||
// Note: we only have a single element to prevent ordering
|
||||
// problems.
|
||||
BoringDictionaryKey(42): 23
|
||||
]
|
||||
let v4: MinimalEncoder.Value = .array([
|
||||
.dictionary(["value": .int(42)]),
|
||||
.uint8(23),
|
||||
])
|
||||
expectEqual(try MinimalEncoder.encode(d4), v4)
|
||||
}
|
||||
|
||||
func test_Decodable() throws {
|
||||
typealias PD<Key: Hashable, Value> = PersistentDictionary<Key, Value>
|
||||
|
||||
let d1: PersistentDictionary<String, Int> = [
|
||||
"one": 1, "two": 2, "three": 3]
|
||||
let v1: MinimalEncoder.Value = .dictionary([
|
||||
"one": .int(1), "two": .int(2), "three": .int(3)])
|
||||
expectEqual(
|
||||
try MinimalDecoder.decode(v1, as: PD<String, Int>.self),
|
||||
d1)
|
||||
|
||||
let d2: PersistentDictionary<Int, String> = [
|
||||
1: "one", 2: "two", 3: "three"]
|
||||
let v2: MinimalEncoder.Value = .dictionary([
|
||||
"1": .string("one"),
|
||||
"2": .string("two"),
|
||||
"3": .string("three"),
|
||||
])
|
||||
expectEqual(
|
||||
try MinimalDecoder.decode(v2, as: PD<Int, String>.self),
|
||||
d2)
|
||||
|
||||
if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) {
|
||||
let d3: PersistentDictionary<FancyDictionaryKey, Int16> = [
|
||||
FancyDictionaryKey(1): 10, FancyDictionaryKey(2): 20
|
||||
]
|
||||
let v3: MinimalEncoder.Value = .dictionary([
|
||||
"1": .int16(10), "2": .int16(20)
|
||||
])
|
||||
expectEqual(
|
||||
try MinimalDecoder.decode(v3, as: PD<FancyDictionaryKey, Int16>.self),
|
||||
d3)
|
||||
}
|
||||
|
||||
let d4: PersistentDictionary<BoringDictionaryKey, UInt8> = [
|
||||
// Note: we only have a single element to prevent ordering
|
||||
// problems.
|
||||
BoringDictionaryKey(42): 23
|
||||
]
|
||||
let v4: MinimalEncoder.Value = .array([
|
||||
.dictionary(["value": .int(42)]),
|
||||
.uint8(23),
|
||||
])
|
||||
expectEqual(
|
||||
try MinimalDecoder.decode(v4, as: PD<BoringDictionaryKey, UInt8>.self),
|
||||
d4)
|
||||
|
||||
let v5: MinimalEncoder.Value = .dictionary([
|
||||
"This is not a number": .string("bus"),
|
||||
"42": .string("train")])
|
||||
expectThrows(try MinimalDecoder.decode(v5, as: PD<Int, String>.self)) {
|
||||
expectTrue($0 is DecodingError)
|
||||
}
|
||||
|
||||
if #available(macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4, *) {
|
||||
let v6: MinimalEncoder.Value = .dictionary([
|
||||
"This is not a number": .string("bus"),
|
||||
"42": .string("train")])
|
||||
expectThrows(
|
||||
try MinimalDecoder.decode(
|
||||
v6, as: PD<FancyDictionaryKey, String>.self)
|
||||
) {
|
||||
expectTrue($0 is DecodingError)
|
||||
}
|
||||
|
||||
let v7: MinimalEncoder.Value = .dictionary([
|
||||
"23": .string("bus"),
|
||||
"42": .string("train")])
|
||||
let d7: PD<FancyDictionaryKey, String> = [
|
||||
FancyDictionaryKey(23): "bus",
|
||||
FancyDictionaryKey(42): "train",
|
||||
]
|
||||
expectEqual(
|
||||
try MinimalDecoder.decode(v7, as: PD<FancyDictionaryKey, String>.self),
|
||||
d7)
|
||||
}
|
||||
|
||||
let v8: MinimalEncoder.Value = .array([
|
||||
.int32(1), .string("bike"), .int32(2),
|
||||
])
|
||||
expectThrows(try MinimalDecoder.decode(v8, as: PD<Int32, String>.self))
|
||||
}
|
||||
|
||||
func test_CustomReflectable() {
|
||||
do {
|
||||
let d: PersistentDictionary<Int, Int> = [1: 2, 3: 4, 5: 6]
|
||||
let mirror = Mirror(reflecting: d)
|
||||
expectEqual(mirror.displayStyle, .dictionary)
|
||||
expectNil(mirror.superclassMirror)
|
||||
expectTrue(mirror.children.compactMap { $0.label }.isEmpty) // No label
|
||||
expectEqualElements(
|
||||
mirror.children.compactMap { $0.value as? (key: Int, value: Int) },
|
||||
d.map { $0 })
|
||||
}
|
||||
}
|
||||
|
||||
func test_Equatable_Hashable() {
|
||||
let samples: [[PersistentDictionary<Int, Int>]] = [
|
||||
[[:], [:]],
|
||||
[[1: 100], [1: 100]],
|
||||
[[2: 200], [2: 200]],
|
||||
[[3: 300], [3: 300]],
|
||||
[[100: 1], [100: 1]],
|
||||
[[1: 1], [1: 1]],
|
||||
[[100: 100], [100: 100]],
|
||||
[[1: 100, 2: 200], [2: 200, 1: 100]],
|
||||
[[1: 100, 2: 200, 3: 300],
|
||||
[1: 100, 3: 300, 2: 200],
|
||||
[2: 200, 1: 100, 3: 300],
|
||||
[2: 200, 3: 300, 1: 100],
|
||||
[3: 300, 1: 100, 2: 200],
|
||||
[3: 300, 2: 200, 1: 100]]
|
||||
]
|
||||
checkHashable(equivalenceClasses: samples)
|
||||
}
|
||||
|
||||
func test_CustomStringConvertible() {
|
||||
let a: PersistentDictionary<RawCollider, Int> = [:]
|
||||
expectEqual(a.description, "[:]")
|
||||
|
||||
let b: PersistentDictionary<RawCollider, Int> = [
|
||||
RawCollider(0): 1
|
||||
]
|
||||
expectEqual(b.description, "[0#0: 1]")
|
||||
|
||||
let c: PersistentDictionary<RawCollider, Int> = [
|
||||
RawCollider(0): 1,
|
||||
RawCollider(2): 3,
|
||||
RawCollider(4): 5,
|
||||
]
|
||||
expectEqual(c.description, "[0#0: 1, 2#2: 3, 4#4: 5]")
|
||||
}
|
||||
|
||||
func test_CustomDebugStringConvertible() {
|
||||
let a: PersistentDictionary<Int, Int> = [:]
|
||||
expectEqual(
|
||||
a.debugDescription,
|
||||
"PersistentDictionary<Int, Int>([:])")
|
||||
|
||||
let b: PersistentDictionary<Int, Int> = [0: 1]
|
||||
expectEqual(
|
||||
b.debugDescription,
|
||||
"PersistentDictionary<Int, Int>([0: 1])")
|
||||
|
||||
let c: PersistentDictionary<Int, Int> = [0: 1, 2: 3, 4: 5]
|
||||
let cd = c.map { "\($0.key): \($0.value)"}.joined(separator: ", ")
|
||||
expectEqual(
|
||||
c.debugDescription,
|
||||
"PersistentDictionary<Int, Int>([\(cd)])")
|
||||
}
|
||||
|
||||
|
||||
func test_updateValueForKey_fixtures() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withLifetimeTracking { tracker in
|
||||
var d: PersistentDictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Int>> = [:]
|
||||
var ref: Dictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Int>> = [:]
|
||||
withEvery("i", in: 0 ..< fixture.items.count) { i in
|
||||
withEvery("i", in: 0 ..< fixture.count) { i in
|
||||
withHiddenCopies(if: isShared, of: &d) { d in
|
||||
let item = fixture.items[i]
|
||||
let key = tracker.instance(for: item.key)
|
||||
let value = tracker.instance(for: item.value)
|
||||
d[key] = value
|
||||
ref[key] = value
|
||||
let item = fixture.itemsInInsertionOrder[i]
|
||||
let key1 = tracker.instance(for: item)
|
||||
let key2 = tracker.instance(for: item)
|
||||
let value = tracker.instance(for: 1000 + item.identity)
|
||||
d[key1] = value
|
||||
ref[key2] = value
|
||||
expectEqualDictionaries(d, ref)
|
||||
}
|
||||
}
|
||||
@@ -293,10 +532,10 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
withLifetimeTracking { tracker in
|
||||
var d: PersistentDictionary<LifetimeTracked<RawCollider>, Empty> = [:]
|
||||
var ref: Dictionary<LifetimeTracked<RawCollider>, Empty> = [:]
|
||||
withEvery("i", in: 0 ..< fixture.items.count) { i in
|
||||
withEvery("i", in: 0 ..< fixture.count) { i in
|
||||
withHiddenCopies(if: isShared, of: &d) { d in
|
||||
let item = fixture.items[i]
|
||||
let key = tracker.instance(for: item.key)
|
||||
let item = fixture.itemsInInsertionOrder[i]
|
||||
let key = tracker.instance(for: item)
|
||||
d[key] = Empty()
|
||||
ref[key] = Empty()
|
||||
expectEqualDictionaries(d, ref)
|
||||
@@ -307,9 +546,9 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_removeValueForKey_fixtures() {
|
||||
func test_removeValueForKey_fixtures_justOne() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("offset", in: 0 ..< fixture.items.count) { offset in
|
||||
withEvery("offset", in: 0 ..< fixture.count) { offset in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withLifetimeTracking { tracker in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
@@ -326,6 +565,27 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_removeValueForKey_fixtures_all() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withLifetimeTracking { tracker in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
var rng = RepeatableRandomNumberGenerator(seed: 0)
|
||||
withEvery("i", in: 0 ..< fixture.count) { _ in
|
||||
withHiddenCopies(if: isShared, of: &d) { d in
|
||||
let offset = ref.indices.randomElement(using: &rng)!
|
||||
let old = d.removeValue(forKey: ref[offset].key)
|
||||
d._invariantCheck()
|
||||
expectEqual(old, ref[offset].value)
|
||||
ref.remove(at: offset)
|
||||
expectEqualDictionaries(d, ref)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_subscript_getter_data() {
|
||||
func check<G: DataGenerator>(count: Int, generator: G) {
|
||||
context.withTrace("count: \(count), generator: \(generator)") {
|
||||
@@ -384,7 +644,7 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
|
||||
func test_subscript_setter_update_fixtures() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("offset", in: 0 ..< fixture.items.count) { offset in
|
||||
withEvery("offset", in: 0 ..< fixture.count) { offset in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withLifetimeTracking { tracker in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
@@ -426,7 +686,7 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
|
||||
func test_subscript_setter_remove_fixtures() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("offset", in: 0 ..< fixture.items.count) { offset in
|
||||
withEvery("offset", in: 0 ..< fixture.count) { offset in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withLifetimeTracking { tracker in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
@@ -491,11 +751,11 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
withLifetimeTracking { tracker in
|
||||
var d: PersistentDictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Int>> = [:]
|
||||
var ref: Dictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Int>> = [:]
|
||||
withEvery("i", in: 0 ..< fixture.items.count) { i in
|
||||
withEvery("i", in: 0 ..< fixture.count) { i in
|
||||
withHiddenCopies(if: isShared, of: &d) { d in
|
||||
let item = fixture.items[i]
|
||||
let key = tracker.instance(for: item.key)
|
||||
let value = tracker.instance(for: item.value)
|
||||
let item = fixture.itemsInInsertionOrder[i]
|
||||
let key = tracker.instance(for: item)
|
||||
let value = tracker.instance(for: 1000 + item.identity)
|
||||
d[key] = value
|
||||
ref[key] = value
|
||||
expectEqualDictionaries(d, ref)
|
||||
@@ -607,7 +867,7 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
|
||||
func test_subscript_modify_update_fixtures() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("offset", in: 0 ..< fixture.items.count) { offset in
|
||||
withEvery("offset", in: 0 ..< fixture.count) { offset in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withLifetimeTracking { tracker in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
@@ -629,7 +889,7 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
|
||||
func test_subscript_modify_in_place() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("offset", in: 0 ..< fixture.items.count) { offset in
|
||||
withEvery("offset", in: 0 ..< fixture.count) { offset in
|
||||
withLifetimeTracking { tracker in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
let key = ref[offset].key
|
||||
@@ -646,7 +906,7 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
|
||||
func test_subscript_modify_remove_fixtures() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("offset", in: 0 ..< fixture.items.count) { offset in
|
||||
withEvery("offset", in: 0 ..< fixture.count) { offset in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withLifetimeTracking { tracker in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
@@ -721,11 +981,11 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
withLifetimeTracking { tracker in
|
||||
var d: PersistentDictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Int>> = [:]
|
||||
var ref: Dictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Int>> = [:]
|
||||
withEvery("i", in: 0 ..< fixture.items.count) { i in
|
||||
withEvery("i", in: 0 ..< fixture.count) { i in
|
||||
withHiddenCopies(if: isShared, of: &d) { d in
|
||||
let item = fixture.items[i]
|
||||
let key = tracker.instance(for: item.key)
|
||||
let value = tracker.instance(for: item.value)
|
||||
let item = fixture.itemsInInsertionOrder[i]
|
||||
let key = tracker.instance(for: item)
|
||||
let value = tracker.instance(for: 1000 + item.identity)
|
||||
mutate(&d[key]) { v in
|
||||
expectNil(v)
|
||||
v = value
|
||||
@@ -825,7 +1085,7 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
|
||||
func test_defaulted_subscript_setter_update_fixtures() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("offset", in: 0 ..< fixture.items.count) { offset in
|
||||
withEvery("offset", in: 0 ..< fixture.count) { offset in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withLifetimeTracking { tracker in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
@@ -879,11 +1139,11 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
var d: PersistentDictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Int>> = [:]
|
||||
var ref: Dictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Int>> = [:]
|
||||
let def = tracker.instance(for: -1000)
|
||||
withEvery("i", in: 0 ..< fixture.items.count) { i in
|
||||
withEvery("i", in: 0 ..< fixture.count) { i in
|
||||
withHiddenCopies(if: isShared, of: &d) { d in
|
||||
let item = fixture.items[i]
|
||||
let key = tracker.instance(for: item.key)
|
||||
let value = tracker.instance(for: item.value)
|
||||
let item = fixture.itemsInInsertionOrder[i]
|
||||
let key = tracker.instance(for: item)
|
||||
let value = tracker.instance(for: 1000 + item.identity)
|
||||
d[key, default: def] = value
|
||||
ref[key] = value
|
||||
expectEqualDictionaries(d, ref)
|
||||
@@ -926,7 +1186,7 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
|
||||
func test_defaulted_subscript_modify_update_fixtures() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("offset", in: 0 ..< fixture.items.count) { offset in
|
||||
withEvery("offset", in: 0 ..< fixture.count) { offset in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withLifetimeTracking { tracker in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
@@ -949,7 +1209,7 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
|
||||
func test_defaulted_subscript_modify_in_place() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("offset", in: 0 ..< fixture.items.count) { offset in
|
||||
withEvery("offset", in: 0 ..< fixture.count) { offset in
|
||||
withLifetimeTracking { tracker in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
let key = ref[offset].key
|
||||
@@ -972,7 +1232,6 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
let values = tracker.instances(
|
||||
for: (0 ..< count).map { generator.value(for: $0) })
|
||||
let def = tracker.instance(for: generator.value(for: -1000))
|
||||
print(def)
|
||||
var d: PersistentDictionary<LifetimeTracked<G.Key>, LifetimeTracked<G.Value>> = [:]
|
||||
var ref: Dictionary<LifetimeTracked<G.Key>, LifetimeTracked<G.Value>> = [:]
|
||||
withEvery("offset", in: 0 ..< count) { offset in
|
||||
@@ -981,6 +1240,7 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
expectEqual(value, def)
|
||||
value = values[offset]
|
||||
}
|
||||
d._invariantCheck()
|
||||
ref[keys[offset]] = values[offset]
|
||||
expectEqualDictionaries(d, ref)
|
||||
}
|
||||
@@ -1002,11 +1262,11 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
var d: PersistentDictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Int>> = [:]
|
||||
var ref: Dictionary<LifetimeTracked<RawCollider>, LifetimeTracked<Int>> = [:]
|
||||
let def = tracker.instance(for: -1)
|
||||
withEvery("i", in: 0 ..< fixture.items.count) { i in
|
||||
withEvery("i", in: 0 ..< fixture.count) { i in
|
||||
withHiddenCopies(if: isShared, of: &d) { d in
|
||||
let item = fixture.items[i]
|
||||
let key = tracker.instance(for: item.key)
|
||||
let value = tracker.instance(for: item.value)
|
||||
let item = fixture.itemsInInsertionOrder[i]
|
||||
let key = tracker.instance(for: item)
|
||||
let value = tracker.instance(for: 1000 + item.identity)
|
||||
mutate(&d[key, default: def]) { v in
|
||||
expectEqual(v, def)
|
||||
v = value
|
||||
@@ -1141,7 +1401,6 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
typealias Value2 = LifetimeTracked<String>
|
||||
|
||||
withEachFixture { fixture in
|
||||
print(fixture.title, fixture.items)
|
||||
withLifetimeTracking { tracker in
|
||||
func transform(_ value: Value) -> Value2? {
|
||||
guard value.payload.isMultiple(of: 2) else { return nil }
|
||||
@@ -1182,18 +1441,17 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
})
|
||||
}
|
||||
|
||||
func test_filter_fixtures() {
|
||||
func test_filter_fixtures_evens() {
|
||||
typealias Key = LifetimeTracked<RawCollider>
|
||||
typealias Value = LifetimeTracked<Int>
|
||||
|
||||
withEachFixture { fixture in
|
||||
print(fixture.title, fixture.items)
|
||||
withLifetimeTracking { tracker in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
withHiddenCopies(if: isShared, of: &d) { d in
|
||||
func predicate(_ item: (key: Key, value: Value)) -> Bool {
|
||||
expectEqual(item.value.payload, 100 + item.key.payload.identity)
|
||||
expectEqual(item.value.payload, 1000 + item.key.payload.identity)
|
||||
return item.value.payload.isMultiple(of: 2)
|
||||
}
|
||||
let d2 = d.filter(predicate)
|
||||
@@ -1206,6 +1464,80 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func test_filter_fixtures_filter_one() {
|
||||
typealias Key = LifetimeTracked<RawCollider>
|
||||
typealias Value = LifetimeTracked<Int>
|
||||
|
||||
withEachFixture { fixture in
|
||||
withLifetimeTracking { tracker in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withEvery("i", in: 0 ..< fixture.count) { i in
|
||||
var (d, ref) = tracker.persistentDictionary(for: fixture)
|
||||
withHiddenCopies(if: isShared, of: &d) { d in
|
||||
func predicate(_ item: (key: Key, value: Value)) -> Bool {
|
||||
expectEqual(item.value.payload, 1000 + item.key.payload.identity)
|
||||
return item.key.payload.identity == i
|
||||
}
|
||||
let d2 = d.filter(predicate)
|
||||
let ref2 = Dictionary(
|
||||
uniqueKeysWithValues: ref.filter(predicate))
|
||||
expectEqualDictionaries(d2, ref2)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_filter_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentDictionary(
|
||||
uniqueKeysWithValues: a.lazy.map {
|
||||
($0, $0.identity + 100)
|
||||
})
|
||||
withEverySubset("b", of: a) { b in
|
||||
let y = Dictionary(
|
||||
uniqueKeysWithValues: b.lazy.map {
|
||||
($0, $0.identity + 100)
|
||||
})
|
||||
expectEqualDictionaries(x.filter { y[$0.key] == $0.value }, y)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_merge_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
withEverySubset("b", of: testItems) { b in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withLifetimeTracking { tracker in
|
||||
func combine(
|
||||
_ a: LifetimeTracked<Int>, _ b: LifetimeTracked<Int>
|
||||
) -> LifetimeTracked<Int> {
|
||||
expectEqual(b.payload, a.payload + 100)
|
||||
return tracker.instance(for: 100 - a.payload)
|
||||
}
|
||||
var expected1 = tracker.dictionary(
|
||||
for: a, by: { $0.identity + 100 })
|
||||
let expected2 = tracker.dictionary(
|
||||
for: b, by: { $0.identity + 200 })
|
||||
|
||||
var actual1 = tracker.persistentDictionary(
|
||||
for: a, by: { $0.identity + 100 })
|
||||
let actual2 = tracker.persistentDictionary(
|
||||
for: b, by: { $0.identity + 200 })
|
||||
|
||||
expected1.merge(expected2, uniquingKeysWith: combine)
|
||||
|
||||
withHiddenCopies(if: isShared, of: &expected1) { expected1 in
|
||||
actual1.merge(actual2, uniquingKeysWith: combine)
|
||||
expectEqualDictionaries(actual1, expected1)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// MARK: -
|
||||
|
||||
@@ -2088,279 +2420,6 @@ class PersistentDictionaryTests: CollectionTestCase {
|
||||
// })
|
||||
// }
|
||||
|
||||
func test_CustomStringConvertible() {
|
||||
let a: PersistentDictionary<RawCollider, Int> = [:]
|
||||
expectEqual(a.description, "[:]")
|
||||
|
||||
let b: PersistentDictionary<RawCollider, Int> = [
|
||||
RawCollider(0): 1
|
||||
]
|
||||
expectEqual(b.description, "[0: 1]")
|
||||
|
||||
let c: PersistentDictionary<RawCollider, Int> = [
|
||||
RawCollider(0): 1,
|
||||
RawCollider(2): 3,
|
||||
RawCollider(4): 5,
|
||||
]
|
||||
expectEqual(c.description, "[0: 1, 2: 3, 4: 5]")
|
||||
}
|
||||
|
||||
// func test_CustomDebugStringConvertible() {
|
||||
// let a: PersistentDictionary<Int, Int> = [:]
|
||||
// expectEqual(a.debugDescription,
|
||||
// "PersistentDictionary<Int, Int>([:])")
|
||||
//
|
||||
// let b: PersistentDictionary<Int, Int> = [0: 1]
|
||||
// expectEqual(b.debugDescription,
|
||||
// "PersistentDictionary<Int, Int>([0: 1])")
|
||||
//
|
||||
// let c: PersistentDictionary<Int, Int> = [0: 1, 2: 3, 4: 5]
|
||||
// expectEqual(c.debugDescription,
|
||||
// "PersistentDictionary<Int, Int>([0: 1, 2: 3, 4: 5])")
|
||||
// }
|
||||
|
||||
// func test_customReflectable() {
|
||||
// do {
|
||||
// let d: PersistentDictionary<Int, Int> = [1: 2, 3: 4, 5: 6]
|
||||
// let mirror = Mirror(reflecting: d)
|
||||
// expectEqual(mirror.displayStyle, .dictionary)
|
||||
// expectNil(mirror.superclassMirror)
|
||||
// expectTrue(mirror.children.compactMap { $0.label }.isEmpty) // No label
|
||||
// expectEqualElements(
|
||||
// mirror.children.compactMap { $0.value as? (key: Int, value: Int) },
|
||||
// d.map { $0 })
|
||||
// }
|
||||
// }
|
||||
|
||||
func test_Equatable_Hashable() {
|
||||
let samples: [[PersistentDictionary<Int, Int>]] = [
|
||||
[[:], [:]],
|
||||
[[1: 100], [1: 100]],
|
||||
[[2: 200], [2: 200]],
|
||||
[[3: 300], [3: 300]],
|
||||
[[100: 1], [100: 1]],
|
||||
[[1: 1], [1: 1]],
|
||||
[[100: 100], [100: 100]],
|
||||
[[1: 100, 2: 200], [2: 200, 1: 100]],
|
||||
[[1: 100, 2: 200, 3: 300],
|
||||
[1: 100, 3: 300, 2: 200],
|
||||
[2: 200, 1: 100, 3: 300],
|
||||
[2: 200, 3: 300, 1: 100],
|
||||
[3: 300, 1: 100, 2: 200],
|
||||
[3: 300, 2: 200, 1: 100]]
|
||||
]
|
||||
checkHashable(equivalenceClasses: samples)
|
||||
}
|
||||
|
||||
// func test_Encodable() throws {
|
||||
// let d1: PersistentDictionary<Int, Int> = [:]
|
||||
// let v1: MinimalEncoder.Value = .array([])
|
||||
// expectEqual(try MinimalEncoder.encode(d1), v1)
|
||||
//
|
||||
// let d2: PersistentDictionary<Int, Int> = [0: 1]
|
||||
// let v2: MinimalEncoder.Value = .array([.int(0), .int(1)])
|
||||
// expectEqual(try MinimalEncoder.encode(d2), v2)
|
||||
//
|
||||
// let d3: PersistentDictionary<Int, Int> = [0: 1, 2: 3]
|
||||
// let v3: MinimalEncoder.Value =
|
||||
// .array([.int(0), .int(1), .int(2), .int(3)])
|
||||
// expectEqual(try MinimalEncoder.encode(d3), v3)
|
||||
//
|
||||
// let d4 = PersistentDictionary(
|
||||
// uniqueKeys: 0 ..< 100,
|
||||
// values: (0 ..< 100).map { 100 * $0 })
|
||||
// let v4: MinimalEncoder.Value =
|
||||
// .array((0 ..< 100).flatMap { [.int($0), .int(100 * $0)] })
|
||||
// expectEqual(try MinimalEncoder.encode(d4), v4)
|
||||
// }
|
||||
|
||||
// func test_Decodable() throws {
|
||||
// typealias OD = PersistentDictionary<Int, Int>
|
||||
// let d1: OD = [:]
|
||||
// let v1: MinimalEncoder.Value = .array([])
|
||||
// expectEqual(try MinimalDecoder.decode(v1, as: OD.self), d1)
|
||||
//
|
||||
// let d2: OD = [0: 1]
|
||||
// let v2: MinimalEncoder.Value = .array([.int(0), .int(1)])
|
||||
// expectEqual(try MinimalDecoder.decode(v2, as: OD.self), d2)
|
||||
//
|
||||
// let d3: OD = [0: 1, 2: 3]
|
||||
// let v3: MinimalEncoder.Value =
|
||||
// .array([.int(0), .int(1), .int(2), .int(3)])
|
||||
// expectEqual(try MinimalDecoder.decode(v3, as: OD.self), d3)
|
||||
//
|
||||
// let d4 = PersistentDictionary(
|
||||
// uniqueKeys: 0 ..< 100,
|
||||
// values: (0 ..< 100).map { 100 * $0 })
|
||||
// let v4: MinimalEncoder.Value =
|
||||
// .array((0 ..< 100).flatMap { [.int($0), .int(100 * $0)] })
|
||||
// expectEqual(try MinimalDecoder.decode(v4, as: OD.self), d4)
|
||||
//
|
||||
// let v5: MinimalEncoder.Value = .array([.int(0), .int(1), .int(2)])
|
||||
// expectThrows(try MinimalDecoder.decode(v5, as: OD.self)) { error in
|
||||
// guard case DecodingError.dataCorrupted(let context) = error else {
|
||||
// expectFailure("Unexpected error \(error)")
|
||||
// return
|
||||
// }
|
||||
// expectEqual(context.debugDescription,
|
||||
// "Unkeyed container reached end before value in key-value pair")
|
||||
//
|
||||
// }
|
||||
//
|
||||
// let v6: MinimalEncoder.Value = .array([.int(0), .int(1), .int(0), .int(2)])
|
||||
// expectThrows(try MinimalDecoder.decode(v6, as: OD.self)) { error in
|
||||
// guard case DecodingError.dataCorrupted(let context) = error else {
|
||||
// expectFailure("Unexpected error \(error)")
|
||||
// return
|
||||
// }
|
||||
// expectEqual(context.debugDescription, "Duplicate key at offset 2")
|
||||
// }
|
||||
// }
|
||||
|
||||
// func test_swapAt() {
|
||||
// withEvery("count", in: 0 ..< 20) { count in
|
||||
// withEvery("i", in: 0 ..< count) { i in
|
||||
// withEvery("j", in: 0 ..< count) { j in
|
||||
// withEvery("isShared", in: [false, true]) { isShared in
|
||||
// withLifetimeTracking { tracker in
|
||||
// var (d, keys, values) = tracker.persistentDictionary(keys: 0 ..< count)
|
||||
// keys.swapAt(i, j)
|
||||
// values.swapAt(i, j)
|
||||
// withHiddenCopies(if: isShared, of: &d) { d in
|
||||
// d.swapAt(i, j)
|
||||
// expectEqualElements(d.values, values)
|
||||
// expectEqual(d[keys[i]], values[i])
|
||||
// expectEqual(d[keys[j]], values[j])
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// func test_partition() {
|
||||
// withEvery("seed", in: 0 ..< 10) { seed in
|
||||
// withEvery("count", in: 0 ..< 30) { count in
|
||||
// withEvery("isShared", in: [false, true]) { isShared in
|
||||
// withLifetimeTracking { tracker in
|
||||
// var rng = RepeatableRandomNumberGenerator(seed: seed)
|
||||
// var (d, keys, values) = tracker.persistentDictionary(
|
||||
// keys: (0 ..< count).shuffled(using: &rng))
|
||||
// var items = Array(zip(keys, values))
|
||||
// let expectedPivot = items.partition { $0.0.payload < count / 2 }
|
||||
// withHiddenCopies(if: isShared, of: &d) { d in
|
||||
// let actualPivot = d.partition { $0.key.payload < count / 2 }
|
||||
// expectEqual(actualPivot, expectedPivot)
|
||||
// expectEqualElements(d, items)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// func test_sort() {
|
||||
// withEvery("seed", in: 0 ..< 10) { seed in
|
||||
// withEvery("count", in: 0 ..< 30) { count in
|
||||
// withEvery("isShared", in: [false, true]) { isShared in
|
||||
// withLifetimeTracking { tracker in
|
||||
// var rng = RepeatableRandomNumberGenerator(seed: seed)
|
||||
// var (d, keys, values) = tracker.persistentDictionary(
|
||||
// keys: (0 ..< count).shuffled(using: &rng))
|
||||
// var items = Array(zip(keys, values))
|
||||
// items.sort(by: { $0.0 < $1.0 })
|
||||
// withHiddenCopies(if: isShared, of: &d) { d in
|
||||
// d.sort()
|
||||
// expectEqualElements(d, items)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// func test_sort_by() {
|
||||
// withEvery("seed", in: 0 ..< 10) { seed in
|
||||
// withEvery("count", in: 0 ..< 30) { count in
|
||||
// withEvery("isShared", in: [false, true]) { isShared in
|
||||
// withLifetimeTracking { tracker in
|
||||
// var rng = RepeatableRandomNumberGenerator(seed: seed)
|
||||
// var (d, keys, values) = tracker.persistentDictionary(
|
||||
// keys: (0 ..< count).shuffled(using: &rng))
|
||||
// var items = Array(zip(keys, values))
|
||||
// items.sort(by: { $0.0 > $1.0 })
|
||||
// withHiddenCopies(if: isShared, of: &d) { d in
|
||||
// d.sort(by: { $0.key > $1.key })
|
||||
// expectEqualElements(d, items)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// func test_shuffle() {
|
||||
// withEvery("count", in: 0 ..< 30) { count in
|
||||
// withEvery("isShared", in: [false, true]) { isShared in
|
||||
// withEvery("seed", in: 0 ..< 10) { seed in
|
||||
// var d = PersistentDictionary(
|
||||
// uniqueKeys: 0 ..< count,
|
||||
// values: 100 ..< 100 + count)
|
||||
// var items = (0 ..< count).map { (key: $0, value: 100 + $0) }
|
||||
// withHiddenCopies(if: isShared, of: &d) { d in
|
||||
// expectEqualElements(d, items)
|
||||
//
|
||||
// var rng1 = RepeatableRandomNumberGenerator(seed: seed)
|
||||
// items.shuffle(using: &rng1)
|
||||
//
|
||||
// var rng2 = RepeatableRandomNumberGenerator(seed: seed)
|
||||
// d.shuffle(using: &rng2)
|
||||
//
|
||||
// items.sort(by: { $0.key < $1.key })
|
||||
// d.sort()
|
||||
// expectEqualElements(d, items)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// if count >= 2 {
|
||||
// // Check that shuffling with the system RNG does permute the elements.
|
||||
// var d = PersistentDictionary(
|
||||
// uniqueKeys: 0 ..< count,
|
||||
// values: 100 ..< 100 + count)
|
||||
// let original = d
|
||||
// var success = false
|
||||
// for _ in 0 ..< 1000 {
|
||||
// d.shuffle()
|
||||
// if !d.elementsEqual(
|
||||
// original,
|
||||
// by: { $0.key == $1.key && $0.value == $1.value}
|
||||
// ) {
|
||||
// success = true
|
||||
// break
|
||||
// }
|
||||
// }
|
||||
// expectTrue(success)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// func test_reverse() {
|
||||
// withEvery("count", in: 0 ..< 30) { count in
|
||||
// withEvery("isShared", in: [false, true]) { isShared in
|
||||
// withLifetimeTracking { tracker in
|
||||
// var (d, keys, values) = tracker.persistentDictionary(keys: 0 ..< count)
|
||||
// var items = Array(zip(keys, values))
|
||||
// withHiddenCopies(if: isShared, of: &d) { d in
|
||||
// items.reverse()
|
||||
// d.reverse()
|
||||
// expectEqualElements(d, items)
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
|
||||
// func test_removeAll() {
|
||||
// withEvery("count", in: 0 ..< 30) { count in
|
||||
// withEvery("isShared", in: [false, true]) { isShared in
|
||||
|
||||
@@ -0,0 +1,337 @@
|
||||
//===----------------------------------------------------------------------===//
|
||||
//
|
||||
// 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 _CollectionsTestSupport
|
||||
import PersistentCollections
|
||||
|
||||
class PersistentSetTests: CollectionTestCase {
|
||||
func test_init_empty() {
|
||||
let set = PersistentSet<Int>()
|
||||
expectEqual(set.count, 0)
|
||||
expectTrue(set.isEmpty)
|
||||
expectEqualElements(set, [])
|
||||
}
|
||||
|
||||
func test_BidirectionalCollection_fixtures() {
|
||||
withEachFixture { fixture in
|
||||
withLifetimeTracking { tracker in
|
||||
let (set, ref) = tracker.persistentSet(for: fixture)
|
||||
checkBidirectionalCollection(set, expectedContents: ref, by: ==)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_BidirectionalCollection_random100() {
|
||||
let s = PersistentSet<Int>(0 ..< 100)
|
||||
checkBidirectionalCollection(s, expectedContents: Array(s))
|
||||
}
|
||||
|
||||
func test_basics() {
|
||||
var set: PersistentSet<HashableBox<Int>> = []
|
||||
|
||||
let a1 = HashableBox(1)
|
||||
let a2 = HashableBox(1)
|
||||
|
||||
var r = set.insert(a1)
|
||||
expectTrue(r.inserted)
|
||||
expectIdentical(r.memberAfterInsert, a1)
|
||||
expectIdentical(set.first, a1)
|
||||
expectTrue(set.contains(a1))
|
||||
expectTrue(set.contains(a2))
|
||||
|
||||
r = set.insert(a2)
|
||||
expectFalse(r.inserted)
|
||||
expectIdentical(r.memberAfterInsert, a1)
|
||||
expectIdentical(set.first, a1)
|
||||
expectTrue(set.contains(a1))
|
||||
expectTrue(set.contains(a2))
|
||||
|
||||
var old = set.update(with: a2)
|
||||
expectIdentical(old, a1)
|
||||
expectIdentical(set.first, a2)
|
||||
expectTrue(set.contains(a1))
|
||||
expectTrue(set.contains(a2))
|
||||
|
||||
old = set.remove(a1)
|
||||
expectIdentical(old, a2)
|
||||
expectNil(set.first)
|
||||
expectFalse(set.contains(a1))
|
||||
expectFalse(set.contains(a2))
|
||||
|
||||
old = set.update(with: a1)
|
||||
expectNil(old)
|
||||
expectIdentical(set.first, a1)
|
||||
expectTrue(set.contains(a1))
|
||||
expectTrue(set.contains(a2))
|
||||
}
|
||||
|
||||
func test_insert_fixtures() {
|
||||
withEachFixture { fixture in
|
||||
withEvery("isShared", in: [false, true]) { isShared in
|
||||
withLifetimeTracking { tracker in
|
||||
var s: PersistentSet<LifetimeTracked<RawCollider>> = []
|
||||
var ref: Set<LifetimeTracked<RawCollider>> = []
|
||||
withEvery("i", in: 0 ..< fixture.count) { i in
|
||||
withHiddenCopies(if: isShared, of: &s) { s in
|
||||
let item = fixture.itemsInInsertionOrder[i]
|
||||
let key1 = tracker.instance(for: item)
|
||||
let r = s.insert(key1)
|
||||
expectTrue(r.inserted)
|
||||
expectEqual(r.memberAfterInsert, key1)
|
||||
|
||||
let key2 = tracker.instance(for: item)
|
||||
ref.insert(key2)
|
||||
expectEqualSets(s, ref)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_intersection_Self_basics() {
|
||||
let a = RawCollider(1, "A")
|
||||
let b = RawCollider(2, "B")
|
||||
let c = RawCollider(3, "C")
|
||||
|
||||
let s0: PersistentSet<RawCollider> = []
|
||||
let s1: PersistentSet = [a, b]
|
||||
let s2: PersistentSet = [a, c]
|
||||
|
||||
expectEqualSets(s0.intersection(s0), [])
|
||||
expectEqualSets(s1.intersection(s0), [])
|
||||
expectEqualSets(s0.intersection(s1), [])
|
||||
|
||||
expectEqualSets(s1.intersection(s1), [a, b])
|
||||
expectEqualSets(s1.intersection(s2), [a])
|
||||
expectEqualSets(s2.intersection(s1), [a])
|
||||
|
||||
let ab = RawCollider(4, "AB")
|
||||
let ac = RawCollider(5, "AC")
|
||||
let s3: PersistentSet = [ab, ac]
|
||||
let s4: PersistentSet = [a, ab]
|
||||
expectEqualSets(s1.intersection(s3), [])
|
||||
expectEqualSets(s2.intersection(s3), [])
|
||||
expectEqualSets(s1.intersection(s4), [a])
|
||||
expectEqualSets(s2.intersection(s4), [a])
|
||||
expectEqualSets(s3.intersection(s1), [])
|
||||
expectEqualSets(s3.intersection(s2), [])
|
||||
expectEqualSets(s4.intersection(s1), [a])
|
||||
expectEqualSets(s4.intersection(s2), [a])
|
||||
|
||||
let ad = RawCollider(6, "AD")
|
||||
let ae = RawCollider(7, "AE")
|
||||
let s5: PersistentSet = [a, ab, ad, ae]
|
||||
expectEqualSets(s1.intersection(s5), [a])
|
||||
expectEqualSets(s2.intersection(s5), [a])
|
||||
expectEqualSets(s3.intersection(s5), [ab])
|
||||
expectEqualSets(s4.intersection(s5), [a, ab])
|
||||
|
||||
expectEqualSets(s5.intersection(s1), [a])
|
||||
expectEqualSets(s5.intersection(s2), [a])
|
||||
expectEqualSets(s5.intersection(s3), [ab])
|
||||
expectEqualSets(s5.intersection(s4), [a, ab])
|
||||
|
||||
let af1 = RawCollider(8, "AF")
|
||||
let af2 = RawCollider(9, "AF")
|
||||
let s6: PersistentSet = [af1, af2]
|
||||
expectEqualSets(s1.intersection(s6), [])
|
||||
expectEqualSets(s2.intersection(s6), [])
|
||||
expectEqualSets(s3.intersection(s6), [])
|
||||
expectEqualSets(s4.intersection(s6), [])
|
||||
expectEqualSets(s5.intersection(s6), [])
|
||||
|
||||
expectEqualSets(s6.intersection(s1), [])
|
||||
expectEqualSets(s6.intersection(s2), [])
|
||||
expectEqualSets(s6.intersection(s3), [])
|
||||
expectEqualSets(s6.intersection(s4), [])
|
||||
expectEqualSets(s6.intersection(s5), [])
|
||||
|
||||
let af3 = RawCollider(10, "AF")
|
||||
let s7: PersistentSet = [af1, af3]
|
||||
expectEqualSets(s1.intersection(s7), [])
|
||||
expectEqualSets(s2.intersection(s7), [])
|
||||
expectEqualSets(s3.intersection(s7), [])
|
||||
expectEqualSets(s4.intersection(s7), [])
|
||||
expectEqualSets(s5.intersection(s7), [])
|
||||
expectEqualSets(s6.intersection(s7), [af1])
|
||||
|
||||
expectEqualSets(s7.intersection(s1), [])
|
||||
expectEqualSets(s7.intersection(s2), [])
|
||||
expectEqualSets(s7.intersection(s3), [])
|
||||
expectEqualSets(s7.intersection(s4), [])
|
||||
expectEqualSets(s7.intersection(s5), [])
|
||||
expectEqualSets(s7.intersection(s6), [af1])
|
||||
|
||||
let s8: PersistentSet = [a, af1]
|
||||
expectEqualSets(s1.intersection(s8), [a])
|
||||
expectEqualSets(s2.intersection(s8), [a])
|
||||
expectEqualSets(s3.intersection(s8), [])
|
||||
expectEqualSets(s4.intersection(s8), [a])
|
||||
expectEqualSets(s5.intersection(s8), [a])
|
||||
expectEqualSets(s6.intersection(s8), [af1])
|
||||
expectEqualSets(s7.intersection(s8), [af1])
|
||||
|
||||
expectEqualSets(s8.intersection(s1), [a])
|
||||
expectEqualSets(s8.intersection(s2), [a])
|
||||
expectEqualSets(s8.intersection(s3), [])
|
||||
expectEqualSets(s8.intersection(s4), [a])
|
||||
expectEqualSets(s8.intersection(s5), [a])
|
||||
expectEqualSets(s8.intersection(s6), [af1])
|
||||
expectEqualSets(s8.intersection(s7), [af1])
|
||||
|
||||
let afa1 = RawCollider(11, "AFA")
|
||||
let afa2 = RawCollider(12, "AFA")
|
||||
let s9: PersistentSet = [afa1, afa2]
|
||||
expectEqualSets(s9.intersection(s6), [])
|
||||
expectEqualSets(s6.intersection(s9), [])
|
||||
}
|
||||
|
||||
func test_isEqual_Self_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentSet(a)
|
||||
let u = Set(a)
|
||||
expectTrue(x.isEqual(to: x))
|
||||
withEverySubset("b", of: testItems) { b in
|
||||
let y = PersistentSet(b)
|
||||
let v = Set(b)
|
||||
expectEqual(x.isEqual(to: y), u == v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_isSubset_Self_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentSet(a)
|
||||
let u = Set(a)
|
||||
expectTrue(x.isSubset(of: x))
|
||||
withEverySubset("b", of: testItems) { b in
|
||||
let y = PersistentSet(b)
|
||||
let v = Set(b)
|
||||
expectEqual(x.isSubset(of: y), u.isSubset(of: v))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_isSuperset_Self_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentSet(a)
|
||||
let u = Set(a)
|
||||
expectTrue(x.isSuperset(of: x))
|
||||
withEverySubset("b", of: testItems) { b in
|
||||
let y = PersistentSet(b)
|
||||
let v = Set(b)
|
||||
expectEqual(x.isSuperset(of: y), u.isSuperset(of: v))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_isStrictsubset_Self_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentSet(a)
|
||||
let u = Set(a)
|
||||
expectFalse(x.isStrictSubset(of: x))
|
||||
withEverySubset("b", of: testItems) { b in
|
||||
let y = PersistentSet(b)
|
||||
let v = Set(b)
|
||||
expectEqual(x.isStrictSubset(of: y), u.isStrictSubset(of: v))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_isStrictSuperset_Self_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentSet(a)
|
||||
let u = Set(a)
|
||||
expectFalse(x.isStrictSuperset(of: x))
|
||||
withEverySubset("b", of: testItems) { b in
|
||||
let y = PersistentSet(b)
|
||||
let v = Set(b)
|
||||
expectEqual(x.isStrictSuperset(of: y), u.isStrictSuperset(of: v))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_isDisjoint_Self_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentSet(a)
|
||||
let u = Set(a)
|
||||
expectEqual(x.isDisjoint(with: x), x.isEmpty)
|
||||
withEverySubset("b", of: testItems) { b in
|
||||
let y = PersistentSet(b)
|
||||
let v = Set(b)
|
||||
expectEqual(x.isDisjoint(with: y), u.isDisjoint(with: v))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_intersection_Self_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentSet(a)
|
||||
let u = Set(a)
|
||||
expectEqualSets(x.intersection(x), u)
|
||||
withEverySubset("b", of: testItems) { b in
|
||||
let y = PersistentSet(b)
|
||||
let v = Set(b)
|
||||
expectEqualSets(x.intersection(y), u.intersection(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_subtracting_Self_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentSet(a)
|
||||
let u = Set(a)
|
||||
expectEqualSets(x.subtracting(x), [])
|
||||
withEverySubset("b", of: testItems) { b in
|
||||
let y = PersistentSet(b)
|
||||
let v = Set(b)
|
||||
expectEqualSets(x.subtracting(y), u.subtracting(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_filter_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentSet(a)
|
||||
withEverySubset("b", of: a) { b in
|
||||
let v = Set(b)
|
||||
expectEqualSets(x.filter { v.contains($0) }, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_union_Self_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentSet(a)
|
||||
let u = Set(a)
|
||||
expectEqualSets(x.union(x), u)
|
||||
withEverySubset("b", of: testItems) { b in
|
||||
let y = PersistentSet(b)
|
||||
let v = Set(b)
|
||||
expectEqualSets(x.union(y), u.union(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_symmetricDifference_Self_exhaustive() {
|
||||
withEverySubset("a", of: testItems) { a in
|
||||
let x = PersistentSet(a)
|
||||
let u = Set(a)
|
||||
expectEqualSets(x.symmetricDifference(x), [])
|
||||
withEverySubset("b", of: testItems) { b in
|
||||
let y = PersistentSet(b)
|
||||
let v = Set(b)
|
||||
expectEqualSets(x.symmetricDifference(y), u.symmetricDifference(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,6 +129,59 @@ func _expectFailure(
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
func expectEqualSets<Element: Hashable>(
|
||||
_ set: PersistentSet<Element>,
|
||||
_ ref: [Element],
|
||||
_ message: @autoclosure () -> String = "",
|
||||
trapping: Bool = false,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) {
|
||||
expectEqualSets(
|
||||
set, Set(ref),
|
||||
message(),
|
||||
trapping: trapping,
|
||||
file: file, line: line)
|
||||
}
|
||||
|
||||
func expectEqualSets<Element: Hashable>(
|
||||
_ set: PersistentSet<Element>,
|
||||
_ ref: Set<Element>,
|
||||
_ message: @autoclosure () -> String = "",
|
||||
trapping: Bool = false,
|
||||
file: StaticString = #file,
|
||||
line: UInt = #line
|
||||
) {
|
||||
var ref = ref
|
||||
var seen: Set<Element> = []
|
||||
var extras: [Element] = []
|
||||
var dupes: [Element: Int] = [:]
|
||||
for item in set {
|
||||
if !seen.insert(item).inserted {
|
||||
dupes[item, default: 1] += 1
|
||||
} else if ref.remove(item) == nil {
|
||||
extras.append(item)
|
||||
}
|
||||
}
|
||||
let missing = Array(ref)
|
||||
var msg = ""
|
||||
if !extras.isEmpty {
|
||||
msg += "\nUnexpected items: \(extras)"
|
||||
}
|
||||
if !missing.isEmpty {
|
||||
msg += "\nMissing items: \(missing)"
|
||||
}
|
||||
if !dupes.isEmpty {
|
||||
msg += "\nDuplicate items: \(dupes)"
|
||||
}
|
||||
if !msg.isEmpty {
|
||||
_expectFailure(
|
||||
"\n\(msg)",
|
||||
message, trapping: trapping, file: file, line: line)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func expectEqualDictionaries<Key: Hashable, Value: Equatable>(
|
||||
_ map: PersistentDictionary<Key, Value>,
|
||||
_ ref: [(key: Key, value: Value)],
|
||||
@@ -188,3 +241,30 @@ func mutate<T, R>(
|
||||
) rethrows -> R {
|
||||
try body(&value)
|
||||
}
|
||||
|
||||
func withEverySubset<C: Collection>(
|
||||
_ label: String,
|
||||
of items: C,
|
||||
body: ([C.Element]) -> Void
|
||||
) {
|
||||
var set: [C.Element] = []
|
||||
_withEverySubset(label, of: items, extending: &set, body: body)
|
||||
}
|
||||
|
||||
func _withEverySubset<C: Collection>(
|
||||
_ label: String,
|
||||
of items: C,
|
||||
extending set: inout [C.Element],
|
||||
body: ([C.Element]) -> Void
|
||||
) {
|
||||
guard let item = items.first else {
|
||||
let entry = TestContext.current.push("\(label): \(set)")
|
||||
defer { TestContext.current.pop(entry) }
|
||||
body(set)
|
||||
return
|
||||
}
|
||||
_withEverySubset(label, of: items.dropFirst(), extending: &set, body: body)
|
||||
set.append(item)
|
||||
_withEverySubset(label, of: items.dropFirst(), extending: &set, body: body)
|
||||
set.removeLast()
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1410"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "memory-benchmark"
|
||||
BuildableName = "memory-benchmark"
|
||||
BlueprintName = "memory-benchmark"
|
||||
ReferencedContainer = "container:../Benchmarks">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<Testables>
|
||||
</Testables>
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
useCustomWorkingDirectory = "NO"
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
allowLocationSimulation = "YES"
|
||||
viewDebuggingEnabled = "No">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "memory-benchmark"
|
||||
BuildableName = "memory-benchmark"
|
||||
BlueprintName = "memory-benchmark"
|
||||
ReferencedContainer = "container:../Benchmarks">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES"
|
||||
savedToolIdentifier = ""
|
||||
useCustomWorkingDirectory = "NO"
|
||||
debugDocumentVersioning = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "memory-benchmark"
|
||||
BuildableName = "memory-benchmark"
|
||||
BlueprintName = "memory-benchmark"
|
||||
ReferencedContainer = "container:../Benchmarks">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
<InstallAction
|
||||
buildConfiguration = "Release">
|
||||
</InstallAction>
|
||||
</Scheme>
|
||||
Reference in new issue
Block a user