[BasicContainers] Add Index to hashed containers. Implement dictionary iteration using indices

This commit is contained in:
Karoy Lorentey committed 2026-02-27 12:19:54 -08:00
1 parent 087197dc1a
commit 318ac805ea
18 files changed
+747 -18

No files matched your search

+6
View File
@@ -68,6 +68,7 @@ target_sources(${module_name} PRIVATE
"RigidSet/RigidSet+Debugging.swift"
"RigidSet/RigidSet+Equatable.swift"
"RigidSet/RigidSet+Hashable.swift"
"RigidSet/RigidSet+Index.swift"
"RigidSet/RigidSet+Initializers.swift"
"RigidSet/RigidSet+Insertions.swift"
"RigidSet/RigidSet+Lookup.swift"
@@ -79,6 +80,7 @@ target_sources(${module_name} PRIVATE
"UniqueSet/UniqueSet+Debugging.swift"
"UniqueSet/UniqueSet+Equatable.swift"
"UniqueSet/UniqueSet+Hashable.swift"
"UniqueSet/UniqueSet+Index.swift"
"UniqueSet/UniqueSet+Initializers.swift"
"UniqueSet/UniqueSet+Insertions.swift"
"UniqueSet/UniqueSet+Lookup.swift"
@@ -88,6 +90,8 @@ target_sources(${module_name} PRIVATE
"RigidDictionary/RigidDictionary+Consumption.swift"
"RigidDictionary/RigidDictionary+Equatable.swift"
"RigidDictionary/RigidDictionary+Hashable.swift"
"RigidDictionary/RigidDictionary+Index.swift"
"RigidDictionary/RigidDictionary+Indices.swift"
"RigidDictionary/RigidDictionary+Initializers.swift"
"RigidDictionary/RigidDictionary+Insertions.swift"
"RigidDictionary/RigidDictionary+Keys.swift"
@@ -98,6 +102,8 @@ target_sources(${module_name} PRIVATE
"UniqueDictionary/UniqueDictionary+Consumption.swift"
"UniqueDictionary/UniqueDictionary+Equatable.swift"
"UniqueDictionary/UniqueDictionary+Hashable.swift"
"UniqueDictionary/UniqueDictionary+Index.swift"
"UniqueDictionary/UniqueDictionary+Indices.swift"
"UniqueDictionary/UniqueDictionary+Initializers.swift"
"UniqueDictionary/UniqueDictionary+Insertions.swift"
"UniqueDictionary/UniqueDictionary+Keys.swift"
@@ -67,7 +67,27 @@ extension _HTable.Bitmap {
}
@inlinable
package func firstUnoccupiedBucket(from start: Bucket) -> Bucket {
package func firstOccupiedBucket(from start: Bucket) -> Bucket? {
assert(isValid(start))
var word = start.word
var bits = _words[word]
bits.removeAll(upTo: start.bit)
while true {
if let bit = bits.firstMember {
return Bucket(word: word, bit: bit)
}
word &+= 1
if word >= _words.count {
return nil
}
bits = _words[word]
}
}
@inlinable
package func firstUnoccupiedBucket(wrappingFrom start: Bucket) -> Bucket {
assert(isValid(start))
var word = start.word
var bits = _words[word]
@@ -36,7 +36,7 @@ extension _HTable {
#if COLLECTIONS_NO_ROBIN_HOOD_HASHING
let ideal = idealBucket(forHashValue: hashValue)
let bitmap = self.bitmap
let actual = bitmap.firstUnoccupiedBucket(from: ideal)
let actual = bitmap.nextUnoccupiedBucket(wrappingFrom: ideal)
bitmap.setOccupied(actual)
let probeLength = self.probeLength(from: ideal, to: actual)
_maxProbeLength = Swift.max(_maxProbeLength, probeLength)
@@ -36,7 +36,7 @@ extension _HTable {
/// iterator values outside the closure call that produced the original
/// hash table.
@usableFromInline
package struct BucketIterator: ~Copyable, ~Escapable {
package struct BucketIterator: ~Escapable {
@usableFromInline
package typealias Bucket = _HTable.Bucket
@usableFromInline
@@ -210,14 +210,14 @@ extension _HTable.BucketIterator {
@_lifetime(self: copy self)
package mutating func advanceToOccupied() -> Bool {
if isAtEnd { return false }
guard _words != nil else {
if _words == nil {
return true
}
while true {
if let first = _nextBits.firstMember {
_nextBits = _nextBits.shiftedDown(by: first)
_bucket._offset &+= first
_nextBitCount &-= UInt8(first)
_bucket._offset &+= first
break
}
guard _advanceToNextWord() else { return false }
@@ -225,6 +225,42 @@ extension _HTable.BucketIterator {
return true
}
/// If the current bucket is already occupied, this does nothing.
@usableFromInline
@discardableResult
@_lifetime(self: copy self)
package mutating func advanceToOccupied(
maximumCount: Int
) -> Bool {
var remainder = UInt(bitPattern: maximumCount)
if isAtEnd { return false }
if _words == nil {
let delta = Swift.min(_endBucket._offset &- _bucket._offset, remainder)
_bucket._offset &+= delta
return true
}
while true {
if let first = _nextBits.firstMember {
let c = Swift.min(remainder, first)
_nextBits = _nextBits.shiftedDown(by: c)
_nextBitCount &-= UInt8(c)
_bucket._offset &+= c
remainder &-= c
break
}
if remainder < _nextBitCount {
_nextBits = _nextBits.shiftedDown(by: remainder)
_nextBitCount &-= UInt8(remainder)
_bucket._offset &+= remainder
remainder = 0
break
}
remainder &-= UInt(_nextBitCount)
guard _advanceToNextWord() else { return false }
}
return true
}
@usableFromInline
@_lifetime(self: copy self)
package mutating func wrapToOccupied() {
@@ -271,14 +307,14 @@ extension _HTable.BucketIterator {
@discardableResult
@_lifetime(self: copy self)
package mutating func advanceToUnoccupied(
maximumCount: Int = .max
maximumCount: Int
) -> 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
_bucket._offset &+= delta
return false
}
while remainder > 0 {
@@ -291,16 +327,15 @@ extension _HTable.BucketIterator {
remainder &-= c
break
}
if remainder >= _nextBitCount {
remainder &-= UInt(_nextBitCount)
guard _advanceToNextWord() else { return false }
} else {
if remainder < _nextBitCount {
_nextBits = _nextBits.shiftedDown(by: remainder)
_nextBitCount &-= UInt8(remainder)
_bucket._offset &+= remainder
remainder = 0
break
}
remainder &-= UInt(_nextBitCount)
guard _advanceToNextWord() else { return false }
}
return true
}
@@ -336,5 +371,19 @@ extension _HTable.BucketIterator {
let end = self.currentBucket
return Range(uncheckedBounds: (start, end))
}
@usableFromInline
@_lifetime(self: copy self)
package mutating func nextUnoccupiedRegion(
maximumCount: Int = .max
) -> Range<Bucket>? {
assert(maximumCount > 0)
guard self.advanceToUnoccupied() else { return nil }
assert(!self.isOccupied)
let start = self.currentBucket
self.advanceToOccupied(maximumCount: maximumCount)
let end = self.currentBucket
return Range(uncheckedBounds: (start, end))
}
}
#endif
@@ -0,0 +1,101 @@
//===----------------------------------------------------------------------===//
//
// 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 ContainersPreview
#endif
#if compiler(>=6.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS
@available(SwiftStdlib 5.0, *)
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
public typealias Index = RigidSet<Key>.Index
@inlinable
@inline(__always)
public var startIndex: Index {
_keys.startIndex
}
@inlinable
@inline(__always)
public var endIndex: Index {
_keys.endIndex
}
@inlinable
@inline(__always)
public func index(forKey key: borrowing Key) -> Index? {
_keys.index(of: key)
}
@inlinable
@inline(__always)
public func index(after index: Index) -> Index {
_keys.index(after: index)
}
@_alwaysEmitIntoClient
@_transparent
package func _isOccupied(_ bucket: _Bucket) -> Bool {
_keys._isOccupied(bucket)
}
@_alwaysEmitIntoClient
@_transparent
package func _checkItemIndex(_ index: Index) -> Void {
_keys._checkItemIndex(index)
}
}
@available(SwiftStdlib 5.0, *)
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
@frozen
public struct Element: ~Copyable, ~Escapable {
// FIXME: See if using (the real) `struct Borrow` would make sense here.
@_alwaysEmitIntoClient
package var _key: UnsafePointer<Key>
@_alwaysEmitIntoClient
package var _value: UnsafePointer<Value>
@_alwaysEmitIntoClient
@_lifetime(borrow _base)
package init(
_base: borrowing RigidDictionary<Key, Value>,
bucket: _Bucket
) {
assert(_base._isOccupied(bucket))
self._key = .init(_base._keyPtr(at: bucket))
self._value = .init(_base._valuePtr(at: bucket))
}
@_alwaysEmitIntoClient
public var key: Key {
// FIXME: This should be a borrow accessor
unsafeAddress { _key }
}
@_alwaysEmitIntoClient
public var value: Value {
// FIXME: This should be a borrow accessor
unsafeAddress { _value }
}
}
@_alwaysEmitIntoClient
public subscript(index: Index) -> Element {
_checkItemIndex(index)
return Element(_base: self, bucket: index._bucket)
}
}
#endif
@@ -0,0 +1,88 @@
//===----------------------------------------------------------------------===//
//
// 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
@available(SwiftStdlib 5.0, *)
extension RigidDictionary where Key: ~Copyable, Value: ~Copyable {
@frozen
public struct Indices: ~Escapable {
@_alwaysEmitIntoClient
package let _base: Borrow<_HTable>
@_alwaysEmitIntoClient
@_lifetime(borrow _base)
package init(_base: borrowing @_addressable _HTable) {
self._base = Borrow(_base)
}
}
@inlinable
public var indices: Indices {
@_lifetime(borrow self)
get {
Indices(_base: self._keys._table)
}
}
}
@available(SwiftStdlib 6.2, *)
extension RigidDictionary.Indices: BorrowingSequence
where Key: ~Copyable, Value: ~Copyable
{
public typealias Element = RigidDictionary.Index
@frozen
public struct BorrowingIterator: ~Escapable {
public typealias Element = RigidDictionary.Index
@usableFromInline
package var _it: _HTable.BucketIterator
@usableFromInline
package var _current: InlineArray<1, Element>
@inlinable
@_lifetime(copy _it)
package init(_it: consuming _HTable.BucketIterator) {
self._it = _it
self._current = InlineArray { target in
target.append(Element(_bucket: _HTable.Bucket(offset: 0)))
}
}
}
@inlinable
public var estimatedCount: EstimatedCount {
.exactly(self._base.value.count)
}
@_lifetime(copy self)
public func makeBorrowingIterator() -> BorrowingIterator {
let bit = self._base.value.makeBucketIterator()
// FIXME: This override really should not be necessary. Check if the real `struct Borrow` fixes it.
let override = _overrideLifetime(bit, copying: self)
return BorrowingIterator(_it: override)
}
}
@available(SwiftStdlib 6.2, *)
extension RigidDictionary.Indices.BorrowingIterator: BorrowingIteratorProtocol
where Key: ~Copyable, Value: ~Copyable {
@_lifetime(&self)
public mutating func nextSpan(maximumCount: Int) -> Span<Element> {
guard _it.advanceToOccupied() else { return .init() }
_current[0] = Element(_bucket: _it.currentBucket)
_it.advanceToNextBit()
return _current.span
}
}
#endif
@@ -17,6 +17,7 @@ import ContainersPreview
#if compiler(>=6.2) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS
@available(SwiftStdlib 5.0, *)
@frozen
@_addressableForDependencies
public struct RigidDictionary<
Key: GeneralizedHashable & ~Copyable,
Value: ~Copyable
@@ -0,0 +1,109 @@
//===----------------------------------------------------------------------===//
//
// 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 ContainersPreview
#endif
#if compiler(>=6.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS
@available(SwiftStdlib 5.0, *)
extension RigidSet where Element: ~Copyable {
@frozen
public struct Index: Equatable {
@_alwaysEmitIntoClient
package var _bucket: _HTable.Bucket
@_alwaysEmitIntoClient
@_transparent
package init(_bucket: _HTable.Bucket) {
self._bucket = _bucket
}
@_alwaysEmitIntoClient
@_transparent
package init(_offset: UInt) {
self._bucket = _HTable.Bucket(offset: _offset)
}
@_alwaysEmitIntoClient
@_transparent
package init(_offset: Int) {
self._bucket = _HTable.Bucket(offset: _offset)
}
@_alwaysEmitIntoClient
@_transparent
package var _offset: UInt { _bucket._offset }
@_alwaysEmitIntoClient
public static func ==(left: Self, right: Self) -> Bool {
left._bucket == right._bucket
}
}
@inlinable
public var startIndex: Index {
if _table.isSmall { return Index(_bucket: _Bucket(offset: 0)) }
guard let b = _table.bitmap.firstOccupiedBucket(from: _Bucket(offset: 0))
else { return endIndex }
return Index(_bucket: b)
}
@inlinable
public var endIndex: Index {
if _table.isSmall { return Index(_offset: count) }
return Index(_bucket: _table.endBucket)
}
@_alwaysEmitIntoClient
@_transparent
package func _isOccupied(_ bucket: _Bucket) -> Bool {
_table.isValid(bucket) && _table.isOccupied(bucket)
}
@_alwaysEmitIntoClient
@_transparent
package func _checkItemIndex(_ index: Index) -> Void {
precondition(_isOccupied(index._bucket), "Index out of bounds")
}
@inlinable
public func index(of member: borrowing Element) -> Index? {
guard let bucket = self._find(member).bucket else { return nil }
return Index(_bucket: bucket)
}
@inlinable
public func index(after index: Index) -> Index {
_checkItemIndex(index)
if _table.isSmall {
return Index(_bucket: _Bucket(offset: index._bucket._offset &+ 1))
}
var start = index._bucket
start._offset &+= 1
guard start < _table.endBucket else { return Index(_bucket: start) }
guard let b = _table.bitmap.firstOccupiedBucket(from: start)
else { return endIndex }
return Index(_bucket: b)
}
@inlinable
public subscript(index: Index) -> Element {
// FIXME: Use borrow accessor here
unsafeAddress {
_checkItemIndex(index)
return .init(_memberPtr(at: index._bucket))
}
}
}
#endif
@@ -0,0 +1,69 @@
//===----------------------------------------------------------------------===//
//
// 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 ContainersPreview
#endif
#if compiler(>=6.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS
@available(SwiftStdlib 5.0, *)
extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
public typealias Index = RigidSet<Key>.Index
@inlinable
@inline(__always)
public var startIndex: Index {
_storage._keys.startIndex
}
@inlinable
@inline(__always)
public var endIndex: Index {
_storage._keys.endIndex
}
@inlinable
@inline(__always)
public func index(forKey key: borrowing Key) -> Index? {
_storage._keys.index(of: key)
}
@inlinable
@inline(__always)
public func index(after index: Index) -> Index {
_storage._keys.index(after: index)
}
@_alwaysEmitIntoClient
@_transparent
package func _isOccupied(_ bucket: _Bucket) -> Bool {
_storage._keys._isOccupied(bucket)
}
@_alwaysEmitIntoClient
@_transparent
package func _checkItemIndex(_ index: Index) -> Void {
_storage._keys._checkItemIndex(index)
}
}
@available(SwiftStdlib 5.0, *)
extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
public typealias Element = RigidDictionary<Key, Value>.Element
@_alwaysEmitIntoClient
public subscript(index: Index) -> Element {
_storage[index]
}
}
#endif
@@ -0,0 +1,27 @@
//===----------------------------------------------------------------------===//
//
// 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
@available(SwiftStdlib 5.0, *)
extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
public typealias Indices = RigidDictionary<Key, Value>.Indices
@inlinable
public var indices: Indices {
@_lifetime(borrow self)
get {
_storage.indices
}
}
}
#endif
@@ -28,7 +28,8 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable {
public func value(
forKey key: borrowing Key
) -> Borrow<Value>? {
_storage.value(forKey: key)
// FIXME: Why is this override necessary? Is it sound? It was triggered by RigidDictionary becoming `@_addressableForDependencies`.
_overrideLifetime(_storage.value(forKey: key), borrowing: self)
}
#endif
@@ -13,6 +13,7 @@
@available(SwiftStdlib 5.0, *)
@frozen
@_addressableForDependencies
public struct UniqueDictionary<
Key: GeneralizedHashable & ~Copyable,
Value: ~Copyable
@@ -0,0 +1,68 @@
//===----------------------------------------------------------------------===//
//
// 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 ContainersPreview
#endif
#if compiler(>=6.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS
@available(SwiftStdlib 5.0, *)
extension UniqueSet where Element: ~Copyable {
public typealias Index = RigidSet<Element>.Index
@inlinable
@inline(__always)
public var startIndex: Index {
_storage.startIndex
}
@inlinable
@inline(__always)
public var endIndex: Index {
_storage.endIndex
}
@_alwaysEmitIntoClient
@_transparent
package func _isOccupied(_ bucket: _Bucket) -> Bool {
_storage._isOccupied(bucket)
}
@_alwaysEmitIntoClient
@_transparent
package func _checkItemIndex(_ index: Index) -> Void {
_storage._checkItemIndex(index)
}
@inlinable
@inline(__always)
public func index(of member: borrowing Element) -> Index? {
_storage.index(of: member)
}
@inlinable
@inline(__always)
public func index(after index: Index) -> Index {
_storage.index(after: index)
}
@inlinable
public subscript(index: Index) -> Element {
// FIXME: Use borrow accessor here
unsafeAddress {
_checkItemIndex(index)
return .init(_storage._memberPtr(at: index._bucket))
}
}
}
#endif