[PersistentCollections] Reformat

Follow the Standard Library coding style:

- Hard 80 character line limit
- Use two spaces as the indentation unit
- Overlong lines broken up by adding line breaks at the following places
    1. After opening delimiters & before closing delimiters
    2. Between each item in a list
    3. Extracting subexpressions etc as needed
This commit is contained in:
Karoy Lorentey committed 2022-09-07 19:16:41 -07:00
1 parent 1a87233bcd
commit 1a4993dfda
22 files changed
+3274 -2864

No files matched your search

@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
//extension PersistentDictionary: CVarArg {
// public var _cVarArgEncoding: [Int] {
// <#code#>
// }
// public var _cVarArgEncoding: [Int] {
// <#code#>
// }
//}
@@ -10,43 +10,43 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary: Collection {
public typealias Index = PersistentDictionaryIndex
///
/// Manipulating Indices
///
public var startIndex: Self.Index { PersistentDictionaryIndex(value: 0) }
public var endIndex: Self.Index { PersistentDictionaryIndex(value: count) }
public func index(after i: Self.Index) -> Self.Index {
return i + 1
}
///
/// Returns the index for the given key.
///
public func index(forKey key: Key) -> Self.Index? {
return rootNode.index(key, computeHash(key), 0, 0)
}
///
/// Accesses the key-value pair at the specified position.
///
public subscript(position: Self.Index) -> Self.Element {
return rootNode.get(position: position, 0, position.value)
}
public typealias Index = PersistentDictionaryIndex
///
/// Manipulating Indices
///
public var startIndex: Self.Index { PersistentDictionaryIndex(value: 0) }
public var endIndex: Self.Index { PersistentDictionaryIndex(value: count) }
public func index(after i: Self.Index) -> Self.Index {
return i + 1
}
///
/// Returns the index for the given key.
///
public func index(forKey key: Key) -> Self.Index? {
return rootNode.index(key, computeHash(key), 0, 0)
}
///
/// Accesses the key-value pair at the specified position.
///
public subscript(position: Self.Index) -> Self.Element {
return rootNode.get(position: position, 0, position.value)
}
}
public struct PersistentDictionaryIndex: Comparable {
let value: Int
public static func < (lhs: Self, rhs: Self) -> Bool {
return lhs.value < rhs.value
}
public static func +(lhs: Self, rhs: Int) -> Self {
return PersistentDictionaryIndex(value: lhs.value + rhs)
}
let value: Int
public static func < (lhs: Self, rhs: Self) -> Bool {
return lhs.value < rhs.value
}
public static func +(lhs: Self, rhs: Int) -> Self {
return PersistentDictionaryIndex(value: lhs.value + rhs)
}
}
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
//extension PersistentDictionary: CustomDebugStringConvertible {
// public var debugDescription: String {
// <#code#>
// }
// public var debugDescription: String {
// <#code#>
// }
//}
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
//extension PersistentDictionary: CustomReflectable {
// public var customMirror: Mirror {
// <#code#>
// }
// public var customMirror: Mirror {
// <#code#>
// }
//}
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// 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
@@ -10,22 +10,22 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary: CustomStringConvertible {
public var description: String {
guard count > 0 else {
return "[:]"
}
var result = "["
var first = true
for (key, value) in self {
if first {
first = false
} else {
result += ", "
}
result += "\(key): \(value)"
}
result += "]"
return result
public var description: String {
guard count > 0 else {
return "[:]"
}
var result = "["
var first = true
for (key, value) in self {
if first {
first = false
} else {
result += ", "
}
result += "\(key): \(value)"
}
result += "]"
return result
}
}
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
//extension PersistentDictionary: Decodable where Key: Decodable, Value: Decodable {
// public init(from decoder: Decoder) throws {
// <#code#>
// }
// public init(from decoder: Decoder) throws {
// <#code#>
// }
//}
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
//extension PersistentDictionary: Encodable where Key: Encodable, Value: Encodable {
// public func encode(to encoder: Encoder) throws {
// <#code#>
// }
// public func encode(to encoder: Encoder) throws {
// <#code#>
// }
//}
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift project authors
// Copyright (c) 2019 - 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
@@ -10,7 +10,7 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary: Equatable where Value: Equatable {
public static func == (lhs: PersistentDictionary<Key, Value>, rhs: PersistentDictionary<Key, Value>) -> Bool {
lhs.rootNode === rhs.rootNode || lhs.rootNode == rhs.rootNode
}
public static func == (lhs: Self, rhs: Self) -> Bool {
lhs.rootNode === rhs.rootNode || lhs.rootNode == rhs.rootNode
}
}
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift project authors
// Copyright (c) 2019 - 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
@@ -10,9 +10,9 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary: ExpressibleByDictionaryLiteral {
@inlinable
@inline(__always)
public init(dictionaryLiteral elements: (Key, Value)...) {
self.init(uniqueKeysWithValues: elements)
}
@inlinable
@inline(__always)
public init(dictionaryLiteral elements: (Key, Value)...) {
self.init(uniqueKeysWithValues: elements)
}
}
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift project authors
// Copyright (c) 2019 - 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
@@ -10,14 +10,14 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary: Hashable where Value: Hashable {
public func hash(into hasher: inout Hasher) {
var commutativeHash = 0
for (key, value) in self {
var elementHasher = hasher
elementHasher.combine(key)
elementHasher.combine(value)
commutativeHash ^= elementHasher.finalize()
}
hasher.combine(commutativeHash)
public func hash(into hasher: inout Hasher) {
var commutativeHash = 0
for (key, value) in self {
var elementHasher = hasher
elementHasher.combine(key)
elementHasher.combine(value)
commutativeHash ^= elementHasher.finalize()
}
hasher.combine(commutativeHash)
}
}
@@ -11,15 +11,11 @@
// 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]
///
/// A collection containing just the keys of the dictionary.
///
public var keys: Self.Keys /* { get } */ {
self.map { $0.key }
}
/// A view of a dictionary’s keys.
public typealias Keys = [Key]
/// A collection containing just the keys of the dictionary.
public var keys: Self.Keys /* { get } */ {
self.map { $0.key }
}
}
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift project authors
// Copyright (c) 2019 - 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
@@ -10,9 +10,10 @@
//===----------------------------------------------------------------------===//
extension PersistentDictionary: Sequence {
public typealias Element = DictionaryKeyValueTupleIterator<Key, Value>.Element
public __consuming func makeIterator() -> DictionaryKeyValueTupleIterator<Key, Value> {
return DictionaryKeyValueTupleIterator(rootNode: rootNode)
}
public typealias Element = (key: Key, value: Value)
public typealias Iterator = DictionaryKeyValueTupleIterator<Key, Value>
public __consuming func makeIterator() -> Iterator {
return DictionaryKeyValueTupleIterator(rootNode: rootNode)
}
}
@@ -11,15 +11,11 @@
// 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]
/// A view of a dictionary’s values.
public typealias Values = [Value]
///
/// A collection containing just the values of the dictionary.
///
public var values: Self.Values /* { get set } */ {
self.map { $0.value }
}
/// A collection containing just the values of the dictionary.
public var values: Self.Values /* { get set } */ {
self.map { $0.value }
}
}
@@ -10,211 +10,233 @@
//===----------------------------------------------------------------------===//
public struct PersistentDictionary<Key, Value> where Key: Hashable {
var rootNode: BitmapIndexedDictionaryNode<Key, Value>
var rootNode: BitmapIndexedDictionaryNode<Key, Value>
fileprivate init(_ rootNode: BitmapIndexedDictionaryNode<Key, Value>) {
self.rootNode = rootNode
fileprivate init(_ rootNode: BitmapIndexedDictionaryNode<Key, Value>) {
self.rootNode = rootNode
}
public init() {
self.init(BitmapIndexedDictionaryNode())
}
public init(_ map: PersistentDictionary<Key, Value>) {
self.init(map.rootNode)
}
@inlinable
@inline(__always)
public init<S: Sequence>(
uniqueKeysWithValues keysAndValues: S
) where S.Element == (Key, Value) {
var builder = Self()
var expectedCount = 0
keysAndValues.forEach { key, value in
builder.updateValue(value, forKey: key)
expectedCount += 1
guard expectedCount == builder.count else {
preconditionFailure("Duplicate key: '\(key)'")
}
}
self.init(builder)
}
@inlinable
@inline(__always)
public init<Keys: Sequence, Values: Sequence>(
uniqueKeys keys: Keys,
values: Values
) where Keys.Element == Key, Values.Element == Value {
self.init(uniqueKeysWithValues: zip(keys, values))
}
///
/// Inspecting a Dictionary
///
public var isEmpty: Bool { rootNode.count == 0 }
public var count: Int { rootNode.count }
public var underestimatedCount: Int { rootNode.count }
public var capacity: Int { rootNode.count }
///
/// Accessing Keys and Values
///
public subscript(key: Key) -> Value? {
get {
return get(key)
}
mutating set(optionalValue) {
if let value = optionalValue {
updateValue(value, forKey: key)
} else {
removeValue(forKey: key)
}
}
}
public subscript(
key: Key,
default defaultValue: @autoclosure () -> Value
) -> Value {
get {
return get(key) ?? defaultValue()
}
mutating set(value) {
updateValue(value, forKey: key)
}
}
public func contains(_ key: Key) -> Bool {
rootNode.containsKey(key, computeHash(key), 0)
}
func get(_ key: Key) -> Value? {
rootNode.get(key, computeHash(key), 0)
}
@discardableResult
public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? {
let isUnique = isKnownUniquelyReferenced(&self.rootNode)
var effect = DictionaryEffect<Value>()
let keyHash = computeHash(key)
let newRootNode = rootNode.updateOrUpdating(
isUnique, key, value, keyHash, 0, &effect)
if effect.modified {
self.rootNode = newRootNode
}
public init() {
self.init(BitmapIndexedDictionaryNode())
// Note, always tracking discardable result negatively impacts batch use cases
return effect.previousValue
}
// fluid/immutable API
public func updatingValue(_ value: Value, forKey key: Key) -> Self {
var effect = DictionaryEffect<Value>()
let keyHash = computeHash(key)
let newRootNode = rootNode.updateOrUpdating(
false, key, value, keyHash, 0, &effect)
if effect.modified {
return Self(newRootNode)
} else { return self }
}
@discardableResult
public mutating func removeValue(forKey key: Key) -> Value? {
let isUnique = isKnownUniquelyReferenced(&self.rootNode)
var effect = DictionaryEffect<Value>()
let keyHash = computeHash(key)
let newRootNode = rootNode.removeOrRemoving(
isUnique, key, keyHash, 0, &effect)
if effect.modified {
self.rootNode = newRootNode
}
public init(_ map: PersistentDictionary<Key, Value>) {
self.init(map.rootNode)
}
// Note, always tracking discardable result negatively impacts batch use cases
return effect.previousValue
}
@inlinable
@inline(__always)
public init<S>(uniqueKeysWithValues keysAndValues: S) where S : Sequence, S.Element == (Key, Value) {
var builder = Self()
var expectedCount = 0
keysAndValues.forEach { key, value in
builder.updateValue(value, forKey: key)
expectedCount += 1
// fluid/immutable API
public func removingValue(forKey key: Key) -> Self {
var effect = DictionaryEffect<Value>()
let keyHash = computeHash(key)
let newRootNode = rootNode.removeOrRemoving(false, key, keyHash, 0, &effect)
guard expectedCount == builder.count else {
preconditionFailure("Duplicate key: '\(key)'")
}
}
self.init(builder)
}
@inlinable
@inline(__always)
public init<Keys: Sequence, Values: Sequence>(uniqueKeys keys: Keys, values: Values) where Keys.Element == Key, Values.Element == Value {
self.init(uniqueKeysWithValues: zip(keys, values))
}
///
/// Inspecting a Dictionary
///
public var isEmpty: Bool { rootNode.count == 0 }
public var count: Int { rootNode.count }
public var underestimatedCount: Int { rootNode.count }
public var capacity: Int { rootNode.count }
///
/// Accessing Keys and Values
///
public subscript(key: Key) -> Value? {
get {
return get(key)
}
mutating set(optionalValue) {
if let value = optionalValue {
updateValue(value, forKey: key)
} else {
removeValue(forKey: key)
}
}
}
public subscript(key: Key, default defaultValue: @autoclosure () -> Value) -> Value {
get {
return get(key) ?? defaultValue()
}
mutating set(value) {
updateValue(value, forKey: key)
}
}
public func contains(_ key: Key) -> Bool {
rootNode.containsKey(key, computeHash(key), 0)
}
func get(_ key: Key) -> Value? {
rootNode.get(key, computeHash(key), 0)
}
@discardableResult
public mutating func updateValue(_ value: Value, forKey key: Key) -> Value? {
let isStorageKnownUniquelyReferenced = isKnownUniquelyReferenced(&self.rootNode)
var effect = DictionaryEffect<Value>()
let keyHash = computeHash(key)
let newRootNode = rootNode.updateOrUpdating(isStorageKnownUniquelyReferenced, key, value, keyHash, 0, &effect)
if effect.modified {
self.rootNode = newRootNode
}
// Note, always tracking discardable result negatively impacts batch use cases
return effect.previousValue
}
// fluid/immutable API
public func updatingValue(_ value: Value, forKey key: Key) -> Self {
var effect = DictionaryEffect<Value>()
let keyHash = computeHash(key)
let newRootNode = rootNode.updateOrUpdating(false, key, value, keyHash, 0, &effect)
if effect.modified {
return Self(newRootNode)
} else { return self }
}
@discardableResult
public mutating func removeValue(forKey key: Key) -> Value? {
let isStorageKnownUniquelyReferenced = isKnownUniquelyReferenced(&self.rootNode)
var effect = DictionaryEffect<Value>()
let keyHash = computeHash(key)
let newRootNode = rootNode.removeOrRemoving(isStorageKnownUniquelyReferenced, key, keyHash, 0, &effect)
if effect.modified {
self.rootNode = newRootNode
}
// Note, always tracking discardable result negatively impacts batch use cases
return effect.previousValue
}
// fluid/immutable API
public func removingValue(forKey key: Key) -> Self {
var effect = DictionaryEffect<Value>()
let keyHash = computeHash(key)
let newRootNode = rootNode.removeOrRemoving(false, key, keyHash, 0, &effect)
if effect.modified {
return Self(newRootNode)
} else { return self }
}
if effect.modified {
return Self(newRootNode)
} else { return self }
}
}
///
/// Fixed-stack iterator for traversing a hash-trie. The iterator performs a
/// depth-first pre-order traversal, which yields first all payload elements of the current
/// node before traversing sub-nodes (left to right).
///
public struct DictionaryKeyValueTupleIterator<Key: Hashable, Value>: IteratorProtocol {
/// depth-first pre-order traversal, which yields first all payload elements
/// of the current node before traversing sub-nodes (left to right).
public struct DictionaryKeyValueTupleIterator<Key: Hashable, Value> {
typealias KeyValueBuffer = UnsafeBufferPointer<(key: Key, value: Value)>
typealias DictionaryNode = BitmapIndexedDictionaryNode<Key, Value>
typealias DictionaryNodeBuffer = UnsafeBufferPointer<DictionaryNode>
private var payloadIterator: UnsafeBufferPointer<(key: Key, value: Value)>.Iterator?
private var payloadIterator: KeyValueBuffer.Iterator?
private var trieIteratorStackTop: UnsafeBufferPointer<BitmapIndexedDictionaryNode<Key, Value>>.Iterator?
private var trieIteratorStackRemainder: [UnsafeBufferPointer<BitmapIndexedDictionaryNode<Key, Value>>.Iterator]
private var trieIteratorStackTop: DictionaryNodeBuffer.Iterator?
private var trieIteratorStackRemainder: [DictionaryNodeBuffer.Iterator]
init(rootNode: BitmapIndexedDictionaryNode<Key, Value>) {
trieIteratorStackRemainder = []
trieIteratorStackRemainder.reserveCapacity(maxDepth)
init(rootNode: DictionaryNode) {
trieIteratorStackRemainder = []
trieIteratorStackRemainder.reserveCapacity(maxDepth)
if rootNode.hasNodes { trieIteratorStackTop = rootNode._trieSlice.makeIterator() }
if rootNode.hasPayload { payloadIterator = rootNode._dataSlice.makeIterator() }
if rootNode.hasNodes {
trieIteratorStackTop = rootNode._trieSlice.makeIterator()
}
if rootNode.hasPayload {
payloadIterator = rootNode._dataSlice.makeIterator()
}
}
}
extension DictionaryKeyValueTupleIterator: IteratorProtocol {
public typealias Element = (key: Key, value: Value)
public mutating func next() -> Element? {
if let payload = payloadIterator?.next() {
return payload
}
public mutating func next() -> (key: Key, value: Value)? {
if let payload = payloadIterator?.next() {
return payload
while trieIteratorStackTop != nil {
if let nextNode = trieIteratorStackTop!.next() {
if nextNode.hasNodes {
trieIteratorStackRemainder.append(trieIteratorStackTop!)
trieIteratorStackTop = nextNode._trieSlice.makeIterator()
}
while trieIteratorStackTop != nil {
if let nextNode = trieIteratorStackTop!.next() {
if nextNode.hasNodes {
trieIteratorStackRemainder.append(trieIteratorStackTop!)
trieIteratorStackTop = nextNode._trieSlice.makeIterator()
}
if nextNode.hasPayload {
payloadIterator = nextNode._dataSlice.makeIterator()
return payloadIterator?.next()
}
} else {
trieIteratorStackTop = trieIteratorStackRemainder.popLast()
}
if nextNode.hasPayload {
payloadIterator = nextNode._dataSlice.makeIterator()
return payloadIterator?.next()
}
// Clean-up state
payloadIterator = nil
assert(payloadIterator == nil)
assert(trieIteratorStackTop == nil)
assert(trieIteratorStackRemainder.isEmpty)
return nil
} else {
trieIteratorStackTop = trieIteratorStackRemainder.popLast()
}
}
// Clean-up state
payloadIterator = nil
assert(payloadIterator == nil)
assert(trieIteratorStackTop == nil)
assert(trieIteratorStackRemainder.isEmpty)
return nil
}
}
// TODO consider reworking similar to `DictionaryKeyValueTupleIterator`
// (would require a reversed variant of `UnsafeBufferPointer<(key: Key, value: Value)>.Iterator`)
// (would require a reversed variant of `KeyValueBuffer.Iterator`)
public struct DictionaryKeyValueTupleReverseIterator<Key: Hashable, Value> {
private var baseIterator: BaseReverseIterator<BitmapIndexedDictionaryNode<Key, Value>>
typealias DictionaryNode = BitmapIndexedDictionaryNode<Key, Value>
private var baseIterator: BaseReverseIterator<DictionaryNode>
init(rootNode: BitmapIndexedDictionaryNode<Key, Value>) {
self.baseIterator = BaseReverseIterator(rootNode: rootNode)
}
init(rootNode: DictionaryNode) {
self.baseIterator = BaseReverseIterator(rootNode: rootNode)
}
}
extension DictionaryKeyValueTupleReverseIterator: IteratorProtocol {
public mutating func next() -> (key: Key, value: Value)? {
guard baseIterator.hasNext() else { return nil }
public mutating func next() -> (key: Key, value: Value)? {
guard baseIterator.hasNext() else { return nil }
let payload = baseIterator.currentValueNode!.getPayload(baseIterator.currentValueCursor)
baseIterator.currentValueCursor -= 1
let payload = baseIterator
.currentValueNode!
.getPayload(baseIterator.currentValueCursor)
baseIterator.currentValueCursor -= 1
return payload
}
return payload
}
}
File diff suppressed because it is too large. Load diff
+211 -183
View File
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2019 - 2021 Apple Inc. and the Swift project authors
// Copyright (c) 2019 - 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
@@ -10,286 +10,314 @@
//===----------------------------------------------------------------------===//
func computeHash<T: Hashable>(_ value: T) -> Int {
value.hashValue
value.hashValue
}
typealias Bitmap = UInt32
extension Bitmap {
public func nonzeroBits() -> NonzeroBits<Self> {
return NonzeroBits(from: self)
}
public func nonzeroBits() -> NonzeroBits<Self> {
return NonzeroBits(from: self)
}
public func zeroBits() -> NonzeroBits<Self> {
return NonzeroBits(from: ~self)
}
public func zeroBits() -> NonzeroBits<Self> {
return NonzeroBits(from: ~self)
}
}
public struct NonzeroBits<Bitmap>: Sequence, IteratorProtocol, CustomStringConvertible where Bitmap: BinaryInteger {
var bitmap: Bitmap
public struct NonzeroBits<Bitmap>
: Sequence, IteratorProtocol, CustomStringConvertible
where Bitmap: BinaryInteger {
var bitmap: Bitmap
init(from bitmap: Bitmap) {
self.bitmap = bitmap
}
init(from bitmap: Bitmap) {
self.bitmap = bitmap
}
public mutating func next() -> Int? {
guard bitmap != 0 else { return nil }
public mutating func next() -> Int? {
guard bitmap != 0 else { return nil }
let index = bitmap.trailingZeroBitCount
bitmap ^= 1 << index
let index = bitmap.trailingZeroBitCount
bitmap ^= 1 << index
return index
}
return index
}
public var description: String {
"[\(self.map { $0.description }.joined(separator: ", "))]"
}
public var description: String {
"[\(self.map { $0.description }.joined(separator: ", "))]"
}
}
let bitPartitionSize: Int = 5
let bitPartitionMask: Int = (1 << bitPartitionSize) - 1
typealias Capacity = UInt32 // TODO: restore type to `UInt8` after reworking hash-collisions to grow in depth instead of width
// TODO: restore type to `UInt8` after reworking hash-collisions to grow in
// depth instead of width
typealias Capacity = UInt32
let hashCodeLength: Int = Int.bitWidth
let maxDepth = Int((Double(hashCodeLength) / Double(bitPartitionSize)).rounded(.up))
func maskFrom(_ hash: Int, _ shift: Int) -> Int {
(hash >> shift) & bitPartitionMask
(hash >> shift) & bitPartitionMask
}
func bitposFrom(_ mask: Int) -> Bitmap {
1 << mask
1 << mask
}
func indexFrom(_ bitmap: Bitmap, _ bitpos: Bitmap) -> Int {
(bitmap & (bitpos &- 1)).nonzeroBitCount
(bitmap & (bitpos &- 1)).nonzeroBitCount
}
func indexFrom(_ bitmap: Bitmap, _ mask: Int, _ bitpos: Bitmap) -> Int {
(bitmap == Bitmap.max) ? mask : indexFrom(bitmap, bitpos)
(bitmap == Bitmap.max) ? mask : indexFrom(bitmap, bitpos)
}
protocol Node: AnyObject {
associatedtype ReturnPayload
associatedtype ReturnBitmapIndexedNode: Node
associatedtype ReturnPayload
associatedtype ReturnBitmapIndexedNode: Node
var hasNodes: Bool { get }
var hasNodes: Bool { get }
var nodeArity: Int { get }
var nodeArity: Int { get }
func getNode(_ index: Int) -> Self
func getNode(_ index: Int) -> Self
var hasPayload: Bool { get }
var hasPayload: Bool { get }
var payloadArity: Int { get }
var payloadArity: Int { get }
func getPayload(_ index: Int) -> ReturnPayload
func getPayload(_ index: Int) -> ReturnPayload
var count: Int { get }
var count: Int { get }
}
///
/// Base class for fixed-stack iterators that traverse a hash-trie. The iterator performs a
/// depth-first pre-order traversal, which yields first all payload elements of the current
/// node before traversing sub-nodes (left to right).
///
/// Base class for fixed-stack iterators that traverse a hash-trie. The iterator
/// performs a depth-first pre-order traversal, which yields first all payload
/// elements of the current node before traversing sub-nodes (left to right).
struct BaseIterator<T: Node> {
var currentValueCursor: Int = 0
var currentValueLength: Int = 0
var currentValueNode: T? = nil
var currentValueCursor: Int = 0
var currentValueLength: Int = 0
var currentValueNode: T? = nil
private var currentStackLevel: Int = -1
private var nodeCursorsAndLengths: [Int] = Array(repeating: 0, count: maxDepth * 2)
private var nodes: [T?] = Array(repeating: nil, count: maxDepth)
private var currentStackLevel: Int = -1
private var nodeCursorsAndLengths: [Int] = (
Array(repeating: 0, count: maxDepth * 2))
private var nodes: [T?] = Array(repeating: nil, count: maxDepth)
init(rootNode: T) {
if rootNode.hasNodes { pushNode(rootNode) }
if rootNode.hasPayload { setupPayloadNode(rootNode) }
init(rootNode: T) {
if rootNode.hasNodes { pushNode(rootNode) }
if rootNode.hasPayload { setupPayloadNode(rootNode) }
}
private mutating func setupPayloadNode(_ node: T) {
currentValueNode = node
currentValueCursor = 0
currentValueLength = node.payloadArity
}
private mutating func pushNode(_ node: T) {
currentStackLevel = currentStackLevel + 1
let cursorIndex = currentStackLevel * 2
let lengthIndex = currentStackLevel * 2 + 1
nodes[currentStackLevel] = node
nodeCursorsAndLengths[cursorIndex] = 0
nodeCursorsAndLengths[lengthIndex] = node.nodeArity
}
private mutating func popNode() {
currentStackLevel = currentStackLevel - 1
}
///
/// Searches for next node that contains payload values,
/// and pushes encountered sub-nodes on a stack for depth-first traversal.
///
private mutating func searchNextValueNode() -> Bool {
while currentStackLevel >= 0 {
let cursorIndex = currentStackLevel * 2
let lengthIndex = currentStackLevel * 2 + 1
let nodeCursor = nodeCursorsAndLengths[cursorIndex]
let nodeLength = nodeCursorsAndLengths[lengthIndex]
if nodeCursor < nodeLength {
nodeCursorsAndLengths[cursorIndex] += 1
let currentNode = nodes[currentStackLevel]!
let nextNode = currentNode.getNode(nodeCursor)
if nextNode.hasNodes { pushNode(nextNode) }
if nextNode.hasPayload { setupPayloadNode(nextNode) ; return true }
} else {
popNode()
}
}
private mutating func setupPayloadNode(_ node: T) {
currentValueNode = node
currentValueCursor = 0
currentValueLength = node.payloadArity
}
return false
}
private mutating func pushNode(_ node: T) {
currentStackLevel = currentStackLevel + 1
let cursorIndex = currentStackLevel * 2
let lengthIndex = currentStackLevel * 2 + 1
nodes[currentStackLevel] = node
nodeCursorsAndLengths[cursorIndex] = 0
nodeCursorsAndLengths[lengthIndex] = node.nodeArity
}
private mutating func popNode() {
currentStackLevel = currentStackLevel - 1
}
///
/// Searches for next node that contains payload values,
/// and pushes encountered sub-nodes on a stack for depth-first traversal.
///
private mutating func searchNextValueNode() -> Bool {
while currentStackLevel >= 0 {
let cursorIndex = currentStackLevel * 2
let lengthIndex = currentStackLevel * 2 + 1
let nodeCursor = nodeCursorsAndLengths[cursorIndex]
let nodeLength = nodeCursorsAndLengths[lengthIndex]
if nodeCursor < nodeLength {
nodeCursorsAndLengths[cursorIndex] += 1
let currentNode = nodes[currentStackLevel]!
let nextNode = currentNode.getNode(nodeCursor)
if nextNode.hasNodes { pushNode(nextNode) }
if nextNode.hasPayload { setupPayloadNode(nextNode) ; return true }
} else {
popNode()
}
}
return false
}
mutating func hasNext() -> Bool {
return (currentValueCursor < currentValueLength) || searchNextValueNode()
}
mutating func hasNext() -> Bool {
return (currentValueCursor < currentValueLength) || searchNextValueNode()
}
}
///
/// Base class for fixed-stack iterators that traverse a hash-trie in reverse order. The base
/// iterator performs a depth-first post-order traversal, traversing sub-nodes (right to left).
///
/// Base class for fixed-stack iterators that traverse a hash-trie in reverse
/// order. The base iterator performs a depth-first post-order traversal,
/// traversing sub-nodes (right to left).
struct BaseReverseIterator<T: Node> {
var currentValueCursor: Int = -1
var currentValueNode: T? = nil
var currentValueCursor: Int = -1
var currentValueNode: T? = nil
private var currentStackLevel: Int = -1
private var nodeIndex: [Int] = Array(repeating: 0, count: maxDepth + 1)
private var nodeStack: [T?] = Array(repeating: nil, count: maxDepth + 1)
private var currentStackLevel: Int = -1
private var nodeIndex: [Int] = Array(repeating: 0, count: maxDepth + 1)
private var nodeStack: [T?] = Array(repeating: nil, count: maxDepth + 1)
init(rootNode: T) {
pushNode(rootNode)
searchNextValueNode()
}
init(rootNode: T) {
pushNode(rootNode)
searchNextValueNode()
}
private mutating func setupPayloadNode(_ node: T) {
currentValueNode = node
currentValueCursor = node.payloadArity - 1
}
private mutating func setupPayloadNode(_ node: T) {
currentValueNode = node
currentValueCursor = node.payloadArity - 1
}
private mutating func pushNode(_ node: T) {
currentStackLevel = currentStackLevel + 1
private mutating func pushNode(_ node: T) {
currentStackLevel = currentStackLevel + 1
nodeStack[currentStackLevel] = node
nodeIndex[currentStackLevel] = node.nodeArity - 1
}
nodeStack[currentStackLevel] = node
nodeIndex[currentStackLevel] = node.nodeArity - 1
}
private mutating func popNode() {
currentStackLevel = currentStackLevel - 1
}
private mutating func popNode() {
currentStackLevel = currentStackLevel - 1
}
///
/// Searches for rightmost node that contains payload values,
/// and pushes encountered sub-nodes on a stack for depth-first traversal.
///
@discardableResult
private mutating func searchNextValueNode() -> Bool {
while currentStackLevel >= 0 {
let nodeCursor = nodeIndex[currentStackLevel] ; nodeIndex[currentStackLevel] = nodeCursor - 1
///
/// Searches for rightmost node that contains payload values,
/// and pushes encountered sub-nodes on a stack for depth-first traversal.
///
@discardableResult
private mutating func searchNextValueNode() -> Bool {
while currentStackLevel >= 0 {
let nodeCursor = nodeIndex[currentStackLevel]
nodeIndex[currentStackLevel] = nodeCursor - 1
if nodeCursor >= 0 {
let currentNode = nodeStack[currentStackLevel]!
let nextNode = currentNode.getNode(nodeCursor)
pushNode(nextNode)
} else {
let currNode = nodeStack[currentStackLevel]!
popNode()
if nodeCursor >= 0 {
let currentNode = nodeStack[currentStackLevel]!
let nextNode = currentNode.getNode(nodeCursor)
pushNode(nextNode)
} else {
let currNode = nodeStack[currentStackLevel]!
popNode()
if currNode.hasPayload { setupPayloadNode(currNode) ; return true }
}
if currNode.hasPayload {
setupPayloadNode(currNode)
return true
}
return false
}
}
mutating func hasNext() -> Bool {
return (currentValueCursor >= 0) || searchNextValueNode()
}
return false
}
mutating func hasNext() -> Bool {
return (currentValueCursor >= 0) || searchNextValueNode()
}
}
func rangeInsert<T>(_ element: T, at index: Int, intoRange range: Range<UnsafeMutablePointer<T>>) {
let seq = range.dropFirst(index)
func rangeInsert<T>(
_ element: T,
at index: Int,
intoRange range: Range<UnsafeMutablePointer<T>>
) {
let seq = range.dropFirst(index)
let src = seq.startIndex
let dst = src.successor()
let src = seq.startIndex
let dst = src.successor()
dst.moveInitialize(from: src, count: seq.count)
dst.moveInitialize(from: src, count: seq.count)
src.initialize(to: element)
src.initialize(to: element)
}
// NEW
@inlinable
@inline(__always)
func rangeInsert<T>(_ element: T, at index: Int, into baseAddress: UnsafeMutablePointer<T>, count: Int) {
let src = baseAddress.advanced(by: index)
let dst = src.successor()
func rangeInsert<T>(
_ element: T,
at index: Int,
into baseAddress: UnsafeMutablePointer<T>,
count: Int
) {
let src = baseAddress.advanced(by: index)
let dst = src.successor()
dst.moveInitialize(from: src, count: count - index)
dst.moveInitialize(from: src, count: count - index)
src.initialize(to: element)
src.initialize(to: element)
}
// `index` is the logical index starting at the rear, indexing to the left
func rangeInsertReversed<T>(_ element: T, at index: Int, intoRange range: Range<UnsafeMutablePointer<T>>) {
let seq = range.dropLast(index)
func rangeInsertReversed<T>(
_ element: T,
at index: Int,
intoRange range: Range<UnsafeMutablePointer<T>>
) {
let seq = range.dropLast(index)
let src = seq.startIndex
let dst = src.predecessor()
let src = seq.startIndex
let dst = src.predecessor()
dst.moveInitialize(from: src, count: seq.count)
dst.moveInitialize(from: src, count: seq.count)
// requires call to predecessor on "past the end" position
seq.endIndex.predecessor().initialize(to: element)
// requires call to predecessor on "past the end" position
seq.endIndex.predecessor().initialize(to: element)
}
func rangeRemove<T>(at index: Int, fromRange range: Range<UnsafeMutablePointer<T>>) {
let seq = range.dropFirst(index + 1)
func rangeRemove<T>(
at index: Int,
fromRange range: Range<UnsafeMutablePointer<T>>
) {
let seq = range.dropFirst(index + 1)
let src = seq.startIndex
let dst = src.predecessor()
let src = seq.startIndex
let dst = src.predecessor()
dst.deinitialize(count: 1)
dst.moveInitialize(from: src, count: seq.count)
dst.deinitialize(count: 1)
dst.moveInitialize(from: src, count: seq.count)
}
// NEW
@inlinable
@inline(__always)
func rangeRemove<T>(at index: Int, from baseAddress: UnsafeMutablePointer<T>, count: Int) {
let src = baseAddress.advanced(by: index + 1)
let dst = src.predecessor()
func rangeRemove<T>(
at index: Int,
from baseAddress: UnsafeMutablePointer<T>,
count: Int
) {
let src = baseAddress.advanced(by: index + 1)
let dst = src.predecessor()
dst.deinitialize(count: 1)
dst.moveInitialize(from: src, count: count - index - 1)
dst.deinitialize(count: 1)
dst.moveInitialize(from: src, count: count - index - 1)
}
// `index` is the logical index starting at the rear, indexing to the left
func rangeRemoveReversed<T>(at index: Int, fromRange range: Range<UnsafeMutablePointer<T>>) {
let seq = range.dropLast(index + 1)
func rangeRemoveReversed<T>(
at index: Int, fromRange range: Range<UnsafeMutablePointer<T>>
) {
let seq = range.dropLast(index + 1)
let src = seq.startIndex
let dst = src.successor()
let src = seq.startIndex
let dst = src.successor()
seq.endIndex.deinitialize(count: 1)
dst.moveInitialize(from: src, count: seq.count)
seq.endIndex.deinitialize(count: 1)
dst.moveInitialize(from: src, count: seq.count)
}
@@ -10,20 +10,20 @@
//===----------------------------------------------------------------------===//
struct DictionaryEffect<Value> {
var modified: Bool = false
var previousValue: Value?
mutating func setModified() {
self.modified = true
}
mutating func setModified(previousValue: Value) {
self.modified = true
self.previousValue = previousValue
}
mutating func setReplacedValue(previousValue: Value) {
self.modified = true
self.previousValue = previousValue
}
var modified: Bool = false
var previousValue: Value?
mutating func setModified() {
self.modified = true
}
mutating func setModified(previousValue: Value) {
self.modified = true
self.previousValue = previousValue
}
mutating func setReplacedValue(previousValue: Value) {
self.modified = true
self.previousValue = previousValue
}
}
@@ -10,16 +10,28 @@
//===----------------------------------------------------------------------===//
protocol DictionaryNode: Node {
associatedtype Key: Hashable
associatedtype Value
associatedtype Key: Hashable
associatedtype Value
func get(_ key: Key, _ hash: Int, _ shift: Int) -> Value?
func get(_ key: Key, _ hash: Int, _ shift: Int) -> Value?
func containsKey(_ key: Key, _ hash: Int, _ shift: Int) -> Bool
func containsKey(_ key: Key, _ hash: Int, _ shift: Int) -> Bool
func index(_ key: Key, _ hash: Int, _ shift: Int, _ skippedBefore: Int) -> PersistentDictionaryIndex?
func index(
_ key: Key, _ hash: Int, _ shift: Int, _ skippedBefore: Int
) -> PersistentDictionaryIndex?
func updateOrUpdating(_ isStorageKnownUniquelyReferenced: Bool, _ key: Key, _ value: Value, _ hash: Int, _ shift: Int, _ effect: inout DictionaryEffect<Value>) -> ReturnBitmapIndexedNode
func updateOrUpdating(
_ isStorageKnownUniquelyReferenced: Bool,
_ key: Key, _ value: Value, _ hash: Int,
_ shift: Int,
_ effect: inout DictionaryEffect<Value>
) -> ReturnBitmapIndexedNode
func removeOrRemoving(_ isStorageKnownUniquelyReferenced: Bool, _ key: Key, _ hash: Int, _ shift: Int, _ effect: inout DictionaryEffect<Value>) -> ReturnBitmapIndexedNode
func removeOrRemoving(
_ isStorageKnownUniquelyReferenced: Bool,
_ key: Key, _ hash: Int,
_ shift: Int,
_ effect: inout DictionaryEffect<Value>
) -> ReturnBitmapIndexedNode
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -2,7 +2,7 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Copyright (c) 2021-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
@@ -2,44 +2,46 @@
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Copyright (c) 2021-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
//
//===----------------------------------------------------------------------===//
final class CollidableInt: CustomStringConvertible, CustomDebugStringConvertible, Equatable, Hashable {
let value: Int
let hashValue: Int
init(_ value: Int) {
self.value = value
self.hashValue = value
}
init(_ value: Int, _ hashValue: Int) {
self.value = value
self.hashValue = hashValue
}
var description: String {
return "\(value)"
}
var debugDescription: String {
return "\(value) [hash = \(hashValue)]"
}
func hash(into hasher: inout Hasher) {
hasher.combine(hashValue)
}
static func == (lhs: CollidableInt, rhs: CollidableInt) -> Bool {
if lhs.value == rhs.value {
precondition(lhs.hashValue == rhs.hashValue)
return true
}
return false
final class CollidableInt:
CustomStringConvertible, CustomDebugStringConvertible, Equatable, Hashable
{
let value: Int
let hashValue: Int
init(_ value: Int) {
self.value = value
self.hashValue = value
}
init(_ value: Int, _ hashValue: Int) {
self.value = value
self.hashValue = hashValue
}
var description: String {
return "\(value)"
}
var debugDescription: String {
return "\(value) [hash = \(hashValue)]"
}
func hash(into hasher: inout Hasher) {
hasher.combine(hashValue)
}
static func == (lhs: CollidableInt, rhs: CollidableInt) -> Bool {
if lhs.value == rhs.value {
precondition(lhs.hashValue == rhs.hashValue)
return true
}
return false
}
}