diff --git a/Benchmarks/Sources/Benchmarks/PersistentDictionaryBenchmarks.swift b/Benchmarks/Sources/Benchmarks/PersistentDictionaryBenchmarks.swift index e05ee963..61cd1d21 100644 --- a/Benchmarks/Sources/Benchmarks/PersistentDictionaryBenchmarks.swift +++ b/Benchmarks/Sources/Benchmarks/PersistentDictionaryBenchmarks.swift @@ -382,5 +382,75 @@ extension Benchmark { blackHole(d) } } + + self.add( + title: "PersistentDictionary subscript, insert, unique", + input: [Large].self + ) { input in + return { timer in + var d: PersistentDictionary = [:] + timer.measure { + for value in input { + d[value] = value + } + } + precondition(d.count == input.count) + blackHole(d) + } + } + + self.add( + title: "PersistentDictionary subscript, insert, shared", + input: [Large].self + ) { input in + return { timer in + var d: PersistentDictionary = [:] + timer.measure { + for value in input { + let copy = d + d[value] = value + blackHole((copy, d)) + } + } + precondition(d.count == input.count) + blackHole(d) + } + } + + self.add( + title: "PersistentDictionary subscript, remove existing, unique", + input: ([Large], [Large]).self + ) { input, lookups in + return { timer in + var d = PersistentDictionary( + uniqueKeysWithValues: input.lazy.map { ($0, $0) }) + timer.measure { + for key in lookups { + d[key] = nil + } + } + precondition(d.isEmpty) + blackHole(d) + } + } + + self.add( + title: "PersistentDictionary subscript, remove existing, shared", + input: ([Large], [Large]).self + ) { input, lookups in + return { timer in + var d = PersistentDictionary( + uniqueKeysWithValues: input.lazy.map { ($0, $0) }) + timer.measure { + for key in lookups { + let copy = d + d[key] = nil + blackHole((copy, d)) + } + } + precondition(d.isEmpty) + blackHole(d) + } + } } } diff --git a/Benchmarks/Sources/benchmark-tool/main.swift b/Benchmarks/Sources/benchmark-tool/main.swift index 27494f96..51232829 100644 --- a/Benchmarks/Sources/benchmark-tool/main.swift +++ b/Benchmarks/Sources/benchmark-tool/main.swift @@ -11,8 +11,21 @@ import CollectionsBenchmark import Benchmarks +import DequeModule + +if Deque._isConsistencyCheckingEnabled { + complain(""" + *** INTERNAL CONSISTENCY CHECKING IS ENABLED *** + + Performance guarantees aren't valid in this configuration, + and benchmarking data will be largely useless. Proceed at + your own risk. + + """) +} var benchmark = Benchmark(title: "Collection Benchmarks") +benchmark.registerCustomGenerators() benchmark.addArrayBenchmarks() benchmark.addSetBenchmarks() benchmark.addDictionaryBenchmarks() diff --git a/Sources/DequeModule/Deque+Testing.swift b/Sources/DequeModule/Deque+Testing.swift index 00692981..b9dc6d9c 100644 --- a/Sources/DequeModule/Deque+Testing.swift +++ b/Sources/DequeModule/Deque+Testing.swift @@ -9,10 +9,16 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + // This file contains exported but non-public entry points to support clear box // testing. extension Deque { + public static var _isConsistencyCheckingEnabled: Bool { + _isCollectionsInternalCheckingEnabled + } + /// The maximum number of elements this deque is currently able to store /// without reallocating its storage buffer. /// diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift index edac2d8b..84443339 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift @@ -9,12 +9,18 @@ // //===----------------------------------------------------------------------===// +import _CollectionsUtilities + extension OrderedSet._UnstableInternals { @_spi(Testing) public var capacity: Int { base._capacity } @_spi(Testing) public var minimumCapacity: Int { base._minimumCapacity } @_spi(Testing) public var scale: Int { base._scale } @_spi(Testing) public var reservedScale: Int { base._reservedScale } @_spi(Testing) public var bias: Int { base._bias } + + public static var isConsistencyCheckingEnabled: Bool { + _isCollectionsInternalCheckingEnabled + } } extension OrderedSet { diff --git a/Sources/PersistentCollections/Node/_Node+CustomStringConvertible.swift b/Sources/PersistentCollections/Node/_Node+CustomStringConvertible.swift index dda52b37..36a62d27 100644 --- a/Sources/PersistentCollections/Node/_Node+CustomStringConvertible.swift +++ b/Sources/PersistentCollections/Node/_Node+CustomStringConvertible.swift @@ -27,7 +27,7 @@ extension _Node: CustomStringConvertible { } result += "\(key): \(value)" } - for child in $0._children { + for child in $0.children { if first { first = false } else { diff --git a/Sources/PersistentCollections/Node/_Node+Debugging.swift b/Sources/PersistentCollections/Node/_Node+Debugging.swift index 1cae50d4..e7821dba 100644 --- a/Sources/PersistentCollections/Node/_Node+Debugging.swift +++ b/Sources/PersistentCollections/Node/_Node+Debugging.swift @@ -73,10 +73,10 @@ extension _Node.UnsafeHandle { """) guard limit > 0 else { return } if iterationOrder { - for slot in stride(from: .zero, to: itemEnd, by: 1) { + for slot in stride(from: .zero, to: itemsEndSlot, by: 1) { print(" \(restPrefix)[\(slot)] \(_itemString(at: slot))") } - for slot in stride(from: .zero, to: childEnd, by: 1) { + for slot in stride(from: .zero, to: childrenEndSlot, by: 1) { self[child: slot].dump( iterationOrder: true, limit: limit - 1, @@ -86,7 +86,7 @@ extension _Node.UnsafeHandle { } } else if isCollisionNode { - for slot in stride(from: .zero, to: itemEnd, by: 1) { + for slot in stride(from: .zero, to: itemsEndSlot, by: 1) { print("\(restPrefix)[\(slot)] \(_itemString(at: slot))") } } else { diff --git a/Sources/PersistentCollections/Node/_Node+Equatable.swift b/Sources/PersistentCollections/Node/_Node+Equatable.swift index 083e40c6..6eca45d0 100644 --- a/Sources/PersistentCollections/Node/_Node+Equatable.swift +++ b/Sources/PersistentCollections/Node/_Node+Equatable.swift @@ -42,7 +42,7 @@ extension _Node: Equatable where Value: Equatable { guard l.reverseItems.elementsEqual(r.reverseItems, by: { $0 == $1 }) else { return false } - guard l._children.elementsEqual(r._children) else { return false } + guard l.children.elementsEqual(r.children) else { return false } return true } } diff --git a/Sources/PersistentCollections/Node/_Node+Initializers.swift b/Sources/PersistentCollections/Node/_Node+Initializers.swift index 32dc6cfd..0d8d99ea 100644 --- a/Sources/PersistentCollections/Node/_Node+Initializers.swift +++ b/Sources/PersistentCollections/Node/_Node+Initializers.swift @@ -15,8 +15,7 @@ extension _Node { _ item1: Element, _ inserter2: (UnsafeMutablePointer) -> Void ) -> _Node { - var node = _Node(collisionCapacity: 2) - node.count = 2 + var node = _Node(storage: Storage.allocate(itemCapacity: 2), count: 2) node.update { $0.collisionCount = 2 let byteCount = 2 * MemoryLayout.stride @@ -38,8 +37,7 @@ extension _Node { _ bucket2: _Bucket ) -> (node: _Node, slot1: _Slot, slot2: _Slot) { assert(bucket1 != bucket2) - var node = _Node(itemCapacity: 2) - node.count = 2 + var node = _Node(storage: Storage.allocate(itemCapacity: 2), count: 2) let (slot1, slot2) = node.update { $0.itemMap.insert(bucket1) $0.itemMap.insert(bucket2) @@ -59,8 +57,9 @@ extension _Node { internal static func _regularNode( _ child: _Node, _ bucket: _Bucket ) -> _Node { - var node = _Node(childCapacity: 1) - node.count = child.count + var node = _Node( + storage: Storage.allocate(childCapacity: 1), + count: child.count) node.update { $0.childMap.insert(bucket) $0.bytesFree &-= MemoryLayout<_Node>.stride @@ -78,8 +77,9 @@ extension _Node { _ childBucket: _Bucket ) -> _Node { assert(itemBucket != childBucket) - var node = _Node(itemCapacity: 1, childCapacity: 1) - node.count = child.count + 1 + var node = _Node( + storage: Storage.allocate(itemCapacity: 1, childCapacity: 1), + count: child.count &+ 1) node.update { $0.itemMap.insert(itemBucket) $0.childMap.insert(childBucket) diff --git a/Sources/PersistentCollections/Node/_Node+Invariants.swift b/Sources/PersistentCollections/Node/_Node+Invariants.swift index df0fc53b..dc829156 100644 --- a/Sources/PersistentCollections/Node/_Node+Invariants.swift +++ b/Sources/PersistentCollections/Node/_Node+Invariants.swift @@ -36,7 +36,7 @@ extension _Node { let itemBytes = $0.itemCount * MemoryLayout.stride let childBytes = $0.childCount * MemoryLayout<_Node>.stride assert(itemBytes + $0.bytesFree + childBytes == $0.byteCapacity) - let actualCount = $0._children.reduce($0.itemCount, { $0 + $1.count }) + let actualCount = $0.children.reduce($0.itemCount, { $0 + $1.count }) assert(actualCount == self.count) } } diff --git a/Sources/PersistentCollections/Node/_Node+Lookups.swift b/Sources/PersistentCollections/Node/_Node+Lookups.swift index 3ad13650..f74efda0 100644 --- a/Sources/PersistentCollections/Node/_Node+Lookups.swift +++ b/Sources/PersistentCollections/Node/_Node+Lookups.swift @@ -54,7 +54,7 @@ extension _Node.UnsafeHandle { } // Note: this searches the items in reverse insertion order. guard let slot = reverseItems.firstIndex(where: { $0.key == key }) - else { return (1, self.itemEnd, _Hash(_value: 0)) } + else { return (1, self.itemsEndSlot, _Hash(_value: 0)) } return (0, _Slot(itemCount &- 1 &- slot), _Hash(_value: 0)) } } @@ -142,7 +142,7 @@ extension _Node.UnsafeHandle { return .found(.invalid, r.slot) } if r.code == 1 { - return .notFound(.invalid, self.itemEnd) + return .notFound(.invalid, self.itemsEndSlot) } assert(r.code == 2) return .expansion(r.expansionHash) @@ -214,7 +214,7 @@ extension _Node { return nil case .descend(_, let slot): return read { h in - let children = h._children + let children = h.children let p = children[slot.value] .position(forKey: key, level.descend(), hash) guard let p = p else { return nil } @@ -234,7 +234,7 @@ extension _Node { return $0[item: _Slot(itemsToSkip)] } itemsToSkip -= itemCount - let children = $0._children + let children = $0.children for i in children.indices { if itemsToSkip < children[i].count { return children[i].item(position: itemsToSkip) diff --git a/Sources/PersistentCollections/Node/_Node+Mutations.swift b/Sources/PersistentCollections/Node/_Node+Mutations.swift deleted file mode 100644 index 3cbafc29..00000000 --- a/Sources/PersistentCollections/Node/_Node+Mutations.swift +++ /dev/null @@ -1,757 +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 -// -//===----------------------------------------------------------------------===// - -// MARK: Node-level mutation operations - -extension _Node.UnsafeHandle { - /// Make room for a new item at `slot` corresponding to `bucket`. - /// There must be enough free space in the node to fit the new item. - /// - /// `itemMap` must not already reflect the insertion at the time this - /// function is called. This method does not update `itemMap`. - /// - /// - Returns: an unsafe mutable pointer to uninitialized memory that is - /// ready to store the new item. It is the caller's responsibility to - /// initialize this memory. - @inlinable - internal func _makeRoomForNewItem( - at slot: _Slot, _ bucket: _Bucket - ) -> UnsafeMutablePointer { - assertMutable() - let c = itemCount - assert(slot.value <= c) - - let stride = MemoryLayout.stride - assert(bytesFree >= stride) - bytesFree &-= stride - - let start = _memory - .advanced(by: byteCapacity &- (c &+ 1) &* stride) - .bindMemory(to: Element.self, capacity: 1) - - let prefix = c &- slot.value - start.moveInitialize(from: start + 1, count: prefix) - - if bucket.isInvalid { - assert(isCollisionNode) - collisionCount &+= 1 - } else { - assert(!itemMap.contains(bucket)) - assert(!childMap.contains(bucket)) - itemMap.insert(bucket) - assert(itemMap.slot(of: bucket) == slot) - } - - return start + prefix - } - - /// Insert `child` at `slot`. There must be enough free space in the node - /// to fit the new child. - /// - /// `childMap` must not yet reflect the insertion at the time this - /// function is called. This method does not update `childMap`. - @inlinable - internal func _insertChild(_ child: __owned _Node, at slot: _Slot) { - assertMutable() - assert(!isCollisionNode) - - let c = childMap.count - assert(slot.value <= c) - - let stride = MemoryLayout<_Node>.stride - assert(bytesFree >= stride) - bytesFree &-= stride - - _memory.bindMemory(to: _Node.self, capacity: c &+ 1) - let q = _childrenStart + slot.value - (q + 1).moveInitialize(from: q, count: c &- slot.value) - q.initialize(to: child) - } - - /// Remove and return the item at `slot`, increasing the amount of free - /// space available in the node. - /// - /// `itemMap` must not yet reflect the removal at the time this - /// function is called. This method does not update `itemMap`. - @inlinable - internal func _removeItem( - at slot: _Slot, - by remover: (UnsafeMutablePointer) -> R - ) -> R { - assertMutable() - let c = itemCount - assert(slot.value < c) - let stride = MemoryLayout.stride - bytesFree &+= stride - - let start = _memory - .advanced(by: byteCapacity &- stride &* c) - .assumingMemoryBound(to: Element.self) - - let prefix = c &- 1 &- slot.value - let q = start + prefix - defer { - (start + 1).moveInitialize(from: start, count: prefix) - } - return remover(q) - } - - /// Remove and return the child at `slot`, increasing the amount of free - /// space available in the node. - /// - /// `childMap` must not yet reflect the removal at the time this - /// function is called. This method does not update `childMap`. - @inlinable - internal func _removeChild(at slot: _Slot) -> _Node { - assertMutable() - assert(!isCollisionNode) - let count = childCount - assert(slot.value < count) - - bytesFree &+= MemoryLayout<_Node>.stride - - let q = _childrenStart + slot.value - let child = q.move() - q.moveInitialize(from: q + 1, count: count &- 1 &- slot.value) - return child - } -} - -extension _Node { - @inlinable @inline(__always) - internal mutating func insertItem( - _ item: __owned Element, _ bucket: _Bucket - ) { - let slot = read { $0.itemMap.slot(of: bucket) } - self.insertItem(item, at: slot, bucket) - } - - @inlinable @inline(__always) - internal mutating func insertItem( - _ item: __owned Element, at slot: _Slot, _ bucket: _Bucket - ) { - self.count &+= 1 - update { - let p = $0._makeRoomForNewItem(at: slot, bucket) - p.initialize(to: item) - } - } - - /// Insert `child` in `bucket`. There must be enough free space in the - /// node to fit the new child. - @inlinable - internal mutating func insertChild( - _ child: __owned _Node, _ bucket: _Bucket - ) { - count &+= child.count - update { - assert(!$0.isCollisionNode) - assert(!$0.itemMap.contains(bucket)) - assert(!$0.childMap.contains(bucket)) - - let slot = $0.childMap.slot(of: bucket) - $0._insertChild(child, at: slot) - $0.childMap.insert(bucket) - } - } - - /// Remove the item at `slot`, increasing the amount of free - /// space available in the node. - /// - /// The closure `remove` is called to perform the deinitialization of the - /// storage slot corresponding to the item to be removed. - @inlinable - internal mutating func removeItem( - at slot: _Slot, _ bucket: _Bucket, - by remover: (UnsafeMutablePointer) -> R - ) -> R { - defer { _invariantCheck() } - assert(count > 0) - count &-= 1 - return update { - let old = $0._removeItem(at: slot, by: remover) - if $0.isCollisionNode { - assert(slot.value < $0.collisionCount) - $0.collisionCount &-= 1 - } else { - assert($0.itemMap.contains(bucket)) - assert($0.itemMap.slot(of: bucket) == slot) - $0.itemMap.remove(bucket) - } - return old - } - } - - @inlinable - internal mutating func removeChild( - at slot: _Slot, _ bucket: _Bucket - ) -> _Node { - defer { _invariantCheck() } - assert(!isCollisionNode) - let child = update { - assert($0.childMap.contains(bucket)) - assert($0.childMap.slot(of: bucket) == slot) - let child = $0._removeChild(at: slot) - $0.childMap.remove(bucket) - return child - } - assert(self.count >= child.count) - self.count &-= child.count - return child - } - - @inlinable - internal mutating func removeSingletonItem() -> Element { - defer { _invariantCheck() } - assert(count == 1) - count = 0 - return update { - assert($0.itemCount == 1 && $0.childCount == 0) - let old = $0._removeItem(at: .zero) { $0.move() } - $0.itemMap = .empty - $0.childMap = .empty - return old - } - } - - @inlinable - internal mutating func removeSingletonChild() -> _Node { - defer { _invariantCheck() } - let child = update { - assert($0.itemCount == 0 && $0.childCount == 1) - let child = $0._removeChild(at: .zero) - $0.childMap = .empty - return child - } - assert(self.count == child.count) - self.count = 0 - return child - } -} - -// MARK: Subtree-level mutation operations - -extension _Node { - @inlinable - internal mutating func updateValue( - _ value: __owned Value, - forKey key: Key, - _ level: _Level, - _ hash: _Hash - ) -> Value? { - defer { _invariantCheck() } - let isUnique = self.isUnique() - let r = find(level, key, hash, forInsert: true) - switch r { - case .found(_, let slot): - ensureUnique(isUnique: isUnique) - _invariantCheck() // FIXME - return update { - let p = $0.itemPtr(at: slot) - let old = p.pointee.value - p.pointee.value = value - return old - } - case .notFound(let bucket, let slot): - ensureUnique(isUnique: isUnique, withFreeSpace: Self.spaceForNewItem) - insertItem((key, value), at: slot, bucket) - return nil - case .newCollision(let bucket, let slot): - _ = _insertNewCollision( - isUnique: isUnique, - level: level, - for: hash, - replacing: slot, bucket, - inserter: { $0.initialize(to: (key, value)) }) - return nil - case .expansion(let collisionHash): - self = _Node.build( - level: level, - item1: { $0.initialize(to: (key, value)) }, hash, - child2: self, collisionHash - ).top - return nil - case .descend(_, let slot): - ensureUnique(isUnique: isUnique) - let old = update { - $0[child: slot].updateValue(value, forKey: key, level.descend(), hash) - } - if old == nil { count &+= 1 } - return old - } - } - - @inlinable - internal mutating func _insertNewCollision( - isUnique: Bool, - level: _Level, - for hash: _Hash, - replacing slot: _Slot, _ bucket: _Bucket, - inserter: (UnsafeMutablePointer) -> Void - ) -> (node: _UnmanagedNode, slot: _Slot) { - let existingHash = read { _Hash($0[item: slot].key) } - if hash == existingHash, hasSingletonItem { - // Convert current node to a collision node. - ensureUnique(isUnique: isUnique, withFreeSpace: Self.spaceForNewItem) - count &+= 1 - update { - $0.collisionCount = 1 - let p = $0._makeRoomForNewItem(at: _Slot(1), .invalid) - inserter(p) - } - return (unmanaged, _Slot(1)) - } - ensureUnique(isUnique: isUnique, withFreeSpace: Self.spaceForNewCollision) - let existing = removeItem(at: slot, bucket) { $0.move() } - let r = _Node.build( - level: level.descend(), - item1: existing, existingHash, - item2: inserter, hash) - insertChild(r.top, bucket) - return (r.leaf, r.slot2) - } -} - -extension _Node { - /// Remove the item with the specified key from this subtree and return it. - /// - /// This function may leave `self` containing a singleton item. - /// It is up to the caller to detect this situation & correct it when needed, - /// by inlining the remaining item into the parent node. - @inlinable - internal mutating func remove( - _ key: Key, _ level: _Level, _ hash: _Hash - ) -> Element? { - defer { _invariantCheck() } - guard self.isUnique() else { - guard let r = removing(key, level, hash) else { return nil } - self = r.replacement - return r.old - } - let r = find(level, key, hash, forInsert: false) - switch r { - case .found(let bucket, let slot): - return _removeItemFromUniqueLeafNode(level, bucket, slot) { $0.move() } - case .notFound, .newCollision, .expansion: - return nil - case .descend(let bucket, let slot): - let (old, needsInlining) = update { - let child = $0.childPtr(at: slot) - let old = child.pointee.remove(key, level.descend(), hash) - guard old != nil else { return (old, false) } - let needsInlining = child.pointee.hasSingletonItem - return (old, needsInlining) - } - guard old != nil else { return nil } - _fixupUniqueAncestorAfterItemRemoval( - slot, { _ in bucket }, needsInlining: needsInlining) - return old - } - } - - @inlinable - internal mutating func _removeItemFromUniqueLeafNode( - _ level: _Level, - _ bucket: _Bucket, - _ slot: _Slot, - by remover: (UnsafeMutablePointer) -> R - ) -> R { - assert(isUnique()) - let result = removeItem(at: slot, bucket, by: remover) - if isAtrophied { - self = removeSingletonChild() - } - if level.isAtRoot, isCollisionNode, hasSingletonItem { - self._convertToRegularNode() - } - return result - } - - @inlinable - internal mutating func _fixupUniqueAncestorAfterItemRemoval( - _ slot: _Slot, - _ bucket: (inout Self) -> _Bucket, - needsInlining: Bool - ) { - assert(isUnique()) - count &-= 1 - if needsInlining { - ensureUnique(isUnique: true, withFreeSpace: Self.spaceForInlinedChild) - let bucket = bucket(&self) - var child = self.removeChild(at: slot, bucket) - let item = child.removeSingletonItem() - insertItem(item, bucket) - } - if isAtrophied { - self = removeSingletonChild() - } - } - - @inlinable - internal mutating func _convertToRegularNode() { - assert(isCollisionNode && hasSingletonItem) - assert(isUnique()) - update { - let hash = _Hash($0[item: .zero].key) - $0.itemMap = _Bitmap(hash[.top]) - $0.childMap = .empty - } - } - - @inlinable - internal func removing( - _ key: Key, _ level: _Level, _ hash: _Hash - ) -> (replacement: _Node, old: Element)? { - let r = find(level, key, hash, forInsert: false) - switch r { - case .found(let bucket, let slot): - return _removingItemFromLeaf(level, slot, bucket) - case .notFound, .newCollision, .expansion: - return nil - case .descend(let bucket, let slot): - let r = read { $0[child: slot].removing(key, level.descend(), hash) } - guard let r = r else { return nil } - return ( - _fixedUpAncestorAfterItemRemoval(level, slot, bucket, r.replacement), - r.old) - } - } - - @inlinable - internal func _removingItemFromLeaf( - _ level: _Level, _ slot: _Slot, _ bucket: _Bucket - ) -> (replacement: _Node, old: Element) { - // Don't copy the node if we'd immediately discard it. - let willAtrophy = read { - $0.itemCount == 1 - && $0.childCount == 1 - && $0[child: .zero].isCollisionNode - } - if willAtrophy { - return read { (replacement: $0[child: .zero], old: $0[item: .zero]) } - } - var node = self.copy() - let old = node.removeItem(at: slot, bucket) { $0.move() } - if level.isAtRoot, node.isCollisionNode, node.hasSingletonItem { - node._convertToRegularNode() - } - node._invariantCheck() - return (node, old) - } - - @inlinable - internal func _fixedUpAncestorAfterItemRemoval( - _ level: _Level, - _ slot: _Slot, - _ bucket: _Bucket, - _ newChild: __owned _Node - ) -> _Node { - var newChild = newChild - if newChild.hasSingletonItem { - var node = copy(withFreeSpace: Self.spaceForInlinedChild) - _ = node.removeChild(at: slot, bucket) - let item = newChild.removeSingletonItem() - node.insertItem(item, bucket) - node._invariantCheck() - return node - } - if newChild.isCollisionNode && self.hasSingletonChild { - // Don't return an atrophied node. - return newChild - } - var node = copy() - node.update { $0[child: slot] = newChild } - node.count &-= 1 - node._invariantCheck() - return node - } -} - -extension _Node { - @inlinable - internal mutating func remove( - _ level: _Level, at path: _UnsafePath - ) -> Element { - defer { _invariantCheck() } - guard self.isUnique() else { - let r = removing(level, at: path) - self = r.replacement - return r.old - } - if level == path.level { - let slot = path.currentItemSlot - let bucket = read { $0.itemBucket(at: slot) } - return _removeItemFromUniqueLeafNode( - level, bucket, slot, by: { $0.move() }) - } - let slot = path.childSlot(at: level) - let (item, needsInlining) = update { - let child = $0.childPtr(at: slot) - let item = child.pointee.remove(level.descend(), at: path) - return (item, child.pointee.hasSingletonItem) - } - _fixupUniqueAncestorAfterItemRemoval( - slot, - { $0.read { $0.childMap.bucket(at: slot) } }, - needsInlining: needsInlining) - return item - } - - @inlinable - internal func removing( - _ level: _Level, at path: _UnsafePath - ) -> (replacement: _Node, old: Element) { - if level == path.level { - let slot = path.currentItemSlot - let bucket = read { $0.itemBucket(at: slot) } - return _removingItemFromLeaf(level, slot, bucket) - } - let slot = path.childSlot(at: level) - let (bucket, r) = read { - ($0.childMap.bucket(at: slot), - $0[child: slot].removing(level.descend(), at: path)) - } - return ( - _fixedUpAncestorAfterItemRemoval(level, slot, bucket, r.replacement), - r.old - ) - } -} - -extension _Node { - @usableFromInline - @frozen - internal struct ValueUpdateState { - @usableFromInline - internal var key: Key - - @usableFromInline - internal var value: Value? - - @usableFromInline - internal let hash: _Hash - - @usableFromInline - internal var path: _UnsafePath - - @usableFromInline - internal var found: Bool - - @inlinable - internal init( - _ key: Key, - _ hash: _Hash, - _ path: _UnsafePath - ) { - self.key = key - self.value = nil - self.hash = hash - self.path = path - self.found = false - } - } - - @inlinable - internal mutating func prepareValueUpdate( - _ key: Key, - _ hash: _Hash - ) -> ValueUpdateState { - var state = ValueUpdateState(key, hash, _UnsafePath(root: raw)) - _prepareValueUpdate(&state) - return state - } - - @inlinable - internal mutating func _prepareValueUpdate( - _ state: inout ValueUpdateState - ) { - // This doesn't make room for a new item if the key doesn't already exist - // but it does ensure that all parent nodes along its eventual path are - // uniquely held. - // - // If the key already exists, we ensure uniqueness for its node and extract - // its item but otherwise leave the tree as it was. - let isUnique = self.isUnique() - let r = find(state.path.level, state.key, state.hash, forInsert: true) - switch r { - case .found(_, let slot): - ensureUnique(isUnique: isUnique) - state.path.node = unmanaged - state.path.selectItem(at: slot) - state.found = true - (state.key, state.value) = update { $0.itemPtr(at: slot).move() } - - case .notFound(_, let slot): - state.path.selectItem(at: slot) - - case .newCollision(_, let slot): - state.path.selectItem(at: slot) - - case .expansion(_): - state.path.selectEnd() - - case .descend(_, let slot): - ensureUnique(isUnique: isUnique) - state.path.selectChild(at: slot) - state.path.descend() - update { $0[child: slot]._prepareValueUpdate(&state) } - } - } - - @inlinable - internal mutating func finalizeValueUpdate( - _ state: __owned ValueUpdateState - ) { - switch (state.found, state.value != nil) { - case (true, true): - // Fast path: updating an existing value. - UnsafeHandle.update(state.path.node) { - $0.itemPtr(at: state.path.currentItemSlot) - .initialize(to: (state.key, state.value.unsafelyUnwrapped)) - } - case (true, false): - // Removal - _finalizeRemoval(.top, state.hash, at: state.path) - case (false, true): - // Insertion - _ = updateValue( - state.value.unsafelyUnwrapped, forKey: state.key, .top, state.hash) - case (false, false): - // Noop - break - } - } - - @inlinable - internal mutating func _finalizeRemoval( - _ level: _Level, _ hash: _Hash, at path: _UnsafePath - ) { - assert(isUnique()) - if level == path.level { - _removeItemFromUniqueLeafNode( - level, hash[level], path.currentItemSlot, by: { _ in }) - } else { - let slot = path.childSlot(at: level) - let needsInlining = update { - let child = $0.childPtr(at: slot) - child.pointee._finalizeRemoval(level.descend(), hash, at: path) - return child.pointee.hasSingletonItem - } - _fixupUniqueAncestorAfterItemRemoval( - slot, { _ in hash[level] }, needsInlining: needsInlining) - } - } -} - -extension _Node { - @usableFromInline - @frozen - internal struct DefaultedValueUpdateState { - @usableFromInline - internal var item: Element - - @usableFromInline - internal var node: _UnmanagedNode - - @usableFromInline - internal var slot: _Slot - - @usableFromInline - internal var inserted: Bool - - @inlinable - internal init( - _ item: Element, - in node: _UnmanagedNode, - at slot: _Slot, - inserted: Bool - ) { - self.item = item - self.node = node - self.slot = slot - self.inserted = inserted - } - } - - @inlinable - internal mutating func prepareDefaultedValueUpdate( - _ level: _Level, - _ key: Key, - _ defaultValue: () -> Value, - _ hash: _Hash - ) -> DefaultedValueUpdateState { - let isUnique = self.isUnique() - let r = find(level, key, hash, forInsert: true) - switch r { - case .found(_, let slot): - ensureUnique(isUnique: isUnique) - return DefaultedValueUpdateState( - update { $0.itemPtr(at: slot).move() }, - in: unmanaged, - at: slot, - inserted: false) - - case .notFound(let bucket, let slot): - ensureUnique(isUnique: isUnique, withFreeSpace: Self.spaceForNewItem) - update { _ = $0._makeRoomForNewItem(at: slot, bucket) } - self.count &+= 1 - return DefaultedValueUpdateState( - (key, defaultValue()), - in: unmanaged, - at: slot, - inserted: true) - - case .newCollision(let bucket, let slot): - let r = _insertNewCollision( - isUnique: isUnique, - level: level, - for: hash, - replacing: slot, bucket, - inserter: { _ in }) - return DefaultedValueUpdateState( - (key, defaultValue()), - in: r.node, - at: r.slot, - inserted: true) - - case .expansion(let collisionHash): - let r = _Node.build( - level: level, - item1: { _ in }, hash, - child2: self, collisionHash - ) - self = r.top - return DefaultedValueUpdateState( - (key, defaultValue()), - in: r.leaf, - at: r.slot1, - inserted: true) - - case .descend(_, let slot): - ensureUnique(isUnique: isUnique) - let res = update { - $0[child: slot].prepareDefaultedValueUpdate( - level.descend(), key, defaultValue, hash) - } - if res.inserted { count &+= 1 } - return res - } - } - - @inlinable - internal mutating func finalizeDefaultedValueUpdate( - _ state: __owned DefaultedValueUpdateState - ) { - UnsafeHandle.update(state.node) { - $0.itemPtr(at: state.slot).initialize(to: state.item) - } - } -} diff --git a/Sources/PersistentCollections/Node/_Node+Primitive Insertions.swift b/Sources/PersistentCollections/Node/_Node+Primitive Insertions.swift new file mode 100644 index 00000000..c52b16c3 --- /dev/null +++ b/Sources/PersistentCollections/Node/_Node+Primitive Insertions.swift @@ -0,0 +1,117 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// MARK: Node-level insertion operations + +extension _Node.UnsafeHandle { + /// Make room for a new item at `slot` corresponding to `bucket`. + /// There must be enough free space in the node to fit the new item. + /// + /// `itemMap` must not already reflect the insertion at the time this + /// function is called. This method does not update `itemMap`. + /// + /// - Returns: an unsafe mutable pointer to uninitialized memory that is + /// ready to store the new item. It is the caller's responsibility to + /// initialize this memory. + @inlinable + internal func _makeRoomForNewItem( + at slot: _Slot, _ bucket: _Bucket + ) -> UnsafeMutablePointer { + assertMutable() + let c = itemCount + assert(slot.value <= c) + + let stride = MemoryLayout.stride + assert(bytesFree >= stride) + bytesFree &-= stride + + let start = _memory + .advanced(by: byteCapacity &- (c &+ 1) &* stride) + .bindMemory(to: Element.self, capacity: 1) + + let prefix = c &- slot.value + start.moveInitialize(from: start + 1, count: prefix) + + if bucket.isInvalid { + assert(isCollisionNode) + collisionCount &+= 1 + } else { + assert(!itemMap.contains(bucket)) + assert(!childMap.contains(bucket)) + itemMap.insert(bucket) + assert(itemMap.slot(of: bucket) == slot) + } + + return start + prefix + } + + /// Insert `child` at `slot`. There must be enough free space in the node + /// to fit the new child. + /// + /// `childMap` must not yet reflect the insertion at the time this + /// function is called. This method does not update `childMap`. + @inlinable + internal func _insertChild(_ child: __owned _Node, at slot: _Slot) { + assertMutable() + assert(!isCollisionNode) + + let c = childMap.count + assert(slot.value <= c) + + let stride = MemoryLayout<_Node>.stride + assert(bytesFree >= stride) + bytesFree &-= stride + + _memory.bindMemory(to: _Node.self, capacity: c &+ 1) + let q = _childrenStart + slot.value + (q + 1).moveInitialize(from: q, count: c &- slot.value) + q.initialize(to: child) + } +} + +extension _Node { + @inlinable @inline(__always) + internal mutating func insertItem( + _ item: __owned Element, _ bucket: _Bucket + ) { + let slot = read { $0.itemMap.slot(of: bucket) } + self.insertItem(item, at: slot, bucket) + } + + @inlinable @inline(__always) + internal mutating func insertItem( + _ item: __owned Element, at slot: _Slot, _ bucket: _Bucket + ) { + self.count &+= 1 + update { + let p = $0._makeRoomForNewItem(at: slot, bucket) + p.initialize(to: item) + } + } + + /// Insert `child` in `bucket`. There must be enough free space in the + /// node to fit the new child. + @inlinable + internal mutating func insertChild( + _ child: __owned _Node, _ bucket: _Bucket + ) { + count &+= child.count + update { + assert(!$0.isCollisionNode) + assert(!$0.itemMap.contains(bucket)) + assert(!$0.childMap.contains(bucket)) + + let slot = $0.childMap.slot(of: bucket) + $0._insertChild(child, at: slot) + $0.childMap.insert(bucket) + } + } +} diff --git a/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift b/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift new file mode 100644 index 00000000..7e5c13fa --- /dev/null +++ b/Sources/PersistentCollections/Node/_Node+Primitive Removals.swift @@ -0,0 +1,138 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// MARK: Node-level removal operations + +extension _Node.UnsafeHandle { + /// Remove and return the item at `slot`, increasing the amount of free + /// space available in the node. + /// + /// `itemMap` must not yet reflect the removal at the time this + /// function is called. This method does not update `itemMap`. + @inlinable + internal func _removeItem( + at slot: _Slot, + by remover: (UnsafeMutablePointer) -> R + ) -> R { + assertMutable() + let c = itemCount + assert(slot.value < c) + let stride = MemoryLayout.stride + bytesFree &+= stride + + let start = _memory + .advanced(by: byteCapacity &- stride &* c) + .assumingMemoryBound(to: Element.self) + + let prefix = c &- 1 &- slot.value + let q = start + prefix + defer { + (start + 1).moveInitialize(from: start, count: prefix) + } + return remover(q) + } + + /// Remove and return the child at `slot`, increasing the amount of free + /// space available in the node. + /// + /// `childMap` must not yet reflect the removal at the time this + /// function is called. This method does not update `childMap`. + @inlinable + internal func _removeChild(at slot: _Slot) -> _Node { + assertMutable() + assert(!isCollisionNode) + let count = childCount + assert(slot.value < count) + + bytesFree &+= MemoryLayout<_Node>.stride + + let q = _childrenStart + slot.value + let child = q.move() + q.moveInitialize(from: q + 1, count: count &- 1 &- slot.value) + return child + } +} + +extension _Node { + /// Remove the item at `slot`, increasing the amount of free + /// space available in the node. + /// + /// The closure `remove` is called to perform the deinitialization of the + /// storage slot corresponding to the item to be removed. + @inlinable + internal mutating func removeItem( + at slot: _Slot, _ bucket: _Bucket, + by remover: (UnsafeMutablePointer) -> R + ) -> R { + defer { _invariantCheck() } + assert(count > 0) + count &-= 1 + return update { + let old = $0._removeItem(at: slot, by: remover) + if $0.isCollisionNode { + assert(slot.value < $0.collisionCount) + $0.collisionCount &-= 1 + } else { + assert($0.itemMap.contains(bucket)) + assert($0.itemMap.slot(of: bucket) == slot) + $0.itemMap.remove(bucket) + } + return old + } + } + + @inlinable + internal mutating func removeChild( + at slot: _Slot, _ bucket: _Bucket + ) -> _Node { + defer { _invariantCheck() } + assert(!isCollisionNode) + let child = update { + assert($0.childMap.contains(bucket)) + assert($0.childMap.slot(of: bucket) == slot) + let child = $0._removeChild(at: slot) + $0.childMap.remove(bucket) + return child + } + assert(self.count >= child.count) + self.count &-= child.count + return child + } + + @inlinable + internal mutating func removeSingletonItem() -> Element { + defer { _invariantCheck() } + assert(count == 1) + count = 0 + return update { + assert($0.itemCount == 1 && $0.childCount == 0) + let old = $0._removeItem(at: .zero) { $0.move() } + $0.itemMap = .empty + $0.childMap = .empty + return old + } + } + + @inlinable + internal mutating func removeSingletonChild() -> _Node { + defer { _invariantCheck() } + let child = update { + assert($0.itemCount == 0 && $0.childCount == 1) + let child = $0._removeChild(at: .zero) + $0.childMap = .empty + return child + } + assert(self.count == child.count) + self.count = 0 + return child + } +} + diff --git a/Sources/PersistentCollections/Node/_Node+Storage.swift b/Sources/PersistentCollections/Node/_Node+Storage.swift index bae2cfa5..ba386500 100644 --- a/Sources/PersistentCollections/Node/_Node+Storage.swift +++ b/Sources/PersistentCollections/Node/_Node+Storage.swift @@ -41,16 +41,16 @@ extension _Node { deinit { UnsafeHandle.update(self) { handle in - handle._children.deinitialize() + handle.children.deinitialize() handle.reverseItems.deinitialize() } } } } -extension _Node { +extension _Node.Storage { @inlinable - internal init(byteCapacity: Int) { + internal static func allocate(byteCapacity: Int) -> _Node.Storage { assert(byteCapacity >= 0) let itemStride = MemoryLayout.stride @@ -69,7 +69,7 @@ extension _Node { bytes += itemAlignment - childAlignment } - let object = Storage.create( + let object = _Node.Storage.create( minimumCapacity: (bytes &+ childStride &- 1) / childStride ) { buffer in _StorageHeader(byteCapacity: buffer.capacity * childStride) @@ -84,22 +84,17 @@ extension _Node { header.pointee._bytesFree = header.pointee._byteCapacity assert(byteCapacity <= header.pointee.byteCapacity) } - self.raw = _RawNode( - storage: unsafeDowncast(object, to: Storage.self), - count: 0) + return unsafeDowncast(object, to: _Node.Storage.self) } - @inlinable - internal init(itemCapacity: Int = 0, childCapacity: Int = 0) { + @inlinable @inline(__always) + internal static func allocate( + itemCapacity: Int = 0, childCapacity: Int = 0 + ) -> _Node.Storage { assert(itemCapacity >= 0 && childCapacity >= 0) let itemBytes = itemCapacity * MemoryLayout.stride let childBytes = childCapacity * MemoryLayout<_Node>.stride - self.init(byteCapacity: itemBytes &+ childBytes) - } - - @inlinable - internal init(collisionCapacity: Int) { - self.init(itemCapacity: collisionCapacity, childCapacity: 0) + return allocate(byteCapacity: itemBytes &+ childBytes) } } @@ -129,6 +124,11 @@ extension _Node { isKnownUniquelyReferenced(&self.raw.storage) } + @inlinable + internal mutating func hasFreeSpace(_ bytes: Int) -> Bool { + bytes <= self.raw.storage.header.bytesFree + } + @inlinable internal mutating func ensureUnique(isUnique: Bool) { if !isUnique { @@ -143,28 +143,51 @@ extension _Node { ) { if !isUnique { self = copy(withFreeSpace: minimumFreeBytes) - } else if self.raw.storage.header.bytesFree < minimumFreeBytes { + } else if !hasFreeSpace(minimumFreeBytes) { move(withFreeSpace: minimumFreeBytes) } } + + @inlinable + internal static func allocate( + itemMap: _Bitmap, childMap: _Bitmap, + count: Int, + initializingWith initializer: ( + UnsafeMutableBufferPointer<_Node>, UnsafeMutableBufferPointer + ) -> R + ) -> (node: _Node, result: R) { + let (itemCount, childCount) = _StorageHeader.counts( + itemMap: itemMap, childMap: childMap) + let storage = Storage.allocate( + itemCapacity: itemCount, childCapacity: childCount) + var node = _Node(storage: storage, count: count) + let result = node.update { + let (children, items) = $0._prepare( + itemMap: itemMap, + itemCount: itemCount, + childMap: childMap, + childCount: childCount + ) + return initializer(children, items) + } + return (node, result) + } + @inlinable @inline(never) internal func copy(withFreeSpace space: Int = 0) -> _Node { assert(space >= 0) - let capacity = read { - $0.byteCapacity &- $0.bytesFree &+ space - } - var new = Self(byteCapacity: capacity) - new.count = self.count - read { source in - new.update { target in - target._prepare(itemMap: source.itemMap, childMap: source.childMap) - let i = target._children.initialize(fromContentsOf: source._children) - assert(i == target.childCount) + let capacity = read { $0.byteCapacity &- $0.bytesFree &+ space } + var new = Self( + storage: Storage.allocate(byteCapacity: capacity), + count: count) + read { src in + new.update { dst in + let (dstChildren, dstItems) = dst._prepare( + itemMap: src.itemMap, childMap: src.childMap) - let j = target.reverseItems - .initialize(fromContentsOf: source.reverseItems) - assert(j == target.itemCount) + dstChildren.initializeAll(fromContentsOf: src.children) + dstItems.initializeAll(fromContentsOf: src.reverseItems) } } new._invariantCheck() @@ -174,25 +197,20 @@ extension _Node { @inlinable @inline(never) internal mutating func move(withFreeSpace space: Int = 0) { assert(space >= 0) - let capacity = read { - $0.byteCapacity &+ Swift.max(0, space &- $0.bytesFree) - } - var new = Self(byteCapacity: capacity) - new.count = self.count - self.update { source in - new.update { target in - target._prepare(itemMap: source.itemMap, childMap: source.childMap) + let capacity = read { $0.byteCapacity &- $0.bytesFree &+ space } + var new = Self( + storage: Storage.allocate(byteCapacity: capacity), + count: self.count) + self.update { src in + new.update { dst in + let (dstChildren, dstItems) = dst._prepare( + itemMap: src.itemMap, childMap: src.childMap) - let i = target._children.moveInitialize(fromContentsOf: source._children) - assert(i == target.childCount) + dstChildren.moveInitializeAll(fromContentsOf: src.children) + dstItems.moveInitializeAll(fromContentsOf: src.reverseItems) - let j = target.reverseItems - .moveInitialize(fromContentsOf: source.reverseItems) - assert(j == target.itemCount) - source.itemMap = .empty - source.childMap = .empty - source.bytesFree = source.byteCapacity - assert(target.bytesFree >= space) + src.clear() + assert(dst.bytesFree >= space) } } self.count = 0 @@ -204,15 +222,45 @@ extension _Node { extension _Node.UnsafeHandle { @inlinable - internal func _prepare(itemMap: _Bitmap, childMap: _Bitmap) { + internal func _prepare( + itemMap: _Bitmap, childMap: _Bitmap + ) -> ( + children: UnsafeMutableBufferPointer<_Node>, + items: UnsafeMutableBufferPointer + ) { + let (itemCount, childCount) = _StorageHeader.counts( + itemMap: itemMap, childMap: childMap) + return self._prepare( + itemMap: itemMap, + itemCount: itemCount, + childMap: childMap, + childCount: childCount) + } + + @inlinable + internal func _prepare( + itemMap: _Bitmap, + itemCount: Int, + childMap: _Bitmap, + childCount: Int + ) -> ( + children: UnsafeMutableBufferPointer<_Node>, + items: UnsafeMutableBufferPointer + ) { assert(self.itemMap.isEmpty && self.childMap.isEmpty) assert(self.byteCapacity == self.bytesFree) + + assert( + itemMap == childMap + || (itemMap.count == itemCount && childMap.count == childCount)) + + assert( + itemMap != childMap + || (itemCount == itemMap._value && childCount == 0)) + self.itemMap = itemMap self.childMap = childMap - let itemCount = self.itemCount - let childCount = self.childCount - let itemStride = MemoryLayout.stride let childStride = MemoryLayout<_Node>.stride @@ -222,9 +270,13 @@ extension _Node.UnsafeHandle { assert(occupiedBytes <= byteCapacity) bytesFree = byteCapacity &- occupiedBytes - self._memory.bindMemory(to: _Node.self, capacity: childCount) - (self._memory + (byteCapacity - itemBytes)) + let childStart = self._memory + .bindMemory(to: _Node.self, capacity: childCount) + let itemStart = (self._memory + (byteCapacity - itemBytes)) .bindMemory(to: Element.self, capacity: itemCount) + return ( + .init(start: childStart, count: childCount), + .init(start: itemStart, count: itemCount)) } } diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift new file mode 100644 index 00000000..344abbe0 --- /dev/null +++ b/Sources/PersistentCollections/Node/_Node+Subtree Insertions.swift @@ -0,0 +1,348 @@ +//===----------------------------------------------------------------------===// +// +// 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 _Node { + @inlinable + internal mutating func updateValue( + _ value: __owned Value, + forKey key: Key, + _ level: _Level, + _ hash: _Hash + ) -> Value? { + defer { _invariantCheck() } + let isUnique = self.isUnique() + let r = find(level, key, hash, forInsert: true) + switch r { + case .found(_, let slot): + ensureUnique(isUnique: isUnique) + _invariantCheck() // FIXME + return update { + let p = $0.itemPtr(at: slot) + let old = p.pointee.value + p.pointee.value = value + return old + } + case .notFound(let bucket, let slot): + ensureUniqueAndInsertItem(isUnique: isUnique, slot, bucket) { + $0.initialize(to: (key, value)) + } + return nil + case .newCollision(let bucket, let slot): + _ = ensureUniqueAndMakeNewCollision( + isUnique: isUnique, + level: level, + replacing: slot, bucket, + newHash: hash + ) { + $0.initialize(to: (key, value)) + } + return nil + case .expansion(let collisionHash): + self = _Node.build( + level: level, + item1: { $0.initialize(to: (key, value)) }, hash, + child2: self, collisionHash + ).top + return nil + case .descend(_, let slot): + ensureUnique(isUnique: isUnique) + let old = update { + $0[child: slot].updateValue(value, forKey: key, level.descend(), hash) + } + if old == nil { count &+= 1 } + return old + } + } + + @inlinable + internal mutating func insertValue( + forKey key: Key, + _ level: _Level, + _ hash: _Hash, + with value: () -> Value + ) -> (inserted: Bool, leaf: _UnmanagedNode, slot: _Slot) { + defer { _invariantCheck() } + let isUnique = self.isUnique() + let r = find(level, key, hash, forInsert: true) + switch r { + case .found(_, let slot): + ensureUnique(isUnique: isUnique) + _invariantCheck() // FIXME + return (false, unmanaged, slot) + case .notFound(let bucket, let slot): + ensureUniqueAndInsertItem(isUnique: isUnique, slot, bucket) { + $0.initialize(to: (key, value())) + } + return (true, unmanaged, slot) + case .newCollision(let bucket, let slot): + let r = ensureUniqueAndMakeNewCollision( + isUnique: isUnique, + level: level, + replacing: slot, bucket, + newHash: hash + ) { + $0.initialize(to: (key, value())) + } + return (true, r.leaf, r.slot) + case .expansion(let collisionHash): + let r = _Node.build( + level: level, + item1: { $0.initialize(to: (key, value())) }, hash, + child2: self, collisionHash + ) + self = r.top + return (true, r.leaf, r.slot1) + case .descend(_, let slot): + ensureUnique(isUnique: isUnique) + let r = update { + $0[child: slot] + .insertValue(forKey: key, level.descend(), hash, with: value) + } + if r.inserted { count &+= 1 } + return r + } + } +} + +extension _Node { + @inlinable + internal mutating func ensureUniqueAndInsertItem( + isUnique: Bool, + _ slot: _Slot, + _ bucket: _Bucket, + inserter: (UnsafeMutablePointer) -> Void + ) { + if !isUnique { + self = copyNodeAndInsertItem(at: slot, bucket, inserter: inserter) + return + } + if !hasFreeSpace(Self.spaceForNewItem) { + moveNodeAndInsertItem(at: slot, bucket, inserter: inserter) + return + } + // In-place insert. + update { + let p = $0._makeRoomForNewItem(at: slot, bucket) + inserter(p) + } + self.count &+= 1 + } + + @inlinable @inline(never) + internal func copyNodeAndInsertItem( + at slot: _Slot, + _ bucket: _Bucket, + inserter: (UnsafeMutablePointer) -> Void + ) -> _Node { + // Copy items into new storage. + 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 + ) { dstChildren, dstItems in + dstChildren.initializeAll(fromContentsOf: src.children) + + let srcItems = src.reverseItems + assert(dstItems.count == srcItems.count + 1) + dstItems.suffix(slot.value) + .initializeAll(fromContentsOf: srcItems.suffix(slot.value)) + let rest = srcItems.count &- slot.value + dstItems.prefix(rest) + .initializeAll(fromContentsOf: srcItems.prefix(rest)) + + inserter(dstItems.baseAddress! + rest) + } + }.node + } + + @inlinable @inline(never) + internal mutating func moveNodeAndInsertItem( + at slot: _Slot, + _ bucket: _Bucket, + inserter: (UnsafeMutablePointer) -> Void + ) { + // Copy items into new storage. + 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 + ) { dstChildren, dstItems in + dstChildren.moveInitializeAll(fromContentsOf: src.children) + + let srcItems = src.reverseItems + assert(dstItems.count == srcItems.count + 1) + dstItems.suffix(slot.value) + .moveInitializeAll(fromContentsOf: srcItems.suffix(slot.value)) + let rest = srcItems.count &- slot.value + dstItems.prefix(rest) + .moveInitializeAll(fromContentsOf: srcItems.prefix(rest)) + + inserter(dstItems.baseAddress! + rest) + + src.clear() + } + }.node + } +} + +extension _Node { + @inlinable + internal mutating func ensureUniqueAndMakeNewCollision( + isUnique: Bool, + level: _Level, + replacing slot: _Slot, + _ bucket: _Bucket, + newHash: _Hash, + inserter: (UnsafeMutablePointer) -> Void + ) -> (leaf: _UnmanagedNode, slot: _Slot) { + let existingHash = read { _Hash($0[item: slot].key) } + if newHash == existingHash, hasSingletonItem { + // Convert current node to a collision node. + ensureUnique(isUnique: isUnique, withFreeSpace: Self.spaceForNewItem) + count &+= 1 + update { + $0.collisionCount = 1 + let p = $0._makeRoomForNewItem(at: _Slot(1), .invalid) + inserter(p) + } + return (unmanaged, _Slot(1)) + } + + if !isUnique { + let r = copyNodeAndMakeNewCollision( + level: level, + replacing: slot, bucket, + existingHash: existingHash, + newHash: newHash, + inserter: inserter) + self = r.node + return (r.leaf, r.slot) + } + if !hasFreeSpace(Self.spaceForNewCollision) { + return moveNodeAndMakeNewCollision( + level: level, + replacing: slot, bucket, + existingHash: existingHash, + newHash: newHash, + inserter: inserter) + } + + let existing = removeItem(at: slot, bucket) { $0.move() } + let r = _Node.build( + level: level.descend(), + item1: existing, existingHash, + item2: inserter, newHash) + insertChild(r.top, bucket) + return (r.leaf, r.slot2) + } + + @inlinable @inline(never) + internal func copyNodeAndMakeNewCollision( + level: _Level, + replacing slot: _Slot, + _ bucket: _Bucket, + existingHash: _Hash, + newHash: _Hash, + inserter: (UnsafeMutablePointer) -> Void + ) -> (node: _Node, leaf: _UnmanagedNode, slot: _Slot) { + let (itemMap, childMap) = ( + self.raw.storage.header.bitmapsForNewCollision(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 + + // 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[slot.value], existingHash, + item2: inserter, newHash) + dstChildren.initializeElement(at: childSlot.value, to: r.top) + + // Initialize items. + dstItems.prefix(slot.value) + .initializeAll(fromContentsOf: srcItems.prefix(slot.value)) + let rest2 = dstItems.count &- slot.value + dstItems.suffix(rest2) + .initializeAll(fromContentsOf: srcItems.suffix(rest2)) + + return (leaf: r.leaf, slot: r.slot2) + } + } + return (r.node, r.result.leaf, r.result.slot) + } + + @inlinable @inline(never) + internal mutating func moveNodeAndMakeNewCollision( + level: _Level, + replacing slot: _Slot, + _ bucket: _Bucket, + existingHash: _Hash, + newHash: _Hash, + inserter: (UnsafeMutablePointer) -> Void + ) -> (leaf: _UnmanagedNode, slot: _Slot) { + let (itemMap, childMap) = ( + self.raw.storage.header.bitmapsForNewCollision(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 + + // 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: slot.value), existingHash, + item2: inserter, newHash) + dstChildren.initializeElement(at: childSlot.value, to: r.top) + + // Initialize items. + dstItems.prefix(slot.value) + .moveInitializeAll(fromContentsOf: srcItems.prefix(slot.value)) + let rest2 = dstItems.count &- slot.value + dstItems.suffix(rest2) + .moveInitializeAll(fromContentsOf: srcItems.suffix(rest2)) + + src.clear() + return (leaf: r.leaf, slot: r.slot2) + } + } + r.node._invariantCheck() + self = r.node + return (r.result.leaf, r.result.slot) + } +} + diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift b/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift new file mode 100644 index 00000000..a10db5c4 --- /dev/null +++ b/Sources/PersistentCollections/Node/_Node+Subtree Modify.swift @@ -0,0 +1,254 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// MARK: Subtree-level in-place mutation operations + +extension _Node { + @inlinable + internal mutating func ensureUnique( + level: _Level, at path: _UnsafePath + ) -> (leaf: _UnmanagedNode, slot: _Slot) { + ensureUnique(isUnique: isUnique()) + guard level < path.level else { return (unmanaged, path.currentItemSlot) } + return update { + $0[child: path.childSlot(at: level)] + .ensureUnique(level: level.descend(), at: path) + } + } +} + +extension _Node { + @usableFromInline + @frozen + internal struct ValueUpdateState { + @usableFromInline + internal var key: Key + + @usableFromInline + internal var value: Value? + + @usableFromInline + internal let hash: _Hash + + @usableFromInline + internal var path: _UnsafePath + + @usableFromInline + internal var found: Bool + + @inlinable + internal init( + _ key: Key, + _ hash: _Hash, + _ path: _UnsafePath + ) { + self.key = key + self.value = nil + self.hash = hash + self.path = path + self.found = false + } + } + + @inlinable + internal mutating func prepareValueUpdate( + _ key: Key, + _ hash: _Hash + ) -> ValueUpdateState { + var state = ValueUpdateState(key, hash, _UnsafePath(root: raw)) + _prepareValueUpdate(&state) + return state + } + + @inlinable + internal mutating func _prepareValueUpdate( + _ state: inout ValueUpdateState + ) { + // This doesn't make room for a new item if the key doesn't already exist + // but it does ensure that all parent nodes along its eventual path are + // uniquely held. + // + // If the key already exists, we ensure uniqueness for its node and extract + // its item but otherwise leave the tree as it was. + let isUnique = self.isUnique() + let r = find(state.path.level, state.key, state.hash, forInsert: true) + switch r { + case .found(_, let slot): + ensureUnique(isUnique: isUnique) + state.path.node = unmanaged + state.path.selectItem(at: slot) + state.found = true + (state.key, state.value) = update { $0.itemPtr(at: slot).move() } + + case .notFound(_, let slot): + state.path.selectItem(at: slot) + + case .newCollision(_, let slot): + state.path.selectItem(at: slot) + + case .expansion(_): + state.path.selectEnd() + + case .descend(_, let slot): + ensureUnique(isUnique: isUnique) + state.path.selectChild(at: slot) + state.path.descend() + update { $0[child: slot]._prepareValueUpdate(&state) } + } + } + + @inlinable + internal mutating func finalizeValueUpdate( + _ state: __owned ValueUpdateState + ) { + switch (state.found, state.value != nil) { + case (true, true): + // Fast path: updating an existing value. + UnsafeHandle.update(state.path.node) { + $0.itemPtr(at: state.path.currentItemSlot) + .initialize(to: (state.key, state.value.unsafelyUnwrapped)) + } + case (true, false): + // Removal + _finalizeRemoval(.top, state.hash, at: state.path) + case (false, true): + // Insertion + _ = updateValue( + state.value.unsafelyUnwrapped, forKey: state.key, .top, state.hash) + case (false, false): + // Noop + break + } + } + + @inlinable + internal mutating func _finalizeRemoval( + _ level: _Level, _ hash: _Hash, at path: _UnsafePath + ) { + assert(isUnique()) + if level == path.level { + _removeItemFromUniqueLeafNode( + level, hash[level], path.currentItemSlot, by: { _ in }) + } else { + let slot = path.childSlot(at: level) + let needsInlining = update { + let child = $0.childPtr(at: slot) + child.pointee._finalizeRemoval(level.descend(), hash, at: path) + return child.pointee.hasSingletonItem + } + _fixupUniqueAncestorAfterItemRemoval( + slot, { _ in hash[level] }, needsInlining: needsInlining) + } + } +} + +extension _Node { + @usableFromInline + @frozen + internal struct DefaultedValueUpdateState { + @usableFromInline + internal var item: Element + + @usableFromInline + internal var node: _UnmanagedNode + + @usableFromInline + internal var slot: _Slot + + @usableFromInline + internal var inserted: Bool + + @inlinable + internal init( + _ item: Element, + in node: _UnmanagedNode, + at slot: _Slot, + inserted: Bool + ) { + self.item = item + self.node = node + self.slot = slot + self.inserted = inserted + } + } + + @inlinable + internal mutating func prepareDefaultedValueUpdate( + _ level: _Level, + _ key: Key, + _ defaultValue: () -> Value, + _ hash: _Hash + ) -> DefaultedValueUpdateState { + let isUnique = self.isUnique() + let r = find(level, key, hash, forInsert: true) + switch r { + case .found(_, let slot): + ensureUnique(isUnique: isUnique) + return DefaultedValueUpdateState( + update { $0.itemPtr(at: slot).move() }, + in: unmanaged, + at: slot, + inserted: false) + + case .notFound(let bucket, let slot): + ensureUniqueAndInsertItem(isUnique: isUnique, slot, bucket) { _ in } + return DefaultedValueUpdateState( + (key, defaultValue()), + in: unmanaged, + at: slot, + inserted: true) + + case .newCollision(let bucket, let slot): + let r = ensureUniqueAndMakeNewCollision( + isUnique: isUnique, + level: level, + replacing: slot, bucket, + newHash: hash) { _ in } + return DefaultedValueUpdateState( + (key, defaultValue()), + in: r.leaf, + at: r.slot, + inserted: true) + + case .expansion(let collisionHash): + let r = _Node.build( + level: level, + item1: { _ in }, hash, + child2: self, collisionHash + ) + self = r.top + return DefaultedValueUpdateState( + (key, defaultValue()), + in: r.leaf, + at: r.slot1, + inserted: true) + + case .descend(_, let slot): + ensureUnique(isUnique: isUnique) + let res = update { + $0[child: slot].prepareDefaultedValueUpdate( + level.descend(), key, defaultValue, hash) + } + if res.inserted { count &+= 1 } + return res + } + } + + @inlinable + internal mutating func finalizeDefaultedValueUpdate( + _ state: __owned DefaultedValueUpdateState + ) { + UnsafeHandle.update(state.node) { + $0.itemPtr(at: state.slot).initialize(to: state.item) + } + } +} + diff --git a/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift new file mode 100644 index 00000000..907b76b3 --- /dev/null +++ b/Sources/PersistentCollections/Node/_Node+Subtree Removals.swift @@ -0,0 +1,226 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// MARK: Subtree-level removal operations + +extension _Node { + /// Remove the item with the specified key from this subtree and return it. + /// + /// This function may leave `self` containing a singleton item. + /// It is up to the caller to detect this situation & correct it when needed, + /// by inlining the remaining item into the parent node. + @inlinable + internal mutating func remove( + _ key: Key, _ level: _Level, _ hash: _Hash + ) -> Element? { + defer { _invariantCheck() } + guard self.isUnique() else { + guard let r = removing(key, level, hash) else { return nil } + self = r.replacement + return r.old + } + let r = find(level, key, hash, forInsert: false) + switch r { + case .found(let bucket, let slot): + return _removeItemFromUniqueLeafNode(level, bucket, slot) { $0.move() } + case .notFound, .newCollision, .expansion: + return nil + case .descend(let bucket, let slot): + let (old, needsInlining) = update { + let child = $0.childPtr(at: slot) + let old = child.pointee.remove(key, level.descend(), hash) + guard old != nil else { return (old, false) } + let needsInlining = child.pointee.hasSingletonItem + return (old, needsInlining) + } + guard old != nil else { return nil } + _fixupUniqueAncestorAfterItemRemoval( + slot, { _ in bucket }, needsInlining: needsInlining) + return old + } + } +} + +extension _Node { + @inlinable + internal func removing( + _ key: Key, _ level: _Level, _ hash: _Hash + ) -> (replacement: _Node, old: Element)? { + let r = find(level, key, hash, forInsert: false) + switch r { + case .found(let bucket, let slot): + return _removingItemFromLeaf(level, slot, bucket) + case .notFound, .newCollision, .expansion: + return nil + case .descend(let bucket, let slot): + let r = read { $0[child: slot].removing(key, level.descend(), hash) } + guard let r = r else { return nil } + return ( + _fixedUpAncestorAfterItemRemoval(level, slot, bucket, r.replacement), + r.old) + } + } +} + +extension _Node { + @inlinable + internal mutating func remove( + _ level: _Level, at path: _UnsafePath + ) -> Element { + defer { _invariantCheck() } + guard self.isUnique() else { + let r = removing(level, at: path) + self = r.replacement + return r.old + } + if level == path.level { + let slot = path.currentItemSlot + let bucket = read { $0.itemBucket(at: slot) } + return _removeItemFromUniqueLeafNode( + level, bucket, slot, by: { $0.move() }) + } + let slot = path.childSlot(at: level) + let (item, needsInlining) = update { + let child = $0.childPtr(at: slot) + let item = child.pointee.remove(level.descend(), at: path) + return (item, child.pointee.hasSingletonItem) + } + _fixupUniqueAncestorAfterItemRemoval( + slot, + { $0.read { $0.childMap.bucket(at: slot) } }, + needsInlining: needsInlining) + return item + } + + @inlinable + internal func removing( + _ level: _Level, at path: _UnsafePath + ) -> (replacement: _Node, old: Element) { + if level == path.level { + let slot = path.currentItemSlot + let bucket = read { $0.itemBucket(at: slot) } + return _removingItemFromLeaf(level, slot, bucket) + } + let slot = path.childSlot(at: level) + let (bucket, r) = read { + ($0.childMap.bucket(at: slot), + $0[child: slot].removing(level.descend(), at: path)) + } + return ( + _fixedUpAncestorAfterItemRemoval(level, slot, bucket, r.replacement), + r.old + ) + } +} + +extension _Node { + @inlinable + internal mutating func _removeItemFromUniqueLeafNode( + _ level: _Level, + _ bucket: _Bucket, + _ slot: _Slot, + by remover: (UnsafeMutablePointer) -> R + ) -> R { + assert(isUnique()) + let result = removeItem(at: slot, bucket, by: remover) + if isAtrophied { + self = removeSingletonChild() + } + if level.isAtRoot, isCollisionNode, hasSingletonItem { + self._convertToRegularNode() + } + return result + } + + @inlinable + internal func _removingItemFromLeaf( + _ level: _Level, _ slot: _Slot, _ bucket: _Bucket + ) -> (replacement: _Node, old: Element) { + // Don't copy the node if we'd immediately discard it. + let willAtrophy = read { + $0.itemCount == 1 + && $0.childCount == 1 + && $0[child: .zero].isCollisionNode + } + if willAtrophy { + return read { (replacement: $0[child: .zero], old: $0[item: .zero]) } + } + var node = self.copy() + let old = node.removeItem(at: slot, bucket) { $0.move() } + if level.isAtRoot, node.isCollisionNode, node.hasSingletonItem { + node._convertToRegularNode() + } + node._invariantCheck() + return (node, old) + } +} + +extension _Node { + @inlinable + internal mutating func _fixupUniqueAncestorAfterItemRemoval( + _ slot: _Slot, + _ bucket: (inout Self) -> _Bucket, + needsInlining: Bool + ) { + assert(isUnique()) + count &-= 1 + if needsInlining { + ensureUnique(isUnique: true, withFreeSpace: Self.spaceForInlinedChild) + let bucket = bucket(&self) + var child = self.removeChild(at: slot, bucket) + let item = child.removeSingletonItem() + insertItem(item, bucket) + } + if isAtrophied { + self = removeSingletonChild() + } + } + + @inlinable + internal func _fixedUpAncestorAfterItemRemoval( + _ level: _Level, + _ slot: _Slot, + _ bucket: _Bucket, + _ newChild: __owned _Node + ) -> _Node { + var newChild = newChild + if newChild.hasSingletonItem { + var node = copy(withFreeSpace: Self.spaceForInlinedChild) + _ = node.removeChild(at: slot, bucket) + let item = newChild.removeSingletonItem() + node.insertItem(item, bucket) + node._invariantCheck() + return node + } + if newChild.isCollisionNode && self.hasSingletonChild { + // Don't return an atrophied node. + return newChild + } + var node = copy() + node.update { $0[child: slot] = newChild } + node.count &-= 1 + node._invariantCheck() + return node + } +} + +extension _Node { + @inlinable + internal mutating func _convertToRegularNode() { + assert(isCollisionNode && hasSingletonItem) + assert(isUnique()) + update { + let hash = _Hash($0[item: .zero].key) + $0.itemMap = _Bitmap(hash[.top]) + $0.childMap = .empty + } + } +} diff --git a/Sources/PersistentCollections/Node/_Node+Transform.swift b/Sources/PersistentCollections/Node/_Node+Transform.swift new file mode 100644 index 00000000..ac838d7b --- /dev/null +++ b/Sources/PersistentCollections/Node/_Node+Transform.swift @@ -0,0 +1,65 @@ +//===----------------------------------------------------------------------===// +// +// 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 _Node { + @inlinable + internal func mapValues( + _ transform: (Value) throws -> T + ) rethrows -> _Node { + let c = self.count + return try read { source in + var result = _Node.allocate( + itemMap: source.itemMap, + childMap: source.childMap, + count: c, + initializingWith: { _, _ in } + ).node + try result.update { target in + let sourceItems = source.reverseItems + let targetItems = target.reverseItems + assert(sourceItems.count == targetItems.count) + + let sourceChildren = source.children + let targetChildren = target.children + assert(sourceChildren.count == targetChildren.count) + + var i = 0 + var j = 0 + + var success = false + + defer { + if !success { + targetItems.prefix(i).deinitialize() + targetChildren.prefix(j).deinitialize() + target.clear() + } + } + + while i < targetItems.count { + let key = sourceItems[i].key + let value = try transform(sourceItems[i].value) + targetItems.initializeElement(at: i, to: (key, value)) + i += 1 + } + while j < targetChildren.count { + let child = try sourceChildren[j].mapValues(transform) + targetChildren.initializeElement(at: j, to: child) + j += 1 + } + success = true + } + return result + } + } +} diff --git a/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift b/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift index 146a7cd4..79751728 100644 --- a/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift +++ b/Sources/PersistentCollections/Node/_Node+UnsafeHandle.swift @@ -178,12 +178,12 @@ extension _Node.UnsafeHandle { } @inlinable @inline(__always) - internal var childEnd: _Slot { - _header.pointee.childEnd + internal var childrenEndSlot: _Slot { + _header.pointee.childrenEndSlot } @inlinable - internal var _children: UnsafeMutableBufferPointer<_Node> { + internal var children: UnsafeMutableBufferPointer<_Node> { UnsafeMutableBufferPointer(start: _childrenStart, count: childCount) } @@ -195,8 +195,13 @@ extension _Node.UnsafeHandle { @inlinable internal subscript(child slot: _Slot) -> _Node { - unsafeAddress { UnsafePointer(childPtr(at: slot)) } - nonmutating unsafeMutableAddress { childPtr(at: slot) } + unsafeAddress { + UnsafePointer(childPtr(at: slot)) + } + nonmutating unsafeMutableAddress { + assertMutable() + return childPtr(at: slot) + } } @inlinable @@ -222,8 +227,8 @@ extension _Node.UnsafeHandle { } @inlinable @inline(__always) - internal var itemEnd: _Slot { - _header.pointee.itemEnd + internal var itemsEndSlot: _Slot { + _header.pointee.itemsEndSlot } @inlinable @@ -240,8 +245,19 @@ extension _Node.UnsafeHandle { @inlinable internal subscript(item slot: _Slot) -> Element { - unsafeAddress { UnsafePointer(itemPtr(at: slot)) } - unsafeMutableAddress { itemPtr(at: slot) } + unsafeAddress { + UnsafePointer(itemPtr(at: slot)) + } + nonmutating unsafeMutableAddress { + assertMutable() + return itemPtr(at: slot) + } + } + + @inlinable + internal func clear() { + assertMutable() + _header.pointee.clear() } } diff --git a/Sources/PersistentCollections/Node/_Node.swift b/Sources/PersistentCollections/Node/_Node.swift index 876c22ab..f225bf84 100644 --- a/Sources/PersistentCollections/Node/_Node.swift +++ b/Sources/PersistentCollections/Node/_Node.swift @@ -82,13 +82,17 @@ extension _Node { extension _Node { @inlinable @inline(__always) - internal func read(_ body: (UnsafeHandle) -> R) -> R { - UnsafeHandle.read(raw.storage, body) + internal func read( + _ body: (UnsafeHandle) throws -> R + ) rethrows -> R { + try UnsafeHandle.read(raw.storage, body) } @inlinable @inline(__always) - internal mutating func update(_ body: (UnsafeHandle) -> R) -> R { - UnsafeHandle.update(raw.storage, body) + internal mutating func update( + _ body: (UnsafeHandle) throws -> R + ) rethrows -> R { + try UnsafeHandle.update(raw.storage, body) } } diff --git a/Sources/PersistentCollections/Node/_RawNode+UnsafeHandle.swift b/Sources/PersistentCollections/Node/_RawNode+UnsafeHandle.swift index c6b59b98..169e9a35 100644 --- a/Sources/PersistentCollections/Node/_RawNode+UnsafeHandle.swift +++ b/Sources/PersistentCollections/Node/_RawNode+UnsafeHandle.swift @@ -59,8 +59,8 @@ extension _RawNode.UnsafeHandle { } @inline(__always) - internal var childEnd: _Slot { - _header.pointee.childEnd + internal var childrenEndSlot: _Slot { + _header.pointee.childrenEndSlot } @inline(__always) @@ -74,8 +74,8 @@ extension _RawNode.UnsafeHandle { } @inline(__always) - internal var itemEnd: _Slot { - _header.pointee.itemEnd + internal var itemsEndSlot: _Slot { + _header.pointee.itemsEndSlot } @inline(__always) @@ -85,12 +85,12 @@ extension _RawNode.UnsafeHandle { internal subscript(child slot: _Slot) -> _RawNode { unsafeAddress { - assert(slot < childEnd) + assert(slot < childrenEndSlot) return _childrenStart + slot.value } } - internal var _children: UnsafeBufferPointer<_RawNode> { + internal var children: UnsafeBufferPointer<_RawNode> { UnsafeBufferPointer(start: _childrenStart, count: childCount) } } diff --git a/Sources/PersistentCollections/Node/_RawNode.swift b/Sources/PersistentCollections/Node/_RawNode.swift index 9cbc9848..fe06e03c 100644 --- a/Sources/PersistentCollections/Node/_RawNode.swift +++ b/Sources/PersistentCollections/Node/_RawNode.swift @@ -59,15 +59,15 @@ extension _RawNode { var n = self.unmanaged while l < path.level { let slot = path.ancestors[l] - precondition(slot < n.childEnd) + precondition(slot < n.childrenEndSlot) n = n.unmanagedChild(at: slot) l = l.descend() } precondition(n == path.node) if path._isItem { - precondition(path.nodeSlot < n.itemEnd) + precondition(path.nodeSlot < n.itemsEndSlot) } else { - precondition(path.nodeSlot <= n.childEnd) + precondition(path.nodeSlot <= n.childrenEndSlot) } } } diff --git a/Sources/PersistentCollections/Node/_StorageHeader.swift b/Sources/PersistentCollections/Node/_StorageHeader.swift index 21749d71..fa56caa9 100644 --- a/Sources/PersistentCollections/Node/_StorageHeader.swift +++ b/Sources/PersistentCollections/Node/_StorageHeader.swift @@ -88,12 +88,12 @@ extension _StorageHeader { } @inlinable @inline(__always) - internal var childEnd: _Slot { + internal var childrenEndSlot: _Slot { _Slot(childCount) } @inlinable @inline(__always) - internal var itemEnd: _Slot { + internal var itemsEndSlot: _Slot { _Slot(itemCount) } @@ -105,9 +105,64 @@ extension _StorageHeader { } set { assert(isCollisionNode || childMap.isEmpty) - assert(newValue > 0 && newValue < UInt32.max) - itemMap._value = UInt32(truncatingIfNeeded: newValue) + assert(newValue > 0 && newValue < _Bitmap.Value.max) + itemMap._value = _Bitmap.Value(truncatingIfNeeded: newValue) childMap = itemMap } } } + +extension _StorageHeader { + @inlinable + internal mutating func clear() { + itemMap = .empty + childMap = .empty + bytesFree = byteCapacity + } +} + +extension _StorageHeader { + @inlinable + internal static func counts( + itemMap: _Bitmap, childMap: _Bitmap + ) -> (itemCount: Int, childCount: Int) { + if itemMap == childMap { + return (Int(truncatingIfNeeded: itemMap._value), 0) + } + return (itemMap.count, childMap.count) + } + + @inlinable + internal func bitmapsForInsertingItem( + at slot: _Slot, + _ bucket: _Bucket + ) -> (itemMap: _Bitmap, childMap: _Bitmap) { + var itemMap = self.itemMap + var childMap = self.childMap + if bucket.isInvalid { + assert(isCollisionNode) + itemMap._value += 1 + childMap = itemMap + } else { + assert(!isCollisionNode) + assert(!itemMap.contains(bucket) && !childMap.contains(bucket)) + itemMap.insert(bucket) + assert(itemMap.slot(of: bucket) == slot) + } + return (itemMap, childMap) + } + + @inlinable + internal func bitmapsForNewCollision( + 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) + } +} diff --git a/Sources/PersistentCollections/Node/_UnmanagedNode.swift b/Sources/PersistentCollections/Node/_UnmanagedNode.swift index 1928686d..724efca8 100644 --- a/Sources/PersistentCollections/Node/_UnmanagedNode.swift +++ b/Sources/PersistentCollections/Node/_UnmanagedNode.swift @@ -85,12 +85,12 @@ extension _UnmanagedNode { } @inlinable - internal var itemEnd: _Slot { + internal var itemsEndSlot: _Slot { withRaw { _Slot($0.header.itemCount) } } @inlinable - internal var childEnd: _Slot { + internal var childrenEndSlot: _Slot { withRaw { _Slot($0.header.childCount) } } diff --git a/Sources/PersistentCollections/Node/_UnsafePath.swift b/Sources/PersistentCollections/Node/_UnsafePath.swift index d507d343..05faf7b2 100644 --- a/Sources/PersistentCollections/Node/_UnsafePath.swift +++ b/Sources/PersistentCollections/Node/_UnsafePath.swift @@ -67,7 +67,7 @@ extension _UnsafePath { _ node: _UnmanagedNode, childSlot: _Slot ) { - assert(childSlot < node.childEnd) + assert(childSlot < node.childrenEndSlot) self.level = level self.ancestors = ancestors self.node = node @@ -82,7 +82,7 @@ extension _UnsafePath { _ node: _UnmanagedNode, itemSlot: _Slot ) { - assert(itemSlot < node.itemEnd) + assert(itemSlot < node.itemsEndSlot) self.level = level self.ancestors = ancestors self.node = node @@ -270,7 +270,7 @@ extension _UnsafePath { // As a special exception, this allows slot to equal the item count. // This can happen for paths that address the position a new item might be // inserted later. - assert(slot <= node.itemEnd) + assert(slot <= node.itemsEndSlot) nodeSlot = slot _isItem = true } @@ -284,7 +284,7 @@ extension _UnsafePath { internal mutating func selectChild(at slot: _Slot) { // As a special exception, this allows slot to equal the child count. // This is equivalent to a call to `selectEnd()`. - assert(slot <= node.childEnd) + assert(slot <= node.childrenEndSlot) nodeSlot = slot _isItem = false } @@ -296,7 +296,7 @@ extension _UnsafePath { @usableFromInline @_effects(releasenone) internal mutating func selectEnd() { - nodeSlot = node.childEnd + nodeSlot = node.childrenEndSlot _isItem = false } @@ -382,7 +382,7 @@ extension _UnsafePath { mutating func selectNextItem() -> Bool { assert(isOnItem) nodeSlot = nodeSlot.next() - if nodeSlot < node.itemEnd { return true } + if nodeSlot < node.itemsEndSlot { return true } nodeSlot = .zero _isItem = false return false @@ -396,10 +396,10 @@ extension _UnsafePath { /// valid. mutating func selectNextChild() -> Bool { assert(!isOnItem) - let childEnd = node.childEnd - guard nodeSlot < childEnd else { return false } + let childrenEndSlot = node.childrenEndSlot + guard nodeSlot < childrenEndSlot else { return false } nodeSlot = nodeSlot.next() - return nodeSlot < childEnd + return nodeSlot < childrenEndSlot } } @@ -430,13 +430,13 @@ extension _UnsafePath { assert(isOnChild) while true { descend() - let childEnd = node.childEnd - guard childEnd > .zero else { break } - selectChild(at: childEnd.previous()) + let childrenEndSlot = node.childrenEndSlot + guard childrenEndSlot > .zero else { break } + selectChild(at: childrenEndSlot.previous()) } - let itemEnd = node.itemEnd - assert(itemEnd > .zero) - selectItem(at: itemEnd.previous()) + let itemsEndSlot = node.itemsEndSlot + assert(itemsEndSlot > .zero) + selectItem(at: itemsEndSlot.previous()) } /// Find the next item in a preorder walk in the tree following the currently @@ -453,7 +453,7 @@ extension _UnsafePath { return true } if ascendToNearestAncestor( - under: root, where: { $1.next() < $0.childEnd } + under: root, where: { $1.next() < $0.childrenEndSlot } ) { let r = selectNextChild() assert(r) @@ -482,7 +482,7 @@ extension _UnsafePath { return true case (false, false): if node.hasItems { - selectItem(at: node.itemEnd.previous()) + selectItem(at: node.itemsEndSlot.previous()) return true } case (true, false): @@ -500,7 +500,7 @@ extension _UnsafePath { return true } if node.hasItems { - selectItem(at: node.itemEnd.previous()) + selectItem(at: node.itemsEndSlot.previous()) return true } return false @@ -521,7 +521,7 @@ extension _RawNode { if level < path.level { let childSlot = path.childSlot(at: level) return read { - let prefix = $0._children[.. Int { read { - assert(start < $0.itemEnd) + assert(start < $0.itemsEndSlot) assert(level < end.level) let childSlot = end.childSlot(at: level) - let children = $0._children + let children = $0.children let prefix = children[.. Bool + ) rethrows -> Self { + var result: PersistentDictionary = [:] + for item in self { + guard try isIncluded(item) else { continue } + // FIXME: We could recover the key's hash from self. + // (As many bits of it as we need to insert it into the new tree.) + // However, this requires a series of `UInt32._bit(ranked:)` invocations + // that may or may not be meaningfully better than simply rehashing the + // key. + let hash = _Hash(item.key) + let r = result._root.updateValue(item.value, forKey: item.key, .top, hash) + assert(r == nil) + } + return result + } +} diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift new file mode 100644 index 00000000..5fbc3066 --- /dev/null +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Initializers.swift @@ -0,0 +1,113 @@ +//===----------------------------------------------------------------------===// +// +// 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 PersistentDictionary { + @inlinable + public init() { + self.init(_new: _Node(storage: _emptySingleton, count: 0)) + } + + @inlinable + public init(_ other: PersistentDictionary) { + self = other + } + + @inlinable + public init( + uniqueKeysWithValues keysAndValues: S + ) where S.Element == (Key, Value) { + self.init() + for (key, value) in keysAndValues { + let hash = _Hash(key) + let unique = nil == _root.updateValue(value, forKey: key, .top, hash) + precondition(unique, "Duplicate key: '\(key)'") + } + _invariantCheck() + } + + @_disfavoredOverload // https://github.com/apple/swift-collections/issues/125 + @inlinable + public init( + uniqueKeysWithValues keysAndValues: S + ) where S.Element == Element { + if S.self == Self.self { + self = keysAndValues as! Self + return + } + self.init( + uniqueKeysWithValues: keysAndValues.lazy.map { ($0.key, $0.value ) }) + } + + @inlinable + public init( + uniqueKeys keys: Keys, + values: Values + ) where Keys.Element == Key, Values.Element == Value { + self.init(uniqueKeysWithValues: zip(keys, values)) + } + + public init( + _ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows where S.Element == (Key, Value) { + self.init() + try self.merge(keysAndValues, uniquingKeysWith: combine) + } + + @_disfavoredOverload // https://github.com/apple/swift-collections/issues/125 + public init( + _ keysAndValues: S, uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows where S.Element == Element { + try self.init( + keysAndValues.lazy.map { ($0.key, $0.value) }, + uniquingKeysWith: combine) + } +} + +extension PersistentDictionary { + @inlinable @inline(__always) + public init( + grouping values: S, + by keyForValue: (S.Element) throws -> Key + ) rethrows + where Value: RangeReplaceableCollection, Value.Element == S.Element + { + try self.init(_grouping: values, by: keyForValue) + } + + @inlinable @inline(__always) + public init( + grouping values: S, + by keyForValue: (S.Element) throws -> Key + ) rethrows + where Value == [S.Element] + { + // Note: this extra overload is necessary to make type inference work + // for the `Value` type -- we want it to default to `[S.Element`]. + // (https://github.com/apple/swift-collections/issues/139) + try self.init(_grouping: values, by: keyForValue) + } + + @inlinable + internal init( + _grouping values: S, + by keyForValue: (S.Element) throws -> Key + ) rethrows + where Value: RangeReplaceableCollection, Value.Element == S.Element + { + self.init() + for value in values { + let key = try keyForValue(value) + self.updateValue(forKey: key, default: Value()) { array in + array.append(value) + } + } + } +} diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift index 210ed123..6386e402 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Keys.swift @@ -9,14 +9,118 @@ // //===----------------------------------------------------------------------===// -// TODO: implement a custom `Keys` view rather than relying on an array representation extension PersistentDictionary { /// A view of a dictionary’s keys. - public typealias Keys = [Key] + @frozen + public struct Keys { + @usableFromInline + internal typealias _Node = PersistentCollections._Node + + @usableFromInline + internal var _base: PersistentDictionary + + @inlinable + internal init(_base: PersistentDictionary) { + self._base = _base + } + } /// A collection containing just the keys of the dictionary. @inlinable - public var keys: Self.Keys /* { get } */ { - self.map { $0.key } + public var keys: Keys { + Keys(_base: self) + } +} + + +extension PersistentDictionary.Keys: Sequence { + public typealias Element = Key + + @frozen + public struct Iterator: IteratorProtocol { + public typealias Element = Key + + @usableFromInline + internal var _base: PersistentDictionary.Iterator + + @inlinable + internal init(_base: PersistentDictionary.Iterator) { + self._base = _base + } + + @inlinable + public mutating func next() -> Element? { + _base.next()?.key + } + } + + @inlinable + public func makeIterator() -> Iterator { + Iterator(_base: _base.makeIterator()) + } + + @inlinable + public func _customContainsEquatableElement( + _ element: Element + ) -> Bool? { + _base._root.containsKey(.top, element, _Hash(element)) + } +} + +extension PersistentDictionary.Keys: BidirectionalCollection { + public typealias Index = PersistentDictionary.Index + + @inlinable + public var isEmpty: Bool { _base.isEmpty } + + @inlinable + public var count: Int { _base.count } + + @inlinable + public var startIndex: Index { _base.startIndex } + + @inlinable + public var endIndex: Index { _base.endIndex } + + @inlinable + public subscript(index: Index) -> Element { + _base[index].key + } + + @inlinable + public func formIndex(after i: inout Index) { + _base.formIndex(after: &i) + } + + @inlinable + public func formIndex(before i: inout Index) { + _base.formIndex(before: &i) + } + + @inlinable + public func index(after i: Index) -> Index { + _base.index(after: i) + } + + @inlinable + public func index(before i: Index) -> Index { + _base.index(before: i) + } + + @inlinable + public func index(_ i: Index, offsetBy distance: Int) -> Index { + _base.index(i, offsetBy: distance) + } + + @inlinable + public func index( + _ i: Index, offsetBy distance: Int, limitedBy limit: Index + ) -> Index? { + _base.index(i, offsetBy: distance, limitedBy: limit) + } + + @inlinable + public func distance(from start: Index, to end: Index) -> Int { + _base.distance(from: start, to: end) } } diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+MapValues.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+MapValues.swift new file mode 100644 index 00000000..16008a83 --- /dev/null +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+MapValues.swift @@ -0,0 +1,39 @@ +//===----------------------------------------------------------------------===// +// +// 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 PersistentDictionary { + @inlinable + public func mapValues( + _ transform: (Value) throws -> T + ) rethrows -> PersistentDictionary { + let transformed = try _root.mapValues(transform) + return PersistentDictionary(_new: transformed) + } + + @inlinable + public func compactMapValues( + _ transform: (Value) throws -> T? + ) rethrows -> PersistentDictionary { + var result: PersistentDictionary = [:] + for (key, value) in self { + guard let value = try transform(value) else { continue } + // FIXME: We could recover the key's hash from self. + // (As many bits of it as we need to insert it into the new tree.) + // However, this requires a series of `UInt32._bit(ranked:)` invocations + // that may or may not be meaningfully better than simply rehashing the + // key. + let hash = _Hash(key) + let r = result._root.updateValue(value, forKey: key, .top, hash) + assert(r == nil) + } + return result + } +} diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift new file mode 100644 index 00000000..bbedd0f9 --- /dev/null +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Merge.swift @@ -0,0 +1,62 @@ +//===----------------------------------------------------------------------===// +// +// 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 PersistentDictionary { + @inlinable + public mutating func merge( + _ keysAndValues: __owned S, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows where S.Element == (Key, Value) { + for (key, value) in keysAndValues { + try self.updateValue(forKey: key) { target in + if let old = target { + target = try combine(old, value) + } else { + target = value + } + } + } + } + + @_disfavoredOverload // https://github.com/apple/swift-collections/issues/125 + @inlinable + public mutating func merge( + _ keysAndValues: __owned S, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows where S.Element == Element { + try merge( + keysAndValues.lazy.map { ($0.key, $0.value) }, + uniquingKeysWith: combine) + } + + @inlinable + public func merging( + _ other: __owned S, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows -> Self + where S.Element == (Key, Value) { + var copy = self + try copy.merge(other, uniquingKeysWith: combine) + return copy + } + + @_disfavoredOverload // https://github.com/apple/swift-collections/issues/125 + @inlinable + public func merging( + _ other: __owned S, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows -> Self + where S.Element == Element { + var copy = self + try copy.merge(other, uniquingKeysWith: combine) + return copy + } +} diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Sequence.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Sequence.swift index 750ad274..7de86638 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Sequence.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Sequence.swift @@ -47,7 +47,7 @@ extension PersistentDictionary: Sequence { $0.hasItems ? $0.reverseItems.reversed().makeIterator() : nil } self._pathTop = _root.read { - $0.hasChildren ? $0._children.makeIterator() : nil + $0.hasChildren ? $0.children.makeIterator() : nil } } } @@ -81,7 +81,7 @@ extension PersistentDictionary.Iterator: IteratorProtocol { } if nextNode.read({ $0.hasChildren }) { _pathRest.append(_pathTop!) - _pathTop = nextNode.read { $0._children.makeIterator() } // 💥ILLEGAL + _pathTop = nextNode.read { $0.children.makeIterator() } // 💥ILLEGAL } if nextNode.read({ $0.hasItems }) { _itemIterator = nextNode.read { $0.reverseItems.reversed().makeIterator() } // 💥ILLEGAL diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift index 0952f846..27d7d2d7 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary+Values.swift @@ -9,14 +9,147 @@ // //===----------------------------------------------------------------------===// -// TODO: implement a custom `Values` view rather than relying on an array representation extension PersistentDictionary { /// A view of a dictionary’s values. - public typealias Values = [Value] + @frozen + public struct Values { + @usableFromInline + internal typealias _Node = PersistentCollections._Node + + @usableFromInline + internal var _base: PersistentDictionary + + @inlinable + internal init(_base: PersistentDictionary) { + self._base = _base + } + } /// A collection containing just the values of the dictionary. @inlinable - public var values: Self.Values /* { get set } */ { - self.map { $0.value } + public var values: Values { + get { + Values(_base: self) + } + set { // FIXME: Consider removing + self = newValue._base + } + _modify { // FIXME: Consider removing + var values = Values(_base: self) + self = Self() + defer { + self = values._base + } + yield &values + } + } +} + +extension PersistentDictionary.Values: Sequence { + public typealias Element = Value + + @frozen + public struct Iterator: IteratorProtocol { + public typealias Element = Value + + @usableFromInline + internal var _base: PersistentDictionary.Iterator + + @inlinable + internal init(_base: PersistentDictionary.Iterator) { + self._base = _base + } + + @inlinable + public mutating func next() -> Element? { + _base.next()?.value + } + } + + @inlinable + public func makeIterator() -> Iterator { + Iterator(_base: _base.makeIterator()) + } +} + +// Note: This cannot be a MutableCollection because its subscript setter +// needs to invalidate indices. +extension PersistentDictionary.Values: BidirectionalCollection { + public typealias Index = PersistentDictionary.Index + + @inlinable + public var isEmpty: Bool { _base.isEmpty } + + @inlinable + public var count: Int { _base.count } + + @inlinable + public var startIndex: Index { _base.startIndex } + + @inlinable + public var endIndex: Index { _base.endIndex } + + @inlinable + public subscript(index: Index) -> Element { + get { + _base[index].value + } + set { // FIXME: Consider removing + precondition(_base._isValid(index), "Invalid index") + precondition(index._path.isOnItem, "Cannot set value at end index") + let (leaf, slot) = _base._root.ensureUnique(level: .top, at: index._path) + _Node.UnsafeHandle.update(leaf) { $0[item: slot].value = newValue } + _base._invalidateIndices() + } + _modify { // FIXME: Consider removing + precondition(_base._isValid(index), "Invalid index") + precondition(index._path.isOnItem, "Cannot set value at end index") + let (leaf, slot) = _base._root.ensureUnique(level: .top, at: index._path) + var item = _Node.UnsafeHandle.update(leaf) { $0.itemPtr(at: slot).move() } + defer { + _Node.UnsafeHandle.update(leaf) { + $0.itemPtr(at: slot).initialize(to: item) + } + _base._invalidateIndices() + } + yield &item.value + } + } + + @inlinable + public func formIndex(after i: inout Index) { + _base.formIndex(after: &i) + } + + @inlinable + public func formIndex(before i: inout Index) { + _base.formIndex(before: &i) + } + + @inlinable + public func index(after i: Index) -> Index { + _base.index(after: i) + } + + @inlinable + public func index(before i: Index) -> Index { + _base.index(before: i) + } + + @inlinable + public func index(_ i: Index, offsetBy distance: Int) -> Index { + _base.index(i, offsetBy: distance) + } + + @inlinable + public func index( + _ i: Index, offsetBy distance: Int, limitedBy limit: Index + ) -> Index? { + _base.index(i, offsetBy: distance, limitedBy: limit) + } + + @inlinable + public func distance(from start: Index, to end: Index) -> Int { + _base.distance(from: start, to: end) } } diff --git a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift index 768df3bd..73736364 100644 --- a/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift +++ b/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift @@ -38,44 +38,11 @@ public struct PersistentDictionary where Key: Hashable { } extension PersistentDictionary { - @inlinable - public init() { - self.init(_new: _Node(storage: _emptySingleton, count: 0)) - } - - @inlinable - public init(_ other: PersistentDictionary) { - self = other - } - @inlinable public func _invariantCheck() { _root._fullInvariantCheck(.top, _Hash(_value: 0)) } - - @inlinable - @inline(__always) - public init( - uniqueKeysWithValues keysAndValues: S - ) where S.Element == (Key, Value) { - self.init() - for (key, value) in keysAndValues { - let unique = updateValue(value, forKey: key) == nil - precondition(unique, "Duplicate key: '\(key)'") - } - _invariantCheck() - } - - @inlinable - @inline(__always) - public init( - uniqueKeys keys: Keys, - values: Values - ) where Keys.Element == Key, Values.Element == Value { - self.init(uniqueKeysWithValues: zip(keys, values)) - } - /// Accesses the value associated with the given key for reading and writing. /// /// This *key-based* subscript returns the value for the given key if the key @@ -249,6 +216,7 @@ extension PersistentDictionary { } } + // FIXME: New addition; needs discussion @inlinable public func contains(_ key: Key) -> Bool { _root.containsKey(.top, key, _Hash(key)) @@ -329,6 +297,31 @@ extension PersistentDictionary { return copy } + // FIXME: New addition; needs discussion + @inlinable @inline(__always) + public mutating func updateValue( + forKey key: Key, + with body: (inout Value?) throws -> R + ) rethrows -> R { + try body(&self[key]) + } + + @inlinable + public mutating func updateValue( + forKey key: Key, + default defaultValue: @autoclosure () -> Value, + with body: (inout Value) throws -> R + ) rethrows -> R { + let hash = _Hash(key) + let r = _root.insertValue(forKey: key, .top, hash, with: defaultValue) + if r.inserted { + _invalidateIndices() + } + return try _Node.UnsafeHandle.update(r.leaf) { + try body(&$0[item: r.slot].value) + } + } + /// Removes the given key and its associated value from the dictionary. /// /// If the key is found in the dictionary, this method returns the key's diff --git a/Sources/PriorityQueueModule/Heap+Invariants.swift b/Sources/PriorityQueueModule/Heap+Invariants.swift index 418bfe8c..ab1d891a 100644 --- a/Sources/PriorityQueueModule/Heap+Invariants.swift +++ b/Sources/PriorityQueueModule/Heap+Invariants.swift @@ -9,10 +9,14 @@ // //===----------------------------------------------------------------------===// -import Swift +import _CollectionsUtilities extension Heap { - #if COLLECTIONS_INTERNAL_CHECKS + public static var _isConsistencyCheckingEnabled: Bool { + _isCollectionsInternalCheckingEnabled + } + + #if COLLECTIONS_INTERNAL_CHECKSx /// Visits each item in the heap in depth-first order, verifying that the /// contents satisfy the min-max heap property. @inlinable diff --git a/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift b/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift new file mode 100644 index 00000000..79a49dd1 --- /dev/null +++ b/Sources/_CollectionsTestSupport/Utilities/DictionaryAPIChecker.swift @@ -0,0 +1,132 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +public protocol DictionaryAPIChecker { + associatedtype Key + associatedtype Value + associatedtype Index + + typealias Element = (key: Key, value: Value) + + associatedtype Keys: Collection where Keys.Element == Key + var keys: Keys { get } + + // `Values` ought to be a `MutableCollection` when possible, with `values` + // providing a setter. Unfortunately, tree-based dictionaries need to + // invalidate indices when mutating keys. + associatedtype Values: Collection where Values.Element == Value + var values: Values { get } + + var isEmpty: Bool { get } + var count: Int { get } + + func index(forKey key: Key) -> Index? + + subscript(key: Key) -> Value? { get set } + subscript( + key: Key, + default defaultValue: @autoclosure () -> Value + ) -> Value { get set } + + mutating func updateValue(_ value: Value, forKey key: Key) -> Value? + mutating func removeValue(forKey key: Key) -> Value? + mutating func remove(at index: Index) -> Element + + init() + + init( + uniqueKeysWithValues keysAndValues: S + ) where S.Element == (Key, Value) + + init( + uniqueKeys keys: Keys, + values: Values + ) where Keys.Element == Key, Values.Element == Value + + init( + _ keysAndValues: S, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows where S.Element == (Key, Value) + + mutating func merge( + _ keysAndValues: __owned S, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows where S.Element == (Key, Value) + + __consuming func merging( + _ other: __owned S, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows -> Self where S.Element == (Key, Value) + + func filter( + _ isIncluded: (Element) throws -> Bool + ) rethrows -> Self + +#if false + // We can't express these as protocol requirements: + func mapValues( + _ transform: (Value) throws -> T + ) rethrows -> Self + + func compactMapValues( + _ transform: (Value) throws -> T? + ) rethrows -> Self + + init( + grouping values: S, + by keyForValue: (S.Element) throws -> Key + ) rethrows where Value: RangeReplaceableCollection, Value.Element == S.Element + + public init( + grouping values: S, + by keyForValue: (S.Element) throws -> Key + ) rethrows where Value == [S.Element] +#endif + + // Extras (not in the Standard Library) + + mutating func updateValue( + forKey key: Key, + default defaultValue: @autoclosure () -> Value, + with body: (inout Value) throws -> R + ) rethrows -> R + + init( + uniqueKeysWithValues keysAndValues: S + ) where S.Element == Element + + init( + _ keysAndValues: S, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows where S.Element == Element + + mutating func merge( + _ keysAndValues: __owned S, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows where S.Element == Element + + __consuming func merging( + _ other: __owned S, + uniquingKeysWith combine: (Value, Value) throws -> Value + ) rethrows -> Self where S.Element == Element + + #if false + // Potential additions implemented by PersistentDictionary: + + func contains(_ key: Key) -> Bool + + mutating func updateValue( + forKey key: Key, + with body: (inout Value?) throws -> R + ) rethrows -> R + + #endif +} diff --git a/Sources/_CollectionsUtilities/Debugging.swift b/Sources/_CollectionsUtilities/Debugging.swift new file mode 100644 index 00000000..0006548e --- /dev/null +++ b/Sources/_CollectionsUtilities/Debugging.swift @@ -0,0 +1,19 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +@inlinable @inline(__always) +public var _isCollectionsInternalCheckingEnabled: Bool { +#if COLLECTIONS_INTERNAL_CHECKS + return true +#else + return false +#endif +} diff --git a/Sources/_CollectionsUtilities/Integer tricks.swift b/Sources/_CollectionsUtilities/Integer tricks.swift index c9041769..f081a87c 100644 --- a/Sources/_CollectionsUtilities/Integer tricks.swift +++ b/Sources/_CollectionsUtilities/Integer tricks.swift @@ -69,3 +69,48 @@ extension UInt32 { return UInt(truncatingIfNeeded: shift) } } + +extension UInt16 { + @inlinable @inline(__always) + internal var _nonzeroBitCount: Self { + Self(truncatingIfNeeded: nonzeroBitCount) + } + + @inlinable @inline(__always) + public func _rank(ofBit bit: UInt) -> Int { + assert(bit < Self.bitWidth) + let mask: Self = (1 &<< bit) &- 1 + return (self & mask).nonzeroBitCount + } + + // Returns the position of the `n`th set bit in `self`, i.e., the bit with + // rank `n`. + @_effects(releasenone) + public func _bit(ranked n: Int) -> UInt? { + assert(n >= 0 && n < Self.bitWidth) + var shift: Self = 0 + var n: Self = UInt16(truncatingIfNeeded: n) + let c8 = ((self &>> shift) & 0xFF)._nonzeroBitCount + if n >= c8 { + shift &+= 8 + n -= c8 + } + let c4 = ((self &>> shift) & 0xF)._nonzeroBitCount + if n >= c4 { + shift &+= 4 + n -= c4 + } + let c2 = ((self &>> shift) & 0x3)._nonzeroBitCount + if n >= c2 { + shift &+= 2 + n -= c2 + } + let c1 = (self &>> shift) & 0x1 + if n >= c1 { + shift &+= 1 + n -= c1 + } + guard n == 0, (self &>> shift) & 0x1 == 1 else { return nil } + return UInt(truncatingIfNeeded: shift) + } +} diff --git a/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift b/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift new file mode 100644 index 00000000..f79bcd03 --- /dev/null +++ b/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift @@ -0,0 +1,138 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Collections open source project +// +// Copyright (c) 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +extension UnsafeMutableBufferPointer { + @inlinable + public func initialize(fromContentsOf source: Self) -> Index { + guard source.count > 0 else { return 0 } + precondition( + source.count <= self.count, + "buffer cannot contain every element from source.") + baseAddress.unsafelyUnwrapped.initialize( + from: source.baseAddress.unsafelyUnwrapped, + count: source.count) + return source.count + } + + @inlinable + public func initialize(fromContentsOf source: Slice) -> Index { + let sourceCount = source.count + guard sourceCount > 0 else { return 0 } + precondition( + sourceCount <= self.count, + "buffer cannot contain every element from source.") + baseAddress.unsafelyUnwrapped.initialize( + from: source.base.baseAddress.unsafelyUnwrapped + source.startIndex, + count: sourceCount) + return sourceCount + } +} + +extension Slice { + @inlinable @inline(__always) + public func initialize( + fromContentsOf source: UnsafeMutableBufferPointer + ) -> Index + where Base == UnsafeMutableBufferPointer + { + let target = UnsafeMutableBufferPointer(rebasing: self) + let i = target.initialize(fromContentsOf: source) + return self.startIndex + i + } + + @inlinable @inline(__always) + public func initialize( + fromContentsOf source: Slice> + ) -> Index + where Base == UnsafeMutableBufferPointer + { + let target = UnsafeMutableBufferPointer(rebasing: self) + let i = target.initialize(fromContentsOf: source) + return self.startIndex + i + } +} + +extension UnsafeMutableBufferPointer { + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: C + ) where C.Element == Element { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func initializeAll(fromContentsOf source: Self) { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func initializeAll(fromContentsOf source: Slice) { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func moveInitializeAll(fromContentsOf source: Self) { + let i = self.moveInitialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func moveInitializeAll(fromContentsOf source: Slice) { + let i = self.moveInitialize(fromContentsOf: source) + assert(i == self.endIndex) + } +} + +extension Slice { + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: C + ) where Base == UnsafeMutableBufferPointer { + let i = self.initialize(fromContentsOf: source) + assert(i == self.endIndex) + } + + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: UnsafeMutableBufferPointer + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.initializeAll(fromContentsOf: source) + } + + @inlinable @inline(__always) + public func initializeAll( + fromContentsOf source: Slice> + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.initializeAll(fromContentsOf: source) + } + + @inlinable @inline(__always) + public func moveInitializeAll( + fromContentsOf source: UnsafeMutableBufferPointer + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.moveInitializeAll(fromContentsOf: source) + } + + @inlinable @inline(__always) + public func moveInitializeAll( + fromContentsOf source: Slice> + ) where Base == UnsafeMutableBufferPointer { + let target = UnsafeMutableBufferPointer(rebasing: self) + target.moveInitializeAll(fromContentsOf: source) + } +} + diff --git a/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer extensions.swift b/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+SE-0370.swift similarity index 55% rename from Sources/_CollectionsUtilities/UnsafeMutableBufferPointer extensions.swift rename to Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+SE-0370.swift index 891a8178..e76f0af1 100644 --- a/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer extensions.swift +++ b/Sources/_CollectionsUtilities/UnsafeMutableBufferPointer+SE-0370.swift @@ -9,6 +9,8 @@ // //===----------------------------------------------------------------------===// +// Note: These are adapted from SE-0370 in the Swift 5.8 Standard Library. + extension UnsafeMutableBufferPointer { /// Deinitializes every instance in this buffer. /// @@ -211,3 +213,156 @@ extension UnsafeMutableBufferPointer { p.deinitialize(count: 1) } } + +extension Slice { + /// Initializes the buffer slice's memory with with + /// every element of the source. + /// + /// Prior to calling the `initialize(fromContentsOf:)` method + /// on a buffer slice, the memory it references must be uninitialized, + /// or the `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer slice up to, but not including, + /// the returned index is initialized. + /// The buffer slice must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the index of the next uninitialized element + /// in the buffer slice, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to + /// the buffer slice's `startIndex`. If `source` contains as many elements + /// as the buffer slice can hold, the returned index is equal to + /// to the slice's `endIndex`. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Note: The memory regions referenced by `source` and this buffer slice + /// must not overlap. + /// + /// - Parameter source: A collection of elements to be used to + /// initialize the buffer slice's storage. + /// - Returns: The index one past the last element of the buffer slice + /// initialized by this function. + @inlinable + @_alwaysEmitIntoClient + public func initialize( + fromContentsOf source: C + ) -> Index where Base == UnsafeMutableBufferPointer { + let buffer = Base(rebasing: self) + let index = buffer.initialize(fromContentsOf: source) + let distance = buffer.distance(from: buffer.startIndex, to: index) + return startIndex.advanced(by: distance) + } + + /// Moves every element of an initialized source buffer into the + /// uninitialized memory referenced by this buffer slice, leaving the + /// source memory uninitialized and this buffer slice's memory initialized. + /// + /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a + /// buffer slice, the memory it references must be uninitialized, + /// or its `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer slice up to, but not including, + /// the returned index is initialized. The memory referenced by + /// `source` is uninitialized after the function returns. + /// The buffer slice must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer slice, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// slice's `startIndex`. If `source` contains as many elements as the slice + /// can hold, the returned index is equal to the slice's `endIndex`. + /// + /// - Note: The memory regions referenced by `source` and this buffer slice + /// may overlap. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Parameter source: A buffer containing the values to copy. + /// The memory region underlying `source` must be initialized. + /// - Returns: The index one past the last element of the buffer slice + /// initialized by this function. + @inlinable + @_alwaysEmitIntoClient + public func moveInitialize( + fromContentsOf source: UnsafeMutableBufferPointer + ) -> Index where Base == UnsafeMutableBufferPointer { + let buffer = Base(rebasing: self) + let index = buffer.moveInitialize(fromContentsOf: source) + let distance = buffer.distance(from: buffer.startIndex, to: index) + return startIndex.advanced(by: distance) + } + + /// Moves every element of an initialized source buffer slice into the + /// uninitialized memory referenced by this buffer slice, leaving the + /// source memory uninitialized and this buffer slice's memory initialized. + /// + /// Prior to calling the `moveInitialize(fromContentsOf:)` method on a + /// buffer slice, the memory it references must be uninitialized, + /// or its `Element` type must be a trivial type. After the call, + /// the memory referenced by the buffer slice up to, but not including, + /// the returned index is initialized. The memory referenced by + /// `source` is uninitialized after the function returns. + /// The buffer slice must reference enough memory to accommodate + /// `source.count` elements. + /// + /// The returned index is the position of the next uninitialized element + /// in the buffer slice, one past the index of the last element written. + /// If `source` contains no elements, the returned index is equal to the + /// slice's `startIndex`. If `source` contains as many elements as the slice + /// can hold, the returned index is equal to the slice's `endIndex`. + /// + /// - Note: The memory regions referenced by `source` and this buffer slice + /// may overlap. + /// + /// - Precondition: `self.count` >= `source.count` + /// + /// - Parameter source: A buffer slice containing the values to copy. + /// The memory region underlying `source` must be initialized. + /// - Returns: The index one past the last element of the buffer slice + /// initialized by this function. + @inlinable + @_alwaysEmitIntoClient + public func moveInitialize( + fromContentsOf source: Slice> + ) -> Index where Base == UnsafeMutableBufferPointer { + let buffer = Base(rebasing: self) + let index = buffer.moveInitialize(fromContentsOf: source) + let distance = buffer.distance(from: buffer.startIndex, to: index) + return startIndex.advanced(by: distance) + } + + /// Deinitializes every instance in this buffer slice. + /// + /// The region of memory underlying this buffer slice must be fully + /// initialized. After calling `deinitialize(count:)`, the memory + /// is uninitialized, but still bound to the `Element` type. + /// + /// - Note: All buffer elements must already be initialized. + /// + /// - Returns: A raw buffer to the same range of memory as this buffer. + /// The range of memory is still bound to `Element`. + @discardableResult + @inlinable + @_alwaysEmitIntoClient + public func deinitialize() -> UnsafeMutableRawBufferPointer + where Base == UnsafeMutableBufferPointer { + Base(rebasing: self).deinitialize() + } + + /// Initializes the element at `index` to the given value. + /// + /// The memory underlying the destination element must be uninitialized, + /// or `Element` must be a trivial type. After a call to `initialize(to:)`, + /// the memory underlying this element of the buffer slice is initialized. + /// + /// - Parameters: + /// - value: The value used to initialize the buffer element's memory. + /// - index: The index of the element to initialize + @inlinable + @_alwaysEmitIntoClient + public func initializeElement(at index: Int, to value: Element) + where Base == UnsafeMutableBufferPointer { + assert(startIndex <= index && index < endIndex) + base.baseAddress.unsafelyUnwrapped.advanced(by: index).initialize(to: value) + } +} diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift index 2ede2d57..8e519ba8 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary Tests.swift @@ -14,6 +14,8 @@ import XCTest import _CollectionsTestSupport +extension OrderedDictionary: DictionaryAPIChecker {} + class OrderedDictionaryTests: CollectionTestCase { func test_empty() { let d = OrderedDictionary() diff --git a/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift b/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift index c8240133..8ae57a67 100644 --- a/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift +++ b/Tests/PersistentCollectionsTests/PersistentCollections Fixtures.swift @@ -189,24 +189,16 @@ let _fixtures: KeyValuePairs = [ ], ] -struct Fixture { - typealias Element = (key: Key, value: Value) - - let title: String - let items: [Element] - - init(title: String, items: [Element]) { - self.title = title - self.items = items - } +let fixtures: [RawFixture] = _fixtures.map { + RawFixture(title: $0, contents: $1) } -func withEachFixture( - body: (Fixture) -> Void -) { - for (name, fixture) in _fixtures { - let entry = TestContext.current.push("fixture: \(name)") - defer { TestContext.current.pop(entry) } +struct RawFixture { + let title: String + let hashes: [Hash] + + init(title: String, contents: [String]) { + self.title = title let maxDepth = PersistentDictionary._maxDepth @@ -218,7 +210,7 @@ func withEachFixture( var paths: [String] = [] var seen: Set = [] - for item in fixture { + for item in contents { let path: String if let i = item.unicodeScalars.firstIndex(of: "*") { // We need to extend the path of collisions with zeroes to @@ -275,29 +267,51 @@ func withEachFixture( return false } - var items: [(key: RawCollider, value: Int)] = [] - items.reserveCapacity(paths.count) - var id = 0 - for path in paths { - let hash = Hash(path)! - let key = RawCollider(id, hash) - let value = 100 + id - items.append((key, value)) - id += 1 - } + self.hashes = paths.map { Hash($0)! } + } +} - print(name) - body(Fixture(title: name, items: items)) +struct Fixture { + 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)) + } + } +} + +func withEachFixture( + body: (Fixture) -> Void +) { + for raw in fixtures { + let entry = TestContext.current.push("fixture: \(raw.title)") + defer { TestContext.current.pop(entry) } + + let fixture = Fixture( + raw, + key: { RawCollider($0, $1) }, + value: { 100 + $0 }) + + body(fixture) } } extension LifetimeTracker { - func persistentDictionary( - for fixture: Fixture + func persistentDictionary( + for fixture: Fixture ) -> ( - map: PersistentDictionary, LifetimeTracked>, - ref: [(key: LifetimeTracked, value: LifetimeTracked)] + map: PersistentDictionary, LifetimeTracked>, + ref: [(key: LifetimeTracked, value: LifetimeTracked)] ) { let ref = fixture.items.map { (key, value) in (key: self.instance(for: key), value: self.instance(for: value)) diff --git a/Tests/PersistentCollectionsTests/PersistentCollections Smoke Tests.swift b/Tests/PersistentCollectionsTests/PersistentCollections Smoke Tests.swift index b4029b6b..c7dc26ea 100644 --- a/Tests/PersistentCollectionsTests/PersistentCollections Smoke Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentCollections Smoke Tests.swift @@ -592,7 +592,7 @@ final class PersistentDictionarySmokeTests: CollectionTestCase { } func test_indexForKey() { - let input = 0 ..< 1 + let input = 0 ..< 10_000 let d = PersistentDictionary( uniqueKeysWithValues: input.lazy.map { ($0, 2 * $0) }) for key in input { diff --git a/Tests/PersistentCollectionsTests/PersistentCollections Tests.swift b/Tests/PersistentCollectionsTests/PersistentCollections Tests.swift index a7f2610f..bec861ca 100644 --- a/Tests/PersistentCollectionsTests/PersistentCollections Tests.swift +++ b/Tests/PersistentCollectionsTests/PersistentCollections Tests.swift @@ -12,6 +12,8 @@ import _CollectionsTestSupport @testable import PersistentCollections +extension PersistentDictionary: DictionaryAPIChecker {} + class PersistentDictionaryTests: CollectionTestCase { func test_empty() { let d = PersistentDictionary() @@ -262,6 +264,49 @@ class PersistentDictionaryTests: CollectionTestCase { checkBidirectionalCollection(d, expectedContents: Array(d), by: ==) } + func test_updateValueForKey_fixtures() { + withEachFixture { fixture in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var d: PersistentDictionary, LifetimeTracked> = [:] + var ref: Dictionary, LifetimeTracked> = [:] + withEvery("i", in: 0 ..< fixture.items.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 + expectEqualDictionaries(d, ref) + } + } + } + } + } + } + + func test_updateValueForKey_fixtures_tiny() { + struct Empty: Hashable {} + + withEachFixture { fixture in + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var d: PersistentDictionary, Empty> = [:] + var ref: Dictionary, Empty> = [:] + withEvery("i", in: 0 ..< fixture.items.count) { i in + withHiddenCopies(if: isShared, of: &d) { d in + let item = fixture.items[i] + let key = tracker.instance(for: item.key) + d[key] = Empty() + ref[key] = Empty() + expectEqualDictionaries(d, ref) + } + } + } + } + } + } + func test_removeValueForKey_fixtures() { withEachFixture { fixture in withEvery("offset", in: 0 ..< fixture.items.count) { offset in @@ -442,20 +487,18 @@ class PersistentDictionaryTests: CollectionTestCase { func test_subscript_setter_insert_fixtures() { withEachFixture { fixture in - withEvery("seed", in: 0..<3) { seed in - withEvery("isShared", in: [false, true]) { isShared in - withLifetimeTracking { tracker in - var d: PersistentDictionary, LifetimeTracked> = [:] - var ref: Dictionary, LifetimeTracked> = [:] - withEvery("i", in: 0 ..< fixture.items.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 - expectEqualDictionaries(d, ref) - } + withEvery("isShared", in: [false, true]) { isShared in + withLifetimeTracking { tracker in + var d: PersistentDictionary, LifetimeTracked> = [:] + var ref: Dictionary, LifetimeTracked> = [:] + withEvery("i", in: 0 ..< fixture.items.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 + expectEqualDictionaries(d, ref) } } }