[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

+12
View File
@@ -49,4 +49,16 @@ target_sources(${module_name} PRIVATE
"UniqueArray/UniqueArray+Insertions.swift"
"UniqueArray/UniqueArray+Removals.swift"
"UniqueArray/UniqueArray+Replacements.swift"
"HashTable/ProtocolGeneralizations.swift"
"HashTable/_HTable.swift"
"HashTable/_HTable+Bitmap.swift"
"HashTable/_HTable+Bucket.swift"
"HashTable/_HTable+Constants.swift"
"HashTable/_HTable+Find.swift"
"HashTable/_HTable+Insert.swift"
"HashTable/_HTable+Iteration.swift"
"HashTable/_HTable+Small.swift"
"HashTable/_HTable+Debugging.swift"
"RigidSet/RigidSet.swift"
"RigidDictionary/RigidDictionary.swift"
)
@@ -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
@@ -0,0 +1,192 @@
//===----------------------------------------------------------------------===//
//
// 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
import ContainersPreview
#endif
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS
public struct RigidDictionary<
Key: GeneralizedHashable & ~Copyable,
Value: ~Copyable
>: ~Copyable {
@_alwaysEmitIntoClient
package var _keys: RigidSet<Key>
@_alwaysEmitIntoClient
package var _values: UnsafeMutablePointer<Value>?
@inlinable
public init() {
self.init(capacity: 0)
}
@inlinable
public init(capacity: Int) {
precondition(capacity >= 0, "Capacity must be nonnegative")
self._keys = RigidSet(capacity: capacity)
if capacity > 0 {
self._values = .allocate(capacity: Int(bitPattern: _keys._table.bucketCount))
} else {
self._values = nil
}
}
@_alwaysEmitIntoClient
deinit {
// FIXME: This iterates over the bitmap twice: once in `self._dispose()`,
// and once in `_keys.deinit`. `self` not being mutable really hurts us
// here.
_dispose()
}
@_alwaysEmitIntoClient
internal func _dispose() {
if !isEmpty {
let values = _valueBuf
var it = _keys._table.makeBucketIterator()
while let range = it.nextOccupiedRegion() {
values.extracting(range._offsets).deinitialize()
}
}
_values?.deallocate()
}
}
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
@inlinable
@inline(__always)
public var count: Int {
_assumeNonNegative(_keys._table.count)
}
@inlinable
@inline(__always)
public var capacity: Int {
_assumeNonNegative(_keys._table.capacity)
}
@inlinable
@inline(__always)
public var isEmpty: Bool {
count == 0
}
@inlinable
@inline(__always)
public var isFull: Bool {
count == capacity
}
@inlinable
@inline(__always)
public var freeCapacity: Int {
_assumeNonNegative(capacity &- count)
}
}
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
@_alwaysEmitIntoClient
@_transparent
internal var _keyBuf: UnsafeMutableBufferPointer<Key> {
_keys._memberBuf
}
@_alwaysEmitIntoClient
@_transparent
internal var _valueBuf: UnsafeMutableBufferPointer<Value> {
.init(start: _values, count: Int(bitPattern: _keys._table.bucketCount))
}
@_alwaysEmitIntoClient
@_transparent
internal func _valuePtr(
at bucket: _HTable.Bucket
) -> UnsafeMutablePointer<Value> {
assert(_keys._table.isValid(bucket))
return _values.unsafelyUnwrapped.advanced(by: bucket.offset)
}
@_alwaysEmitIntoClient
@_transparent
internal func _keyPtr(
at bucket: _HTable.Bucket
) -> UnsafeMutablePointer<Key> {
_keys._memberPtr(at: bucket)
}
}
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
@inlinable
@_lifetime(borrow self)
public func value(
forKey key: borrowing Key
) -> Borrow<Value>? {
guard let bucket = _keys._find(key) else { return nil }
return Borrow(unsafeAddress: _valuePtr(at: bucket), borrowing: self)
}
@inlinable
public mutating func insertValue(
_ value: consuming Value,
forKey key: consuming Key
) -> Value? {
let valueBuf = _valueBuf
let r = _keys._insert(key) { key, bucket in
swap(&value, &valueBuf[bucket])
}
if r.found {
return value
}
valueBuf.initializeElement(at: r.bucket, to: value)
return nil
}
@inlinable
public mutating func updateValue(
_ value: consuming Value,
forKey key: consuming Key
) -> Value? {
let valueBuf = _valueBuf
let r = _keys._insert(key) { key, bucket in
swap(&value, &valueBuf[bucket])
}
if r.found {
return exchange(&valueBuf[r.bucket], with: value)
}
valueBuf.initializeElement(at: r.bucket, to: value)
return nil
}
@inlinable
@_lifetime(&self)
public mutating func memoizedValue(
forKey key: consuming Key,
_ body: (borrowing Key) -> Value
) -> Borrow<Value> {
let values = _valueBuf
var value: Value? = nil
let r = _keys._insert(key) { key, bucket in
var v = value.take() ?? body(key)
swap(&values[bucket.offset], &v)
value = consume v
}
let p = values._ptr(at: r.bucket)
if !r.found {
p.initialize(to: value.take() ?? body(_keys._memberBuf[r.bucket]))
}
return Borrow(unsafeAddress: p, borrowing: self)
}
}
#endif
@@ -0,0 +1,317 @@
//===----------------------------------------------------------------------===//
//
// 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.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS
@frozen
public struct RigidSet<Element: GeneralizedHashable & ~Copyable>: ~Copyable {
@_alwaysEmitIntoClient
package var _members: UnsafeMutablePointer<Element>?
@_alwaysEmitIntoClient
package var _table: _HTable
@inlinable
public init() {
self.init(capacity: 0)
}
@inlinable
public init(capacity: Int) {
precondition(capacity >= 0, "Capacity must be nonnegative")
self._table = _HTable(capacity: capacity)
if capacity > 0 {
self._members = .allocate(capacity: Int(bitPattern: _table.bucketCount))
} else {
self._members = nil
}
}
@_alwaysEmitIntoClient
deinit {
_dispose()
}
@_alwaysEmitIntoClient
internal func _dispose() {
if !isEmpty {
let storage = _memberBuf
var it = _table.makeBucketIterator()
while let range = it.nextOccupiedRegion() {
storage.extracting(range._offsets).deinitialize()
}
}
_members?.deallocate()
}
}
extension RigidSet where Element: ~Copyable {
@inlinable
@inline(__always)
public var count: Int {
_assumeNonNegative(_table.count)
}
@inlinable
@inline(__always)
public var capacity: Int {
_assumeNonNegative(_table.capacity)
}
@inlinable
@inline(__always)
public var isEmpty: Bool {
count == 0
}
@inlinable
@inline(__always)
public var isFull: Bool {
count == capacity
}
@inlinable
@inline(__always)
public var freeCapacity: Int {
_assumeNonNegative(capacity &- count)
}
}
extension RigidSet where Element: ~Copyable {
@_alwaysEmitIntoClient
@_transparent
internal var _memberBuf: UnsafeMutableBufferPointer<Element> {
.init(start: _members, count: Int(bitPattern: _table.bucketCount))
}
@_alwaysEmitIntoClient
@_transparent
internal func _memberPtr(
at bucket: _HTable.Bucket
) -> UnsafeMutablePointer<Element> {
assert(_table.isValid(bucket))
return _members.unsafelyUnwrapped.advanced(by: bucket.offset)
}
@_alwaysEmitIntoClient
internal var _seed: Int {
#if COLLECTIONS_DETERMINISTIC_HASHING
Int(_table.scale)
#else
Int(bitPattern: _baseAddress)
#endif
}
@_alwaysEmitIntoClient
@_transparent
internal borrowing func _hashValue(
at bucket: _HTable.Bucket
) -> Int {
assert(bucket.offset >= 0 && bucket.offset < capacity)
return _hashValue(for: _members.unsafelyUnwrapped[bucket.offset])
}
@_alwaysEmitIntoClient
@_transparent
internal borrowing func _hashValue(
for item: borrowing Element
) -> Int {
item._rawHashValue(seed: _seed)
}
}
extension RigidSet where Element: ~Copyable {
@inlinable
package borrowing func _find(_ item: borrowing Element) -> _HTable.Bucket? {
func tester(_ bucket: _HTable.Bucket) -> Bool {
_memberBuf[bucket.offset] == item
}
if _table.isSmall {
return _table.find_Small(tester: tester)
}
return _table.find_Large(
hashValue: _hashValue(for: item),
tester: tester)
}
@inlinable
public borrowing func contains(_ item: borrowing Element) -> Bool {
_find(item) != nil
}
@usableFromInline
@frozen
internal struct _InsertResult: ~Copyable {
// FIXME: This struct really just wants to be a tuple.
@_alwaysEmitIntoClient
internal var bucket: _HTable.Bucket
@_alwaysEmitIntoClient
internal var remnant: Element?
@_alwaysEmitIntoClient
internal init(
bucket: _HTable.Bucket, remnant: consuming Element?
) {
self.bucket = bucket
self.remnant = remnant
}
@_alwaysEmitIntoClient
internal var found: Bool { remnant != nil }
}
@inlinable
@discardableResult
internal mutating func _insert(
_ item: consuming Element,
swapper: (borrowing Element, _HTable.Bucket) -> Void = { _, _ in }
) -> _InsertResult {
let storage = _memberBuf
if _table.isSmall {
if let bucket = _table.find_Small(
tester: { storage[$0.offset] == item }
) {
return .init(bucket: bucket, remnant: item)
}
precondition(!isFull, "RigidSet capacity overflow")
let bucket = _table.insertNew_Small(
swapper: {
swapper(item, $0)
swap(&item, &storage[$0.offset])
})
storage.initializeElement(at: bucket.offset, to: item)
return .init(bucket: bucket, remnant: nil)
}
let hashValue = _hashValue(for: item)
if let bucket = _table.find_Large(
hashValue: hashValue,
tester: { storage[$0.offset] == item }
) {
return .init(bucket: bucket, remnant: item)
}
precondition(!isFull, "RigidSet capacity overflow")
let seed = self._seed
let bucket = _table.insertNew_Large(
hashValue: hashValue,
hashGenerator: {
storage[$0.offset]._rawHashValue(seed: seed)
},
swapper: {
swapper(item, $0)
swap(&item, &storage[$0.offset])
})
storage.initializeElement(at: bucket.offset, to: item)
return .init(bucket: bucket, remnant: nil)
}
/// Inserts the given element into the set unconditionally. If the set already
/// contained a member equal to `item`, then the new item replaces it.
///
/// - Parameter item: An element to insert into the set.
/// - Returns: An element equal to `item` if the set already contained such
/// a member, otherwise `nil`.
@inlinable
@discardableResult
public mutating func update(
with item: consuming Element
) -> Element? {
var r = self._insert(item)
if let remnant = r.remnant.take() {
return exchange(&_memberBuf[r.bucket.offset], with: remnant)
}
return nil
}
/// Inserts the given element in the set if it is not already present.
///
/// - Parameter item: An element to insert into the set.
/// - Returns:
@inlinable
@discardableResult
public mutating func insert(
_ item: consuming Element
) -> Element? {
var r = self._insert(item)
return r.remnant.take()
}
}
extension RigidSet where Element: ~Copyable {
@inlinable
public var estimatedCount: EstimatedCount {
.exactly(count)
}
@inlinable
public func _customContainsEquatableElement(
_ element: borrowing Element
) -> Bool? {
contains(element)
}
@_lifetime(borrow self)
public borrowing func makeBorrowingIterator() -> BorrowingIterator {
BorrowingIterator(_table: _table, baseAddress: _members)
}
@frozen
public struct BorrowingIterator:
BorrowingIteratorProtocol,
~Copyable,
~Escapable
{
@_alwaysEmitIntoClient
internal var _baseAddress: UnsafePointer<Element>?
@_alwaysEmitIntoClient
internal var _bucketIterator: _HTable.BucketIterator
@_alwaysEmitIntoClient
@_lifetime(borrow _table)
internal init(
_table: borrowing _HTable,
baseAddress: UnsafePointer<Element>?
) {
self._baseAddress = baseAddress
self._bucketIterator = _table.makeBucketIterator()
}
@_alwaysEmitIntoClient
@_lifetime(copy self)
internal func _span(over buckets: Range<_HTable.Bucket>) -> Span<Element> {
let items = UnsafeBufferPointer(
start: _baseAddress.unsafelyUnwrapped + buckets.lowerBound.offset,
count: buckets.upperBound.offset - buckets.lowerBound.offset)
return _overrideLifetime(Span(_unsafeElements: items), copying: self)
}
@_alwaysEmitIntoClient
@_lifetime(copy self)
public mutating func nextSpan(maximumCount: Int) -> Span<Element> {
precondition(maximumCount > 0, "maximumCount must be positive")
guard
let next = _bucketIterator.nextOccupiedRegion(maximumCount: maximumCount)
else {
return .init()
}
return _span(over: next)
}
}
}
#endif