Files
swift-collections/Sources/PersistentCollections/PersistentDictionary/PersistentDictionary.swift
T
Karoy Lorentey c9ca59fbb9 [PersistentCollections] Improved storage representation
- Switch to using `ManagedBuffer` to represent node storage. This has
  useful performance benefits, but it significantly complicates access
  to node data. We no longer have direct access to the underlying raw
  storage: everything needs to go through closures passed to
  `ManagedBuffer.withUnsafeMutablePointers`.

- Introduce `struct _Node` and `struct _Node.UnsafeHandle` to
  represent a (strong) reference to a hash tree node, and a
  convenient handle for node storage, respectively. Use these instead
  of directly accessing the ManagedBuffer object, whenever feasible.

- Implement separate paths for in-place mutations vs copy-on-write
  operation, optimizing both flavors.

- Go to great lengths to eliminate unnecessary retain-release traffic,
  whenever possible.

- Push subtree counts into parent nodes by moving the corresponding
  field from the node header into the `_Node` struct. (This results in
  a cool ~20x speedup for jumping around in the tree by integer
  offsets.)

- Implement a type-punned empty root singleton, to allow creating
  empty trees without allocating anything.
2022-09-13 23:48:54 -07:00

148 lines
3.5 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// 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
//
//===----------------------------------------------------------------------===//
public struct PersistentDictionary<Key, Value> where Key: Hashable {
@usableFromInline
internal typealias _Node = PersistentCollections._Node<Key, Value>
@usableFromInline
var _root: _Node
@inlinable
internal init(_root: _Node) {
self._root = _root
}
}
extension PersistentDictionary {
@inlinable
public init() {
self.init(_root: _Node(_storage: _emptySingleton, count: 0))
}
@inlinable
public init(_ other: PersistentDictionary<Key, Value>) {
self = other
}
@inlinable
public func _invariantCheck() {
_root._fullInvariantCheck(.top, _Hash(_value: 0))
}
@inlinable
@inline(__always)
public init<S: Sequence>(
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<Keys: Sequence, Values: Sequence>(
uniqueKeys keys: Keys,
values: Values
) where Keys.Element == Key, Values.Element == Value {
self.init(uniqueKeysWithValues: zip(keys, values))
}
@inlinable
public subscript(key: Key) -> Value? {
get {
return _get(key)
}
mutating set(optionalValue) {
if let value = optionalValue {
updateValue(value, forKey: key)
} else {
removeValue(forKey: key)
}
}
}
@inlinable
public subscript(
key: Key,
default defaultValue: @autoclosure () -> Value
) -> Value {
get {
return _get(key) ?? defaultValue()
}
mutating set(value) {
updateValue(value, forKey: key)
}
}
@inlinable
public func contains(_ key: Key) -> Bool {
_root.containsKey(.top, key, _Hash(key))
}
@inlinable
func _get(_ key: Key) -> Value? {
_root.get(.top, key, _Hash(key))
}
/// Returns the index for the given key.
@inlinable
public func index(forKey key: Key) -> Index? {
_root.position(forKey: key, .top, _Hash(key)).map { Index(_value: $0) }
}
@inlinable
@discardableResult
public mutating func updateValue(
_ value: __owned Value, forKey key: Key
) -> Value? {
return _root.updateValue(value, forKey: key, .top, _Hash(key))
}
// fluid/immutable API
@inlinable
public func updatingValue(_ value: Value, forKey key: Key) -> Self {
var copy = self
copy.updateValue(value, forKey: key)
return copy
}
@inlinable
@discardableResult
public mutating func removeValue(forKey key: Key) -> Value? {
let old = _root.remove(key, .top, _Hash(key))
if old != nil, _root.isCollisionNode, _root.hasSingletonItem {
// Convert to regular node.
assert(_root.isUnique())
_root.update {
let hash = _Hash($0[item: 0].key)
$0.itemMap = _Bitmap(hash[.top])
$0.childMap = .empty
}
}
return old?.value
}
// fluid/immutable API
@inlinable
public func removingValue(forKey key: Key) -> Self {
var copy = self
copy.removeValue(forKey: key)
return copy
}
}