[BasicContainers] Add early drafts for RigidSet/RigidDictionary

This commit is contained in:
Karoy Lorentey committed 2026-02-16 17:15:59 -08:00
1 parent 934ad786d2
commit bf9a7033a0
36 files changed
+2411 -51

No files matched your search

@@ -0,0 +1,92 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 compiler(>=6.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS
/// This is a stand-in for the generalization of Equatable as described in SE-0499.
/// This is a temporary protocol that will be deprecated and later removed
/// when the official generalization becomes widely available.
public protocol GeneralizedEquatable: ~Copyable, ~Escapable {
/// Returns a Boolean value indicating whether two values are equal.
///
/// Equality is the inverse of inequality. For any values `a` and `b`,
/// `a == b` implies that `a != b` is `false`.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
static func == (lhs: borrowing Self, rhs: borrowing Self) -> Bool
}
/// This is a stand-in for the generalization of Hashable as described in SE-0499.
/// This is a temporary protocol that will be deprecated and later removed
/// when the official generalization becomes widely available.
public protocol GeneralizedHashable: GeneralizedEquatable, ~Copyable, ~Escapable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// Implement this method to conform to the `Hashable` protocol. The
/// components used for hashing must be the same as the components compared
/// in your type's `==` operator implementation. Call `hasher.combine(_:)`
/// with each of these components.
///
/// - Important: In your implementation of `hash(into:)`,
/// don't call `finalize()` on the `hasher` instance provided,
/// or replace it with a different instance.
/// Doing so may become a compile-time error in the future.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
func hash(into hasher: inout Hasher)
// Raw top-level hashing interface. Some standard library types (mostly
// primitives) specialize this to eliminate small resiliency overheads. (This
// only matters for tiny keys.)
func _rawHashValue(seed: Int) -> Int
}
extension GeneralizedHashable where Self: ~Copyable & ~Escapable {
/// The hash value.
///
/// Hash values are not guaranteed to be equal across different executions of
/// your program. Do not save hash values to use during a future execution.
@_alwaysEmitIntoClient
@inline(__always)
public var hashValue: Int {
_rawHashValue(seed: 0)
}
}
extension Int: GeneralizedHashable {}
extension Int8: GeneralizedHashable {}
extension Int16: GeneralizedHashable {}
extension Int32: GeneralizedHashable {}
extension Int64: GeneralizedHashable {}
@available(SwiftStdlib 6.0, *)
extension Int128: GeneralizedHashable {}
extension UInt: GeneralizedHashable {}
extension UInt8: GeneralizedHashable {}
extension UInt16: GeneralizedHashable {}
extension UInt32: GeneralizedHashable {}
extension UInt64: GeneralizedHashable {}
@available(SwiftStdlib 6.0, *)
extension UInt128: GeneralizedHashable {}
extension Float: GeneralizedHashable {}
extension Double: GeneralizedHashable {}
@available(SwiftStdlib 5.7, *)
extension Duration: GeneralizedHashable {}
extension String: GeneralizedHashable {}
extension Substring: GeneralizedHashable {}
extension Character: GeneralizedHashable {}
extension Bool: GeneralizedHashable {}
extension UnsafePointer: GeneralizedHashable {}
extension UnsafeMutablePointer: GeneralizedHashable {}
#endif
@@ -0,0 +1,85 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
#if compiler(>=6.2)
extension _HTable {
@usableFromInline
@frozen
package struct Bitmap: ~Copyable, ~Escapable {
@usableFromInline
package typealias Bucket = _HTable.Bucket
@_alwaysEmitIntoClient
package let _words: UnsafeMutableBufferPointer<Word>
@_alwaysEmitIntoClient
@_lifetime(borrow table)
package init(table: borrowing _HTable) {
self._words = .init(start: table._bitmap, count: table.wordCount)
}
}
}
extension _HTable.Bitmap {
@_transparent
@inlinable
package func isValid(_ bucket: Bucket) -> Bool {
bucket.word < _words.count
}
@_transparent
@inlinable
package func isOccupied(_ bucket: Bucket) -> Bool {
assert(isValid(bucket))
return _words[bucket.word].contains(bucket.bit)
}
@_transparent
@inlinable
package func setOccupied(_ bucket: Bucket) {
assert(isValid(bucket))
_words[bucket.word].set(bucket.bit)
}
@_transparent
@inlinable
package func clearOccupied(_ bucket: Bucket) {
assert(isValid(bucket))
_words[bucket.word].clear(bucket.bit)
}
@inlinable
package func firstUnoccupiedBucket(from start: Bucket) -> Bucket {
assert(isValid(start))
var word = start.word
var bits = _words[word]
bits.insertAll(upTo: start.bit)
var wrapped = false
while true {
bits.formComplement()
if let bit = bits.firstMember {
return Bucket(word: word, bit: bit)
}
word &+= 1
if word >= _words.count {
precondition(!wrapped, "Corrupt hash table")
wrapped = true
word = 0
}
bits = _words[word]
}
}
}
#endif
@@ -0,0 +1,151 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2026 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 !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
#if compiler(>=6.2)
extension _HTable {
/// Identifies a particular bucket within a hash table by its offset.
/// Having a dedicated wrapper type for this prevents passing a bucket number
/// to a function that expects a word index, or vice versa.
@usableFromInline
@frozen
package struct Bucket {
@usableFromInline
internal typealias Word = _HTable.Word
/// The distance of this bucket from the first bucket in the hash table.
@_alwaysEmitIntoClient
package var _offset: UInt
@inlinable
@_transparent
package init(offset: UInt) {
self._offset = offset
}
@inlinable
@_transparent
package init(offset: Int) {
assert(offset >= 0)
self._offset = UInt(bitPattern: offset)
}
@inlinable
@_transparent
package init(word: Int, bit: UInt) {
let word = UInt(bitPattern: word)
self.init(offset: (word &<< Word.wordShift) | (bit & Word.wordMask))
}
@inlinable
package var offset: Int {
@_transparent
get { Int(bitPattern: _offset) }
}
}
}
extension _HTable.Bucket: CustomStringConvertible {
@_transparent
@usableFromInline
package var description: String {
"⌗\(_offset)"
}
}
extension _HTable.Bucket: Equatable {
@_transparent
@usableFromInline
package static func == (left: Self, right: Self) -> Bool {
left.offset == right.offset
}
}
extension _HTable.Bucket: Comparable {
@_transparent
@usableFromInline
package static func < (left: Self, right: Self) -> Bool {
left.offset < right.offset
}
}
extension _HTable.Bucket {
@_alwaysEmitIntoClient
@_transparent
package var word: Int {
Int(truncatingIfNeeded: offset &>> Word.wordShift)
}
@_alwaysEmitIntoClient
@_transparent
package var bit: UInt {
_offset & Word.wordMask
}
@_alwaysEmitIntoClient
@_transparent
package var isOnWordBoundary: Bool {
bit == 0
}
@_alwaysEmitIntoClient
@_transparent
package mutating func advanceToNextWord() {
_offset &= ~Word.wordMask
_offset &+= 1 &<< Word.wordShift
}
}
extension UnsafeMutableBufferPointer where Element: ~Copyable {
@_alwaysEmitIntoClient
package subscript(bucket: _HTable.Bucket) -> Element {
@_transparent
unsafeAddress {
return .init(_ptr(at: bucket.offset))
}
@_transparent
nonmutating unsafeMutableAddress {
return _ptr(at: bucket.offset)
}
}
@_alwaysEmitIntoClient
@_transparent
package func _ptr(
at bucket: _HTable.Bucket
) -> UnsafeMutablePointer<Element> {
_ptr(at: bucket.offset)
}
@_alwaysEmitIntoClient
@_transparent
package func initializeElement(
at bucket: _HTable.Bucket,
to value: consuming Element
) {
initializeElement(at: bucket.offset, to: value)
}
}
extension Range where Bound == _HTable.Bucket {
@_alwaysEmitIntoClient
package var _offsets: Range<Int> {
@_transparent
get {
.init(uncheckedBounds: (lowerBound.offset, upperBound.offset))
}
}
}
#endif
@@ -0,0 +1,118 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
#if compiler(>=6.2)
extension _HTable {
/// The minimum hash table scale.
@_alwaysEmitIntoClient
@_transparent
internal static var minimumScale: Int {
@_effects(readnone)
get {
4
}
}
/// The maximum hash table scale.
@_alwaysEmitIntoClient
@_transparent
internal static var maximumScale: Int {
@_effects(readnone)
get {
Swift.min(Int.bitWidth &- 1, 56)
}
}
/// The maximum number of items for which we do not create a hash table.
@_alwaysEmitIntoClient
@_transparent
internal static var maximumUnhashedCount: Int {
@_effects(readnone)
get {
(1 &<< (minimumScale &- 1)) &- 1
}
}
@inlinable
@inline(__always)
package static func wordCount(forScale scale: UInt8) -> Int {
guard scale > 0 else { return 0 }
let shift = Swift.max(UInt(scale), Word.wordShift) - Word.wordShift
return 1 &<< shift
}
/// The numerator of the maximum hash table load factor.
@_alwaysEmitIntoClient
@_transparent
internal static var _maxLFNum: UInt { 7 }
/// The denominator of the maximum hash table load factor.
@_alwaysEmitIntoClient
@_transparent
internal static var _maxLFDenom: UInt { 8 }
/// The numerator of the minimum hash table load factor.
@_alwaysEmitIntoClient
@_transparent
internal static var _minLFNum: UInt { 1 }
/// The denominator of minimum hash table load factor.
@_alwaysEmitIntoClient
@_transparent
internal static var _minLFDenom: UInt { 8 }
/// The minimum number of items that can be held in a hash table of the given scale.
@usableFromInline
@_effects(readnone)
internal static func minimumCapacity(forScale scale: UInt8) -> Int {
guard scale >= minimumScale else { return 0 }
precondition(scale <= maximumScale)
let bucketCount: UInt = 1 &<< scale
return Int(bucketCount * _minLFNum / _minLFDenom)
}
/// The maximum number of items that can be held in a hash table of the given scale.
@usableFromInline
@_effects(readnone)
internal static func maximumCapacity(forScale scale: UInt8) -> Int {
guard scale >= minimumScale else { return maximumUnhashedCount }
let bucketCount: UInt = 1 &<< scale
return Int(bucketCount * _maxLFNum / _maxLFDenom)
}
/// The minimum hash table scale that can hold the specified number of elements.
@usableFromInline
@_effects(readnone)
internal static func minimumScale(forCapacity capacity: Int) -> UInt8 {
guard capacity > maximumUnhashedCount else { return 0 }
let capacity = UInt(truncatingIfNeeded: Swift.max(capacity, 1))
// Calculate the minimum number of entries we need to allocate to satisfy
// the maximum load factor. `capacity + 1` below ensures that we always
// leave at least one hole.
let minimumEntries = Swift.max(
((capacity + 1) * _maxLFDenom - 1) / _maxLFNum, // (capacity / maxLoadFactor).rounded(.up)
capacity + 1)
// The actual number of entries we need to allocate is the lowest power of
// two greater than or equal to the minimum entry count. Calculate its
// exponent.
let scale = (Swift.max(minimumEntries, 2) - 1)._binaryLogarithm() + 1
assert(scale >= minimumScale && scale <= maximumScale)
// The scale is the exponent corresponding to the bucket count.
assert(self.maximumCapacity(forScale: UInt8(scale)) >= capacity)
return UInt8(truncatingIfNeeded: scale)
}
}
#endif
@@ -0,0 +1,50 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
#if compiler(>=6.2)
extension _HTable {
@inlinable
internal func find_Small(
tester: (Bucket) -> Bool,
) -> Bucket? {
assert(isSmall)
// Linear search
var bucket = Bucket(offset: 0)
while bucket.offset < count {
if tester(bucket) { return bucket }
bucket._offset &+= 1
}
return nil
}
@inlinable
internal func find_Large(
hashValue: Int,
tester: (Bucket) -> Bool,
) -> Bucket? {
assert(!isSmall)
// Naive find
let start = idealBucket(forHashValue: hashValue)
var it = makeBucketIterator(from: start)
while it.isOccupied {
if tester(it.currentBucket) {
return it.currentBucket
}
it.wrapToNextBit()
}
return nil
}
}
#endif
@@ -0,0 +1,64 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 compiler(>=6.2)
extension _HTable {
@inlinable
internal mutating func insertNew_Small(
swapper: (Bucket) -> Void,
) -> Bucket {
assert(isSmall)
// FIXME: Scramble order by swapping things in some way
let r = Bucket(offset: _count)
_count &+= 1
return r
}
@inlinable
internal mutating func insertNew_Large(
hashValue: Int,
hashGenerator: (Bucket) -> Int,
swapper: (Bucket) -> Void,
) -> Bucket {
assert(!isSmall)
assert(!isFull)
#if COLLECTIONS_NO_ROBIN_HOOD_HASHING
let ideal = idealBucket(forHashValue: hashValue)
let actual = _bitmap.firstUnoccupiedBucket(from: b)
_totalProbeLength += probeLength(from: ideal, to: actual)
_bitmap.setOccupied(actual)
return actual
#else
var b = idealBucket(forHashValue: hashValue)
var probeLength = 0
while bitmap.isOccupied(b) {
probeLength &+= 1
_totalProbeLength &+= 1
let oldHashValue = hashGenerator(b)
let oldProbeLength = self.probeLength(
forHashValue: oldHashValue,
in: b)
if probeLength > oldProbeLength {
swapper(b)
probeLength = oldProbeLength
}
self.wrapBucket(after: &b)
}
_totalProbeLength &+= 1
bitmap.setOccupied(b)
_count &+= 1
return b
#endif
}
}
#endif
@@ -0,0 +1,331 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
#if compiler(>=6.2)
extension _HTable {
@_alwaysEmitIntoClient
@_lifetime(borrow self)
package func makeBucketIterator(
from start: Bucket = Bucket(offset: 0)
) -> BucketIterator {
BucketIterator(table: self, startingAt: start)
}
/// An iterator construct for visiting a chain of buckets within the hash
/// table. This is a convenient tool for implementing linear probing.
///
/// Beyond merely providing bucket values, bucket iterators can also tell
/// you their current opposition within the hash table, and (for mutable hash
/// tables) they allow you update the value of the currently visited bucket.
/// (This is useful when implementing simple insertions, for example.)
///
/// - Warning: Like `UnsafeHandle`, `BucketIterator` does not have
/// ownership of its underlying storage buffer. You must not escape
/// iterator values outside the closure call that produced the original
/// hash table.
@usableFromInline
@frozen
package struct BucketIterator: ~Copyable, ~Escapable {
@usableFromInline
package typealias Bucket = _HTable.Bucket
@usableFromInline
package typealias Word = _HTable.Word
/// The bitmap we are iterating over.
@_alwaysEmitIntoClient
package let _words: UnsafePointer<Word>?
@_alwaysEmitIntoClient
package let _endBucket: Bucket
@_alwaysEmitIntoClient
package var _bucket: Bucket
/// Remaining bits not yet processed from the last word read.
@_alwaysEmitIntoClient
package var _nextBits: Word
/// Number of remaining bits not yet processed from the last word read.
@_alwaysEmitIntoClient
package var _nextBitCount: UInt8
@_alwaysEmitIntoClient
package var _wrapped = false
/// Create a new iterator starting at the specified bucket.
@_effects(releasenone)
@usableFromInline
@_lifetime(borrow table)
package init(table: borrowing _HTable, startingAt bucket: Bucket) {
assert(table.isValid(bucket) || bucket == table.endBucket)
assert(table.endBucket.bit == 0 || table.endBucket.word == 0) // We rely on this throughout the code below
self._bucket = bucket
if let bitmap = table._bitmap {
self._words = .init(bitmap)
self._endBucket = table.endBucket
self._nextBits = bitmap[_bucket.word].shiftedDown(by: _bucket.bit)
if table.endBucket._offset < _Word.capacity {
self._nextBitCount = UInt8(table.endBucket.bit &- _bucket.bit)
} else {
self._nextBitCount = UInt8(_Word._capacity &- _bucket.bit)
}
} else {
self._words = nil
self._endBucket = Bucket(offset: table.count) // Note: not capacity!
self._nextBits = .empty
self._nextBitCount = 0
}
}
}
}
extension _HTable.BucketIterator {
@_alwaysEmitIntoClient
@_transparent
package var currentBucket: Bucket {
_bucket
}
@_alwaysEmitIntoClient
@_transparent
package var isAtEnd: Bool {
_bucket >= _endBucket
}
@_alwaysEmitIntoClient
@_transparent
package var isOccupied: Bool {
assert(!isAtEnd)
if _words == nil { return true }
return _nextBits.contains(0)
}
@_alwaysEmitIntoClient
@_transparent
package mutating func restart() {
_wrapped = true
_bucket._offset = 0
if let words = _words {
_nextBits = words[_bucket.word]
_nextBitCount = UInt8(Swift.min(_Word._capacity, _endBucket._offset))
}
}
@_alwaysEmitIntoClient
@_transparent
package mutating func _wrap() {
precondition(!_wrapped, "Corrupt hash table")
restart()
}
@_alwaysEmitIntoClient
@discardableResult
package mutating func _advanceToNextWord() -> Bool {
assert(!isAtEnd)
_bucket.advanceToNextWord()
if isAtEnd {
_bucket = _endBucket
_nextBits = .empty
_nextBitCount = 0
return false
}
if let words = _words{
_nextBits = words[_bucket.word]
_nextBitCount = UInt8(_Word._capacity)
}
return true
}
@_alwaysEmitIntoClient
package mutating func _wrapToNextWord() {
_bucket.advanceToNextWord()
if isAtEnd {
_wrap()
} else if let words = _words {
_nextBits = words[_bucket.word]
_nextBitCount = UInt8(_Word._capacity)
}
}
@_alwaysEmitIntoClient
@discardableResult
package mutating func advanceToNextBit() -> Bool {
assert(!isAtEnd)
_bucket._offset &+= 1
if isAtEnd {
_nextBits = .empty
_nextBitCount = 0
return false
}
guard let words = _words else { return true }
assert(_nextBitCount > 0)
_nextBitCount &-= 1
if _nextBitCount > 0 {
_nextBits = _nextBits.shiftedDown(by: 1)
} else {
assert(_bucket.bit == 0)
_nextBits = words[_bucket.word]
_nextBitCount = UInt8(_Word._capacity)
}
return true
}
@_alwaysEmitIntoClient
package mutating func wrapToNextBit() {
_bucket._offset &+= 1
if isAtEnd {
_wrap()
return
}
guard let words = _words else { return }
assert(_nextBitCount > 0)
_nextBitCount &-= 1
if _nextBitCount > 0 {
_nextBits = _nextBits.shiftedDown(by: 1)
} else {
_nextBits = words[_bucket.word]
_nextBitCount = UInt8(_Word._capacity)
}
}
/// If the current bucket is already occupied, this does nothing.
@_alwaysEmitIntoClient
@discardableResult
package mutating func advanceToOccupied() -> Bool {
if isAtEnd { return false }
guard _words != nil else {
return true
}
while true {
if let first = _nextBits.firstMember {
_nextBits = _nextBits.shiftedDown(by: first)
_bucket._offset &+= first
_nextBitCount &-= UInt8(first)
break
}
guard _advanceToNextWord() else { return false }
}
return true
}
@_alwaysEmitIntoClient
package mutating func wrapToOccupied() {
if _words == nil {
wrapToNextBit()
return
}
while true {
if let first = _nextBits.firstMember {
_nextBits = _nextBits.shiftedDown(by: first)
_nextBitCount &-= UInt8(first)
_bucket._offset &+= first
break
}
_wrapToNextWord()
}
}
/// If the current bucket is already unoccupied, this does nothing.
@_alwaysEmitIntoClient
@discardableResult
package mutating func advanceToUnoccupied() -> Bool {
assert(!isAtEnd)
if _words == nil {
_bucket = _endBucket
return false
}
while true {
let emptyBits = Word(upTo: UInt(_nextBitCount)).subtracting(_nextBits)
if let first = emptyBits.firstMember {
_nextBits = _nextBits.shiftedDown(by: first)
_nextBitCount &-= UInt8(first)
_bucket._offset &+= first
break
}
guard _advanceToNextWord() else { return false }
}
return true
}
/// If the current bucket is already unoccupied, this does nothing.
@_alwaysEmitIntoClient
@discardableResult
package mutating func advanceToUnoccupied(
maximumCount: Int = .max
) -> Bool {
assert(maximumCount > 0)
assert(!isAtEnd)
var remainder = UInt(bitPattern: maximumCount)
if _words == nil {
let delta = Swift.min(_endBucket._offset &- _bucket._offset, remainder)
_bucket._offset = _bucket._offset + delta
return false
}
while remainder > 0 {
let emptyBits = Word(upTo: UInt(_nextBitCount)).subtracting(_nextBits)
if let first = emptyBits.firstMember {
let c = Swift.min(remainder, first)
_nextBits = _nextBits.shiftedDown(by: c)
_nextBitCount &-= UInt8(c)
_bucket._offset &+= c
remainder &-= c
break
}
if remainder >= _nextBitCount {
remainder &-= UInt(_nextBitCount)
guard _advanceToNextWord() else { return false }
} else {
_nextBits = _nextBits.shiftedDown(by: remainder)
_nextBitCount &-= UInt8(remainder)
_bucket._offset &+= remainder
remainder = 0
break
}
}
return true
}
@_alwaysEmitIntoClient
package mutating func wrapToUnoccupied() {
if _words == nil {
_bucket = _endBucket
return
}
while true {
if let first = _nextBits.complement().firstMember {
_nextBits = _nextBits.shiftedDown(by: first)
_nextBitCount &-= UInt8(first)
_bucket._offset &+= first
break
}
_wrapToNextWord()
}
}
@_alwaysEmitIntoClient
package mutating func nextOccupiedRegion(
maximumCount: Int = .max
) -> Range<Bucket>? {
assert(maximumCount > 0)
guard self.advanceToOccupied() else { return nil }
assert(self.isOccupied)
let start = self.currentBucket
self.advanceToUnoccupied(maximumCount: maximumCount)
let end = self.currentBucket
return Range(uncheckedBounds: (start, end))
}
}
#endif
@@ -0,0 +1,34 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 compiler(>=6.2)
extension _HTable {
@usableFromInline
@frozen
internal enum Variant: ~Copyable {
case small(_HTable.Small)
case large(_HTable)
}
@usableFromInline
@frozen
internal struct Small: ~Copyable {
@_alwaysEmitIntoClient
internal var count: Int
@_transparent
@_alwaysEmitIntoClient
internal init() {
self.count = 0
}
}
}
#endif
@@ -0,0 +1,196 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
#if compiler(>=6.2)
@usableFromInline
@frozen
package struct _HTable: ~Copyable {
@usableFromInline
package typealias Word = _UnsafeBitSet._Word
@_alwaysEmitIntoClient
package var _count: Int
@_alwaysEmitIntoClient
package let capacity: Int
@_alwaysEmitIntoClient
package let _bitmap: UnsafeMutablePointer<Word>?
@_alwaysEmitIntoClient
package var _totalProbeLength: Int
@_alwaysEmitIntoClient
package let scale: UInt8
@inlinable
internal init(
_capacity: Int,
scale: UInt8
) {
assert(_capacity <= Self.maximumCapacity(forScale: scale))
self._count = 0
self.capacity = _capacity
self._totalProbeLength = 0
self.scale = scale
if scale == 0 {
self._bitmap = nil
} else {
assert(scale >= Self.minimumScale && scale <= Self.maximumScale)
let wordCount = _HTable.wordCount(forScale: scale)
let bitmap = UnsafeMutablePointer<Word>.allocate(capacity: wordCount)
bitmap.initialize(repeating: .empty, count: wordCount)
self._bitmap = bitmap
}
}
@inlinable
internal init(capacity: Int) {
assert(capacity >= 0)
self.init(
_capacity: capacity,
scale: Self.minimumScale(forCapacity: capacity))
}
@_alwaysEmitIntoClient
deinit {
_bitmap?.deallocate()
}
}
extension _HTable {
@_alwaysEmitIntoClient
@_transparent
package var isSmall: Bool {
_bitmap == nil
}
@_alwaysEmitIntoClient
@_transparent
package var count: Int {
_count
}
@_alwaysEmitIntoClient
@_transparent
package var isEmpty: Bool {
_count == 0
}
@_alwaysEmitIntoClient
@_transparent
package var isFull: Bool {
_count == capacity
}
@_alwaysEmitIntoClient
@_transparent
package var wordCount: Int {
if isSmall { return 0 }
return Word.wordCount(forBitCount: bucketCount)
}
}
extension _HTable {
@_alwaysEmitIntoClient
@_transparent
package var startBucket: Bucket {
Bucket(offset: 0)
}
@_alwaysEmitIntoClient
@_transparent
package var endBucket: Bucket {
Bucket(offset: bucketCount)
}
@_alwaysEmitIntoClient
@_transparent
package var bucketCount: UInt {
if isSmall { return UInt(bitPattern: capacity) }
return 1 &<< scale
}
@_transparent
@inlinable
package func isValid(_ bucket: Bucket) -> Bool {
bucket._offset < bucketCount
}
@_transparent
@inlinable
package func wrapBucket(after bucket: inout Bucket) {
assert(isValid(bucket))
bucket._offset &+= 1
if bucket._offset == bucketCount {
bucket._offset = 0
}
}
@_transparent
@inlinable
package func formBucket(after bucket: inout Bucket) {
assert(isValid(bucket))
bucket._offset &+= 1
}
@inlinable
package var bitmap: Bitmap {
@_lifetime(borrow self)
get {
Bitmap(table: self)
}
}
@_transparent
@inlinable
package func isOccupied(_ bucket: Bucket) -> Bool {
if isSmall { return bucket._offset < _count }
return bitmap.isOccupied(bucket)
}
}
extension _HTable {
@_transparent
@inlinable
package func idealBucket(forHashValue hashValue: Int) -> Bucket {
let hashValue = UInt(truncatingIfNeeded: hashValue)
return Bucket(offset: hashValue & (bucketCount &- 1))
}
@_transparent
@inlinable
package func probeLength(
from start: Bucket,
to end: Bucket
) -> Int {
if start.offset <= end.offset {
return Int(end._offset &- start._offset &+ 1)
}
return Int(bucketCount &- start._offset &+ end._offset)
}
@_transparent
@inlinable
package func probeLength(
forHashValue hashValue: Int,
in bucket: Bucket
) -> Int {
let ideal = idealBucket(forHashValue: hashValue)
return probeLength(from: ideal, to: bucket)
}
}
#endif
@@ -0,0 +1,49 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2026 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 compiler(>=6.2)
extension _HTable {
package var description: String {
let multiline = self.endBucket.offset > _Word.capacity
var buckets = ""
if !self.isSmall {
let lastWord = self.endBucket.bit > 0 ? self.endBucket.word : self.endBucket.word - 1
var it = self.makeBucketIterator()
while !it.isAtEnd {
if it.currentBucket.isOnWordBoundary {
if multiline {
buckets += "\n "
buckets += it.currentBucket.word == lastWord ? "└╴" : "├╴"
buckets += "[" + String(it.currentBucket.offset).lpad(8, with: "0") + "] "
} else {
buckets += " "
}
} else if it.currentBucket.bit % 8 == 0 {
buckets += "∙"
}
buckets.append(it.isOccupied ? "■" : "□")
it.advanceToNextBit()
}
}
var s = "⌗ \(scale == 0 ? "small" : "large@\(scale)")"
s += "\(multiline ? "" : buckets) "
s += "\(count)/\(capacity), "
s += "totalProbeLength: \(_totalProbeLength)"
if !self.isSmall, multiline {
s += buckets
}
return s
}
}
#endif