Files
swift-collections/Sources/PersistentCollections/_HashPath.swift
T
Karoy Lorentey 14f90620c8 [PersistentCollections] Introduce _Bucket, _Bitmap, _HashPath, and _HashValue
These provide nicer tools for slicing up hash values and dealing with node bitmaps.

_Bucket is a logical entry in the hash table inside a node.
_Bitmap is a set of bucket values, represented by a bitset.
_HashPath facilitates slicing up a hash value into a series of bucket values.
_HashValue represents a hash value.

This is still just mostly superficial refactoring, with little to no functional changes.
2022-09-09 00:47:10 -07:00

53 lines
1.5 KiB
Swift

//===----------------------------------------------------------------------===//
//
// 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
}
}