Merge pull request #175 from lorentey/PersistentCollections-updates

Persistent collections updates
This commit is contained in:
Karoy Lorentey authored and GitHub committed 2022-09-09 12:39:11 -07:00
commit 366850d69d
17 files changed
+746 -607

No files matched your search

@@ -36,12 +36,12 @@ extension PersistentDictionary: Collection {
/// Returns the index for the given key.
public func index(forKey key: Key) -> Index? {
rootNode.index(key, _computeHash(key), 0, 0)
rootNode.index(forKey: key, _HashPath(key), 0)
}
/// Accesses the key-value pair at the specified position.
public subscript(position: Index) -> Element {
rootNode.get(position: position, 0, position._value)
rootNode.item(position: position._value)
}
}
File diff suppressed because it is too large. Load diff
@@ -69,7 +69,7 @@ public struct PersistentDictionary<Key, Value> where Key: Hashable {
public subscript(key: Key) -> Value? {
get {
return get(key)
return _get(key)
}
mutating set(optionalValue) {
if let value = optionalValue {
@@ -85,7 +85,7 @@ public struct PersistentDictionary<Key, Value> where Key: Hashable {
default defaultValue: @autoclosure () -> Value
) -> Value {
get {
return get(key) ?? defaultValue()
return _get(key) ?? defaultValue()
}
mutating set(value) {
updateValue(value, forKey: key)
@@ -93,11 +93,11 @@ public struct PersistentDictionary<Key, Value> where Key: Hashable {
}
public func contains(_ key: Key) -> Bool {
rootNode.containsKey(key, _computeHash(key), 0)
rootNode.containsKey(key, _HashPath(key))
}
func get(_ key: Key) -> Value? {
rootNode.get(key, _computeHash(key), 0)
func _get(_ key: Key) -> Value? {
rootNode.get(key, _HashPath(key))
}
@discardableResult
@@ -105,9 +105,8 @@ public struct PersistentDictionary<Key, Value> where Key: Hashable {
let isUnique = isKnownUniquelyReferenced(&self.rootNode)
var effect = _DictionaryEffect<Value>()
let keyHash = _computeHash(key)
let newRootNode = rootNode.updateOrUpdating(
isUnique, key, value, keyHash, 0, &effect)
isUnique, (key, value), _HashPath(key), &effect)
if effect.modified {
self.rootNode = newRootNode
@@ -120,13 +119,11 @@ public struct PersistentDictionary<Key, Value> where Key: Hashable {
// 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)
false, (key, value), _HashPath(key), &effect)
if effect.modified {
return Self(newRootNode)
} else { return self }
guard effect.modified else { return self }
return Self(newRootNode)
}
@discardableResult
@@ -134,9 +131,8 @@ public struct PersistentDictionary<Key, Value> where Key: Hashable {
let isUnique = isKnownUniquelyReferenced(&self.rootNode)
var effect = _DictionaryEffect<Value>()
let keyHash = _computeHash(key)
let newRootNode = rootNode.removeOrRemoving(
isUnique, key, keyHash, 0, &effect)
isUnique, key, _HashPath(key), &effect)
if effect.modified {
self.rootNode = newRootNode
@@ -149,8 +145,8 @@ public struct PersistentDictionary<Key, Value> where Key: Hashable {
// 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)
let newRootNode = rootNode.removeOrRemoving(
false, key, _HashPath(key), &effect)
if effect.modified {
return Self(newRootNode)
@@ -9,6 +9,7 @@
//
//===----------------------------------------------------------------------===//
#if false
/// 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).
@@ -73,4 +74,4 @@ internal struct _BaseReverseIterator<T: _NodeProtocol> {
return (currentValueCursor >= 0) || searchNextValueNode()
}
}
#endif
@@ -1,29 +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
//
//===----------------------------------------------------------------------===//
#if false
extension PersistentDictionary._Node {
final func count(upTo mask: Int) -> Int {
let bitpos = _bitposFrom(mask)
let dataIndex = _indexFrom(dataMap, mask, bitpos)
let trieIndex = _indexFrom(trieMap, mask, bitpos)
let buffer = UnsafeMutableBufferPointer(
start: trieBaseAddress, count: header.trieCount)
let children = buffer.prefix(upTo: trieIndex).map { $0.count }.reduce(0, +)
let count = dataIndex + children
assert(count == _counts.prefix(upTo: mask).reduce(0, +))
return count
}
}
#endif
@@ -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 UInt32 {
@inlinable @inline(__always)
var _nonzeroBitCount: Self {
Self(truncatingIfNeeded: nonzeroBitCount)
}
@inlinable @inline(__always)
@_effects(readnone)
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(readnone)
@usableFromInline
func _bit(ranked n: Int) -> UInt? {
assert(n >= 0 && n < Self.bitWidth)
var shift: Self = 0
var n: Self = UInt32(truncatingIfNeeded: n)
let c16 = (self & 0xFFFF)._nonzeroBitCount
if n >= c16 {
shift = 16
n -= c16
}
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)
}
}
+147
View File
@@ -0,0 +1,147 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A set of `_Bucket` values, represented by a 32-bit wide bitset.
internal struct _Bitmap {
internal typealias Value = UInt32
internal var _value: Value
@inline(__always)
init(_value: Value) {
self._value = _value
}
@inline(__always)
init(bitPattern: Int) {
self._value = Value(bitPattern)
}
@inline(__always)
internal init() {
_value = 0
}
@inline(__always)
internal init(_ bucket: _Bucket) {
assert(bucket.value < Self.capacity)
_value = (1 &<< bucket.value)
}
@inline(__always)
internal init(_ bucket1: _Bucket, _ bucket2: _Bucket) {
assert(bucket1.value < Self.capacity && bucket2.value < Self.capacity)
assert(bucket1 != bucket2)
_value = (1 &<< bucket1.value) | (1 &<< bucket2.value)
}
internal init(upTo bucket: _Bucket) {
assert(bucket.value < Self.capacity)
_value = (1 &<< bucket.value) &- 1
}
}
extension _Bitmap: Equatable {
@inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left._value == right._value
}
}
extension _Bitmap {
@inline(__always)
internal static var empty: Self { .init() }
@inline(__always)
internal static var capacity: Int { Value.bitWidth }
@inline(__always)
internal var count: Int { _value.nonzeroBitCount }
@inline(__always)
internal var capacity: Int { Value.bitWidth }
@inline(__always)
internal var isEmpty: Bool { _value == 0 }
}
extension _Bitmap {
@inline(__always)
internal func contains(_ bucket: _Bucket) -> Bool {
assert(bucket.value < capacity)
return _value & (1 &<< bucket.value) != 0
}
@inline(__always)
internal mutating func insert(_ bucket: _Bucket) {
assert(bucket.value < capacity)
_value |= (1 &<< bucket.value)
}
@inline(__always)
internal mutating func remove(_ bucket: _Bucket) {
assert(bucket.value < capacity)
_value &= ~(1 &<< bucket.value)
}
@inline(__always)
internal func offset(of bucket: _Bucket) -> Int {
_value._rank(ofBit: bucket.value)
}
@inline(__always)
internal func bucket(at offset: Int) -> _Bucket {
_Bucket(_value._bit(ranked: offset)!)
}
}
extension _Bitmap {
@inline(__always)
internal func isDisjoint(with other: Self) -> Bool {
_value & other._value != 0
}
@inline(__always)
internal func union(_ other: Self) -> Self {
Self(_value: _value | other._value)
}
@inline(__always)
internal func intersection(_ other: Self) -> Self {
Self(_value: _value & other._value)
}
@inline(__always)
internal func symmetricDifference(_ other: Self) -> Self {
Self(_value: _value & other._value)
}
@inline(__always)
internal func subtracting(_ other: Self) -> Self {
Self(_value: _value & ~other._value)
}
}
extension _Bitmap: Sequence, IteratorProtocol {
var underestimatedCount: Int { count }
func makeIterator() -> _Bitmap { self }
/// Return the index of the lowest set bit in this word,
/// and also destructively clear it.
@inlinable
internal mutating func next() -> _Bucket? {
guard _value != 0 else { return nil }
let bucket = _Bucket(UInt(bitPattern: _value.trailingZeroBitCount))
_value &= _value &- 1 // Clear lowest nonzero bit.
return bucket
}
}
@@ -0,0 +1,35 @@
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Identifies an entry in the hash table inside a node.
/// (Internally, a number between 0 and 31.)
internal struct _Bucket {
var value: UInt
init(_ value: UInt) { self.value = value }
static var bitWidth: Int { _Bitmap.capacity.trailingZeroBitCount }
static var bitMask: UInt { UInt(bitPattern: _Bitmap.capacity) &- 1 }
}
extension _Bucket: Equatable {
@inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
}
extension _Bucket: Comparable {
@inline(__always)
internal static func <(left: Self, right: Self) -> Bool {
left.value < right.value
}
}
+9 -26
View File
@@ -13,35 +13,18 @@ internal func _computeHash<T: Hashable>(_ value: T) -> Int {
value.hashValue
}
internal let _bitPartitionSize: Int = 5
@inline(__always)
internal var _bitPartitionSize: Int { 5 }
internal let _bitPartitionMask: Int = (1 << _bitPartitionSize) - 1
@inline(__always)
internal var _bitPartitionMask: Int { (1 << _bitPartitionSize) - 1 }
internal let _hashCodeLength: Int = Int.bitWidth
@inline(__always)
internal var _hashCodeLength: Int { Int.bitWidth }
internal let _maxDepth = (_hashCodeLength + _bitPartitionSize - 1) / _bitPartitionSize
internal func _maskFrom(_ hash: Int, _ shift: Int) -> Int {
(hash >> shift) & _bitPartitionMask
}
internal func _bitposFrom(_ mask: Int) -> _NodeHeader.Bitmap {
1 << mask
}
internal func _indexFrom(
_ bitmap: _NodeHeader.Bitmap,
_ bitpos: _NodeHeader.Bitmap
) -> Int {
(bitmap & (bitpos &- 1)).nonzeroBitCount
}
internal func _indexFrom(
_ bitmap: _NodeHeader.Bitmap,
_ mask: Int,
_ bitpos: _NodeHeader.Bitmap
) -> Int {
(bitmap == _NodeHeader.Bitmap.max) ? mask : _indexFrom(bitmap, bitpos)
@inline(__always)
internal var _maxDepth: Int {
(_hashCodeLength + _bitPartitionSize - 1) / _bitPartitionSize
}
// NEW
@@ -10,29 +10,31 @@
//===----------------------------------------------------------------------===//
// FIXME: Remove
internal protocol _DictionaryNodeProtocol: _NodeProtocol {
internal protocol _DictionaryNodeProtocol: _NodeProtocol
where Element == (key: Key, value: Value)
{
associatedtype Key: Hashable
associatedtype Value
func get(_ key: Key, _ hash: Int, _ shift: Int) -> Value?
func get(_ key: Key, _ path: _HashPath) -> Value?
func containsKey(_ key: Key, _ hash: Int, _ shift: Int) -> Bool
func containsKey(_ key: Key, _ path: _HashPath) -> Bool
func index(
_ key: Key, _ hash: Int, _ shift: Int, _ skippedBefore: Int
forKey key: Key, _ path: _HashPath, _ skippedBefore: Int
) -> PersistentDictionary<Key, Value>.Index?
func updateOrUpdating(
_ isStorageKnownUniquelyReferenced: Bool,
_ key: Key, _ value: Value, _ hash: Int,
_ shift: Int,
_ isUnique: Bool,
_ item: Element,
_ path: _HashPath,
_ effect: inout _DictionaryEffect<Value>
) -> ReturnBitmapIndexedNode
) -> Self
func removeOrRemoving(
_ isStorageKnownUniquelyReferenced: Bool,
_ key: Key, _ hash: Int,
_ shift: Int,
_ key: Key,
_ path: _HashPath,
_ effect: inout _DictionaryEffect<Value>
) -> ReturnBitmapIndexedNode
) -> Self
}
@@ -0,0 +1,52 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A structure for slicing up a hash value into a series of bucket values,
/// representing a path inside the prefix tree.
internal struct _HashPath {
internal var _hash: _HashValue
internal var _shift: UInt
internal init(_hash: _HashValue, shift: UInt) {
self._hash = _hash
self._shift = shift
}
internal init<Key: Hashable>(_ key: Key) {
_hash = _HashValue(key)
_shift = 0
}
internal var currentBucket: _Bucket {
precondition(_shift < UInt.bitWidth, "Ran out of hash bits")
return _Bucket((_hash.value &>> _shift) & _Bucket.bitMask)
}
internal var isAtRoot: Bool { _shift == 0 }
internal func descend() -> _HashPath {
// FIXME: Consider returning nil when we run out of bits
let s = _shift &+ UInt(bitPattern: _Bucket.bitWidth)
return _HashPath(_hash: _hash, shift: s)
}
internal func ascend() -> _HashPath {
precondition(_shift >= _Bucket.bitWidth)
let s = _shift &- UInt(bitPattern: _Bucket.bitWidth)
return _HashPath(_hash: _hash, shift: s)
}
internal func top() -> _HashPath {
var result = self
result._shift = 0
return result
}
}
@@ -9,8 +9,19 @@
//
//===----------------------------------------------------------------------===//
//extension PersistentDictionary: CVarArg {
// public var _cVarArgEncoding: [Int] {
// <#code#>
// }
//}
/// An abstract representation of a hash value.
internal struct _HashValue {
internal var value: UInt
internal init<Key: Hashable>(_ key: Key) {
let hashValue = key._rawHashValue(seed: 0)
self.value = UInt(bitPattern: hashValue)
}
}
extension _HashValue: Equatable {
@inline(__always)
internal static func ==(left: Self, right: Self) -> Bool {
left.value == right.value
}
}
@@ -10,8 +10,7 @@
//===----------------------------------------------------------------------===//
protocol _NodeProtocol: AnyObject {
associatedtype ReturnPayload
associatedtype ReturnBitmapIndexedNode: _NodeProtocol
associatedtype Element
var hasNodes: Bool { get }
@@ -23,7 +22,7 @@ protocol _NodeProtocol: AnyObject {
var payloadArity: Int { get }
func getPayload(_ index: Int) -> ReturnPayload
func getPayload(_ index: Int) -> Element
var count: Int { get }
}
@@ -1,43 +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
//
//===----------------------------------------------------------------------===//
extension FixedWidthInteger {
internal func _nonzeroBits() -> _NonzeroBits<Self> {
return _NonzeroBits(from: self)
}
internal func _zeroBits() -> _NonzeroBits<Self> {
return _NonzeroBits(from: ~self)
}
}
internal struct _NonzeroBits<_Bitmap: FixedWidthInteger>
: Sequence, IteratorProtocol, CustomStringConvertible
{
var bitmap: _Bitmap
init(from bitmap: _Bitmap) {
self.bitmap = bitmap
}
public mutating func next() -> Int? {
guard bitmap != 0 else { return nil }
let index = bitmap.trailingZeroBitCount
bitmap ^= 1 << index
return index
}
public var description: String {
"[\(self.map { $0.description }.joined(separator: ", "))]"
}
}
@@ -13,19 +13,14 @@ import _CollectionsTestSupport
import XCTest
@testable import PersistentCollections
#if false
final class BitmapSmokeTests: CollectionTestCase {
typealias Bitmap = _NodeHeader.Bitmap
typealias Capacity = _NodeHeader.Capacity
func test_BitPartitionSize_isValid() {
expectTrue(_bitPartitionSize > 0)
expectTrue((2 << (_bitPartitionSize - 1)) != 0)
expectTrue((2 << (_bitPartitionSize - 1)) <= Bitmap.bitWidth)
}
func test_Capacity_isValid() {
expectTrue(Int(2 << _bitPartitionSize) <= Int(Capacity.max))
}
func test_Bitmap_nonzeroBits() {
let bitmap: Bitmap = 0b0100_0000_0000_1011
@@ -66,3 +61,4 @@ final class BitmapSmokeTests: CollectionTestCase {
expectNil(zipIterator.next())
}
}
#endif
@@ -13,16 +13,16 @@ final class CollidableInt:
CustomStringConvertible, CustomDebugStringConvertible, Equatable, Hashable
{
let value: Int
let hashValue: Int
let _hashValue: Int
init(_ value: Int) {
self.value = value
self.hashValue = value
self._hashValue = value
}
init(_ value: Int, _ hashValue: Int) {
self.value = value
self.hashValue = hashValue
self._hashValue = hashValue
}
var description: String {
@@ -30,16 +30,24 @@ final class CollidableInt:
}
var debugDescription: String {
return "\(value) [hash = \(hashValue)]"
return "\(value) [hash = \(_hashValue)]"
}
func _rawHashValue(seed: Int) -> Int {
_hashValue
}
func hash(into hasher: inout Hasher) {
hasher.combine(hashValue)
fatalError()
}
var hashValue: Int {
fatalError()
}
static func == (lhs: CollidableInt, rhs: CollidableInt) -> Bool {
if lhs.value == rhs.value {
precondition(lhs.hashValue == rhs.hashValue)
precondition(lhs._hashValue == rhs._hashValue)
return true
}
return false
@@ -41,6 +41,7 @@
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
enableASanStackUseAfterReturn = "YES"
codeCoverageEnabled = "YES">
<Testables>
<TestableReference