diff --git a/CMakeLists.txt b/CMakeLists.txt index ddd1bebb..b878c7c8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -51,6 +51,9 @@ set(collections_swift_flags "-enable-experimental-feature BuiltinModule" "-enable-experimental-feature Lifetimes" "-enable-experimental-feature InoutLifetimeDependence" + "-enable-experimental-feature SuppressedAssociatedTypes" + "-enable-experimental-feature AddressableParameters" + "-enable-experimental-feature AddressableTypes" ) foreach(flag ${collections_swift_flags}) add_compile_options("$<$:SHELL:${flag}>") @@ -62,6 +65,7 @@ set(availability_defs "SwiftStdlib 5.0: macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2" "SwiftStdlib 5.1: macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0" "SwiftStdlib 5.6: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4" + "SwiftStdlib 5.7: macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0" "SwiftStdlib 5.8: macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4" "SwiftStdlib 5.9: macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0" "SwiftStdlib 5.10: macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.1" diff --git a/Package.swift b/Package.swift index 3c7c5a57..84ad9a49 100644 --- a/Package.swift +++ b/Package.swift @@ -34,6 +34,14 @@ let _traits: Set = [ production. We will make significant, source breaking API changes to these types before they ship. """), + .trait( + name: "UnstableNoncopyableKeys", + description: """ + Enables support for noncopyable set members and dictionary keys in + `BasicContainers`. This requires a Standard Library with generalized + `Equatable` and `Hashable` protocols that allow noncopyable conformers; + this feature has not shipped in a stable compiler version yet. + """), ] // This package recognizes the conditional compilation flags listed below. @@ -48,6 +56,9 @@ var defines: [SwiftSetting] = [ .define( "COLLECTIONS_UNSTABLE_SORTED_COLLECTIONS", .when(traits: ["UnstableSortedCollections"])), + .define( + "COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS", + .when(traits: ["UnstableNoncopyableKeys"])), // Enables internal consistency checks at the end of initializers and // mutating operations. This can have very significant overhead, so enabling @@ -89,6 +100,7 @@ let availabilityMacros: KeyValuePairs = [ "SwiftStdlib 5.0": "macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2", "SwiftStdlib 5.1": "macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0", "SwiftStdlib 5.6": "macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4", + "SwiftStdlib 5.7": "macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0", "SwiftStdlib 5.8": "macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4", "SwiftStdlib 5.9": "macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0", "SwiftStdlib 5.10": "macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.1", diff --git a/Sources/BasicContainers/CMakeLists.txt b/Sources/BasicContainers/CMakeLists.txt index d0c1af97..f095e5ea 100644 --- a/Sources/BasicContainers/CMakeLists.txt +++ b/Sources/BasicContainers/CMakeLists.txt @@ -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" ) diff --git a/Sources/BasicContainers/HashTable/ProtocolGeneralizations.swift b/Sources/BasicContainers/HashTable/ProtocolGeneralizations.swift new file mode 100644 index 00000000..856f36cc --- /dev/null +++ b/Sources/BasicContainers/HashTable/ProtocolGeneralizations.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 diff --git a/Sources/BasicContainers/HashTable/_HTable+Bitmap.swift b/Sources/BasicContainers/HashTable/_HTable+Bitmap.swift new file mode 100644 index 00000000..7a7e9219 --- /dev/null +++ b/Sources/BasicContainers/HashTable/_HTable+Bitmap.swift @@ -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 + + @_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 diff --git a/Sources/BasicContainers/HashTable/_HTable+Bucket.swift b/Sources/BasicContainers/HashTable/_HTable+Bucket.swift new file mode 100644 index 00000000..59ac919a --- /dev/null +++ b/Sources/BasicContainers/HashTable/_HTable+Bucket.swift @@ -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 { + _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 { + @_transparent + get { + .init(uncheckedBounds: (lowerBound.offset, upperBound.offset)) + } + } +} + +#endif diff --git a/Sources/BasicContainers/HashTable/_HTable+Constants.swift b/Sources/BasicContainers/HashTable/_HTable+Constants.swift new file mode 100644 index 00000000..abf1d916 --- /dev/null +++ b/Sources/BasicContainers/HashTable/_HTable+Constants.swift @@ -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 diff --git a/Sources/BasicContainers/HashTable/_HTable+Find.swift b/Sources/BasicContainers/HashTable/_HTable+Find.swift new file mode 100644 index 00000000..a8662343 --- /dev/null +++ b/Sources/BasicContainers/HashTable/_HTable+Find.swift @@ -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 diff --git a/Sources/BasicContainers/HashTable/_HTable+Insert.swift b/Sources/BasicContainers/HashTable/_HTable+Insert.swift new file mode 100644 index 00000000..d89d4f70 --- /dev/null +++ b/Sources/BasicContainers/HashTable/_HTable+Insert.swift @@ -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 diff --git a/Sources/BasicContainers/HashTable/_HTable+Iteration.swift b/Sources/BasicContainers/HashTable/_HTable+Iteration.swift new file mode 100644 index 00000000..35474d57 --- /dev/null +++ b/Sources/BasicContainers/HashTable/_HTable+Iteration.swift @@ -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? + + @_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? { + 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 diff --git a/Sources/BasicContainers/HashTable/_HTable+Small.swift b/Sources/BasicContainers/HashTable/_HTable+Small.swift new file mode 100644 index 00000000..7f834a65 --- /dev/null +++ b/Sources/BasicContainers/HashTable/_HTable+Small.swift @@ -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 diff --git a/Sources/BasicContainers/HashTable/_HTable.swift b/Sources/BasicContainers/HashTable/_HTable.swift new file mode 100644 index 00000000..9baa1bfb --- /dev/null +++ b/Sources/BasicContainers/HashTable/_HTable.swift @@ -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? + + @_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.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 diff --git a/Sources/BasicContainers/HashTable/_Htable+Debugging.swift b/Sources/BasicContainers/HashTable/_Htable+Debugging.swift new file mode 100644 index 00000000..6cb0ba76 --- /dev/null +++ b/Sources/BasicContainers/HashTable/_Htable+Debugging.swift @@ -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 diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary.swift new file mode 100644 index 00000000..c50f93e3 --- /dev/null +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary.swift @@ -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 + + @_alwaysEmitIntoClient + package var _values: UnsafeMutablePointer? + + @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 { + _keys._memberBuf + } + + @_alwaysEmitIntoClient + @_transparent + internal var _valueBuf: UnsafeMutableBufferPointer { + .init(start: _values, count: Int(bitPattern: _keys._table.bucketCount)) + } + + @_alwaysEmitIntoClient + @_transparent + internal func _valuePtr( + at bucket: _HTable.Bucket + ) -> UnsafeMutablePointer { + assert(_keys._table.isValid(bucket)) + return _values.unsafelyUnwrapped.advanced(by: bucket.offset) + } + + @_alwaysEmitIntoClient + @_transparent + internal func _keyPtr( + at bucket: _HTable.Bucket + ) -> UnsafeMutablePointer { + _keys._memberPtr(at: bucket) + } +} + +extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { + @inlinable + @_lifetime(borrow self) + public func value( + forKey key: borrowing Key + ) -> Borrow? { + 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 { + 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 diff --git a/Sources/BasicContainers/RigidSet/RigidSet.swift b/Sources/BasicContainers/RigidSet/RigidSet.swift new file mode 100644 index 00000000..32e6a74e --- /dev/null +++ b/Sources/BasicContainers/RigidSet/RigidSet.swift @@ -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: ~Copyable { + @_alwaysEmitIntoClient + package var _members: UnsafeMutablePointer? + + @_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 { + .init(start: _members, count: Int(bitPattern: _table.bucketCount)) + } + + @_alwaysEmitIntoClient + @_transparent + internal func _memberPtr( + at bucket: _HTable.Bucket + ) -> UnsafeMutablePointer { + 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? + + @_alwaysEmitIntoClient + internal var _bucketIterator: _HTable.BucketIterator + + @_alwaysEmitIntoClient + @_lifetime(borrow _table) + internal init( + _table: borrowing _HTable, + baseAddress: UnsafePointer? + ) { + self._baseAddress = baseAddress + self._bucketIterator = _table.makeBucketIterator() + } + + @_alwaysEmitIntoClient + @_lifetime(copy self) + internal func _span(over buckets: Range<_HTable.Bucket>) -> Span { + 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 { + precondition(maximumCount > 0, "maximumCount must be positive") + guard + let next = _bucketIterator.nextOccupiedRegion(maximumCount: maximumCount) + else { + return .init() + } + return _span(over: next) + } + } +} +#endif diff --git a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift index 2567e2fe..e0ca75f8 100644 --- a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift +++ b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift @@ -42,7 +42,7 @@ internal struct _ChunkedBitsForwardIterator { .shiftedDown(by: b), count: end.bit - b) } - let c = UInt(_Word.capacity) - b + let c = _Word._capacity - b position.value += c return (bits: words[w].shiftedDown(by: b), count: c) } @@ -85,7 +85,7 @@ internal struct _ChunkedBitsBackwardIterator { extension IteratorProtocol where Element == Bool { mutating func _nextChunk( - maximumCount: UInt = UInt(_Word.capacity) + maximumCount: UInt = _Word._capacity ) -> (bits: _Word, count: UInt) { assert(maximumCount <= _Word.capacity) var bits = _Word.empty diff --git a/Sources/BitCollections/BitArray/BitArray+Copy.swift b/Sources/BitCollections/BitArray/BitArray+Copy.swift index 9507204c..3998eba1 100644 --- a/Sources/BitCollections/BitArray/BitArray+Copy.swift +++ b/Sources/BitCollections/BitArray/BitArray+Copy.swift @@ -79,7 +79,7 @@ extension BitArray._UnsafeHandle { words[start.word].formUnion(bits.shiftedUp(by: start.bit)) words[end.word].formIntersection(_Word(upTo: end.bit).complement()) words[end.word].formUnion( - bits.shiftedDown(by: UInt(_Word.capacity) &- start.bit)) + bits.shiftedDown(by: _Word._capacity &- start.bit)) } internal mutating func copy( @@ -160,7 +160,7 @@ extension BitArray._UnsafeHandle { var it = source.makeIterator() if pos.bit > 0 { let (bits, count) = it._nextChunk( - maximumCount: UInt(_Word.capacity) - pos.bit) + maximumCount: _Word._capacity - pos.bit) _copy(bits: bits, count: count, to: pos) pos.value += count } diff --git a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift index 93c8ffef..2b2d385e 100644 --- a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift +++ b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift @@ -283,7 +283,7 @@ extension BitArray { var pos = _BitPosition(_count) if pos.bit > 0 { let (bits, count) = it._nextChunk( - maximumCount: UInt(_Word.capacity) - pos.bit) + maximumCount: _Word._capacity - pos.bit) guard count > 0 else { return } _count += count _update { $0._copy(bits: bits, count: count, to: pos) } diff --git a/Sources/BitCollections/BitSet/BitSet.swift b/Sources/BitCollections/BitSet/BitSet.swift index 82cc66cd..f27d7935 100644 --- a/Sources/BitCollections/BitSet/BitSet.swift +++ b/Sources/BitCollections/BitSet/BitSet.swift @@ -48,7 +48,7 @@ extension BitSet { @usableFromInline internal var _capacity: UInt { - UInt(_storage.count) &* UInt(_Word.capacity) + UInt(_storage.count) &* _Word._capacity } internal mutating func _ensureCapacity(limit capacity: UInt) { diff --git a/Sources/ContainersPreview/Protocols/Container.swift b/Sources/ContainersPreview/Protocols/Container.swift index 6a380909..a413dbcf 100644 --- a/Sources/ContainersPreview/Protocols/Container.swift +++ b/Sources/ContainersPreview/Protocols/Container.swift @@ -405,7 +405,7 @@ where Base: ~Copyable /*FIXME: & ~Escapable*/ @_unsafeNonescapableResult // FIXME: we cannot convert from a borrow to an inout dependence! @_lifetime(&self) public mutating func nextSpan(maximumCount: Int) -> Span { - _base[].nextSpan(after: &self._position, maximumCount: maximumCount) + _base.value.nextSpan(after: &self._position, maximumCount: maximumCount) } } diff --git a/Sources/ContainersPreview/Types/Borrow.swift b/Sources/ContainersPreview/Types/Borrow.swift index f909262b..4c38ad23 100644 --- a/Sources/ContainersPreview/Types/Borrow.swift +++ b/Sources/ContainersPreview/Types/Borrow.swift @@ -18,14 +18,14 @@ import Builtin public struct Borrow: Copyable, ~Escapable { @usableFromInline package let _pointer: UnsafePointer - + @_lifetime(borrow value) @_alwaysEmitIntoClient @_transparent internal init(_borrowing value: borrowing @_addressable Target) { unsafe _pointer = UnsafePointer(Builtin.unprotectedAddressOfBorrow(value)) } - + #if compiler(>=6.3) // rdar://161844406 (https://github.com/swiftlang/swift/pull/84748) @_lifetime(borrow value) @_alwaysEmitIntoClient @@ -34,7 +34,7 @@ public struct Borrow: Copyable, ~Esca unsafe _pointer = UnsafePointer(Builtin.unprotectedAddressOfBorrow(value)) } #endif - + @_lifetime(borrow owner) @_alwaysEmitIntoClient @_transparent @@ -44,7 +44,7 @@ public struct Borrow: Copyable, ~Esca ) { unsafe _pointer = unsafeAddress } - + @_lifetime(copy owner) @_alwaysEmitIntoClient @_transparent @@ -54,14 +54,23 @@ public struct Borrow: Copyable, ~Esca ) { unsafe _pointer = unsafeAddress } - + @_alwaysEmitIntoClient + @available(*, deprecated, renamed: "value") public subscript() -> Target { @_transparent unsafeAddress { unsafe _pointer } } + + @_alwaysEmitIntoClient + public var value: Target { + @_transparent + unsafeAddress { + unsafe _pointer + } + } } extension Optional where Wrapped: ~Copyable /* FIXME: ~Escapable */ { diff --git a/Sources/ContainersPreview/Types/Inout.swift b/Sources/ContainersPreview/Types/Inout.swift index a7526630..b2712279 100644 --- a/Sources/ContainersPreview/Types/Inout.swift +++ b/Sources/ContainersPreview/Types/Inout.swift @@ -69,9 +69,8 @@ public struct Inout: ~Copyable, ~Esca } extension Inout where Target: ~Copyable { - /// Dereferences the mutable reference allowing for in-place reads and writes - /// to the underlying instance. @_alwaysEmitIntoClient + @available(*, deprecated, renamed: "value") public subscript() -> Target { @_transparent unsafeAddress { @@ -83,6 +82,21 @@ extension Inout where Target: ~Copyable { unsafe _pointer } } + + /// Dereferences the mutable reference allowing for in-place reads and writes + /// to the underlying instance. + @_alwaysEmitIntoClient + public var value: Target { + @_transparent + unsafeAddress { + unsafe .init(_pointer) + } + @_transparent + unsafeMutableAddress { + unsafe _pointer + } + } + } diff --git a/Sources/InternalCollectionsUtilities/CMakeLists.txt b/Sources/InternalCollectionsUtilities/CMakeLists.txt index c1154d81..36e3b8ba 100644 --- a/Sources/InternalCollectionsUtilities/CMakeLists.txt +++ b/Sources/InternalCollectionsUtilities/CMakeLists.txt @@ -1,7 +1,7 @@ #[[ This source file is part of the Swift Collections Open Source Project -Copyright (c) 2022 - 2024 Apple Inc. and the Swift project authors +Copyright (c) 2022 - 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 @@ -21,15 +21,6 @@ else() endif() target_sources(${module_name} PRIVATE - "Debugging.swift" - "Descriptions.swift" - "LifetimeOverride.swift" - "RandomAccessCollection+Offsets.swift" - "Span+Extras.swift" - "UnsafeBufferPointer+Extras.swift" - "UnsafeMutableBufferPointer+Extras.swift" - "UnsafeMutableRawBufferPointer+Extras.swift" - "UnsafeRawBufferPointer+Extras.swift" "IntegerTricks/FixedWidthInteger+roundUpToPowerOfTwo.swift" "IntegerTricks/Integer rank.swift" "IntegerTricks/UInt+first and last set bit.swift" @@ -39,4 +30,14 @@ target_sources(${module_name} PRIVATE "UnsafeBitSet/_UnsafeBitSet.swift" "_SortedCollection.swift" "_UniqueCollection.swift" + "Debugging.swift" + "Descriptions.swift" + "LifetimeOverride.swift" + "RandomAccessCollection+Offsets.swift" + "Span+Extras.swift" + "String+Padding.swift" + "UnsafeBufferPointer+Extras.swift" + "UnsafeMutableBufferPointer+Extras.swift" + "UnsafeMutableRawBufferPointer+Extras.swift" + "UnsafeRawBufferPointer+Extras.swift" ) diff --git a/Sources/InternalCollectionsUtilities/String+Padding.swift b/Sources/InternalCollectionsUtilities/String+Padding.swift new file mode 100644 index 00000000..b762f552 --- /dev/null +++ b/Sources/InternalCollectionsUtilities/String+Padding.swift @@ -0,0 +1,35 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +extension String { + @_alwaysEmitIntoClient + package func lpad(_ width: Int, with character: Character = " ") -> Self { + let c = count + guard c < width else { return self } + return String(repeating: character, count: width - c) + self + } + + @_alwaysEmitIntoClient + package func rpad(_ width: Int, with character: Character = " ") -> Self { + let c = count + guard c < width else { return self } + return self + String(repeating: character, count: width - c) + } + + @_alwaysEmitIntoClient + package func cpad(_ width: Int, with character: Character = " ") -> Self { + let c = count + guard c < width else { return self } + let l = String(repeating: character, count: (width - c + 1) / 2) + let r = String(repeating: character, count: (width - c) / 2) + return l + self + r + } +} diff --git a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift index d0f1890f..6edd4431 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift @@ -42,13 +42,13 @@ extension _UnsafeBitSet.Index { @inlinable package var word: Int { // Note: We perform on UInts to get faster unsigned math (shifts). - Int(truncatingIfNeeded: value / UInt(bitPattern: _Word.capacity)) + Int(truncatingIfNeeded: value / _Word._capacity) } @inlinable package var bit: UInt { // Note: We perform on UInts to get faster unsigned math (masking). - value % UInt(bitPattern: _Word.capacity) + value % _Word._capacity } @inlinable @@ -60,7 +60,7 @@ extension _UnsafeBitSet.Index { package var endSplit: (word: Int, bit: UInt) { let w = word let b = bit - if w > 0, b == 0 { return (w &- 1, UInt(_Word.capacity)) } + if w > 0, b == 0 { return (w &- 1, _Word._capacity) } return (w, b) } diff --git a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift index f7bdfbe3..0591f687 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+_Word.swift @@ -80,11 +80,29 @@ extension _UnsafeBitSet._Word { } extension _UnsafeBitSet._Word { + @_transparent + @inlinable + package static var wordShift: UInt { + #if _pointerBitWidth(_32) + return 5 + #elseif _pointerBitWidth(_64) + return 6 + #else + #error("Unsupported architecture") + #endif + } + + @_transparent + @inlinable + package static var wordMask: UInt { + (1 &<< wordShift) &- 1 + } + @inlinable @inline(__always) package static func wordCount(forBitCount count: UInt) -> Int { // Note: We perform on UInts to get faster unsigned math (shifts). - let width = UInt(bitPattern: Self.capacity) + let width = Self._capacity return Int(bitPattern: (count + width - 1) / width) } } @@ -96,6 +114,12 @@ extension _UnsafeBitSet._Word { return UInt.bitWidth } + @inlinable + @inline(__always) + package static var _capacity: UInt { + UInt(bitPattern: UInt.bitWidth) + } + @inlinable @inline(__always) package var count: Int { @@ -133,6 +157,13 @@ extension _UnsafeBitSet._Word { value._firstSetBit } + @inlinable + @inline(__always) + package mutating func set(_ bit: UInt) { + assert(bit < UInt.bitWidth) + value |= 1 &<< bit + } + @inlinable @inline(__always) @discardableResult @@ -144,6 +175,13 @@ extension _UnsafeBitSet._Word { return inserted } + @inlinable + @inline(__always) + package mutating func clear(_ bit: UInt) { + assert(bit < UInt.bitWidth) + value &= ~(1 &<< bit) + } + @inlinable @inline(__always) @discardableResult @@ -171,7 +209,7 @@ extension _UnsafeBitSet._Word { extension _UnsafeBitSet._Word { @inlinable @inline(__always) - internal mutating func insertAll(upTo bit: UInt) { + package mutating func insertAll(upTo bit: UInt) { assert(bit >= 0 && bit < Self.capacity) let mask: UInt = (1 as UInt &<< bit) &- 1 value |= mask @@ -179,7 +217,7 @@ extension _UnsafeBitSet._Word { @inlinable @inline(__always) - internal mutating func removeAll(upTo bit: UInt) { + package mutating func removeAll(upTo bit: UInt) { assert(bit >= 0 && bit < Self.capacity) let mask = UInt.max &<< bit value &= mask @@ -187,7 +225,7 @@ extension _UnsafeBitSet._Word { @inlinable @inline(__always) - internal mutating func removeAll(through bit: UInt) { + package mutating func removeAll(through bit: UInt) { assert(bit >= 0 && bit < Self.capacity) var mask = UInt.max &<< bit mask &= mask &- 1 // Clear lowest nonzero bit. @@ -196,7 +234,7 @@ extension _UnsafeBitSet._Word { @inlinable @inline(__always) - internal mutating func removeAll(from bit: UInt) { + package mutating func removeAll(from bit: UInt) { assert(bit >= 0 && bit < Self.capacity) let mask: UInt = (1 as UInt &<< bit) &- 1 value &= mask diff --git a/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift index ce2e1895..8c7cde3c 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift @@ -9,7 +9,7 @@ // //===----------------------------------------------------------------------===// -extension UnsafeBufferPointer { +extension UnsafeBufferPointer where Element: ~Copyable{ @inlinable @inline(__always) package func _ptr(at index: Int) -> UnsafePointer { diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift index 3b0ded25..e8bfc012 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift @@ -9,6 +9,15 @@ // //===----------------------------------------------------------------------===// +extension UnsafeMutableBufferPointer where Element: ~Copyable { + @inlinable + @inline(__always) + package func _ptr(at index: Int) -> UnsafeMutablePointer { + assert(index >= 0 && index < count) + return baseAddress.unsafelyUnwrapped + index + } +} + extension UnsafeMutableBufferPointer where Element: ~Copyable { /// Returns a Boolean value indicating whether two /// `UnsafeMutableBufferPointer` instances refer to the same region in diff --git a/Tests/BasicContainersTests/RigidDictionaryTests.swift b/Tests/BasicContainersTests/RigidDictionaryTests.swift new file mode 100644 index 00000000..ffc0c447 --- /dev/null +++ b/Tests/BasicContainersTests/RigidDictionaryTests.swift @@ -0,0 +1,234 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import _CollectionsTestSupport +import BasicContainers +#endif + +#if compiler(>=6.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS + +class RigidDictionaryTests: CollectionTestCase { + func test_empty() { + let s = RigidDictionary() + expectEqual(s.count, 0) + expectTrue(s.isEmpty) + expectTrue(s.isFull) + expectEqual(s.capacity, 0) + expectEqual(s.freeCapacity, 0) + } + + func test_init_capacity() { + withSome("capacity", in: 0 ..< 1000) { capacity in + let d = RigidDictionary(capacity: capacity) + expectEqual(d.count, 0) + expectTrue(d.isEmpty) + expectEqual(d.isFull, capacity == 0) + expectEqual(d.capacity, capacity) + expectEqual(d.freeCapacity, capacity) + } + } + + func test_insertValue_one() { + typealias Key = LifetimeTracked + typealias Value = LifetimeTracked + withLifetimeTracking { tracker in + var d = RigidDictionary(capacity: 20) + let firstKey = tracker.instance(for: 42) + let firstValue = tracker.instance(for: "forty-two") + expectNil(d.insertValue(firstValue, forKey: firstKey)) + + let secondKey = tracker.instance(for: 42) + let secondValue = tracker.instance(for: "forty-two") + expectIdentical( + d.insertValue(secondValue, forKey: secondKey), + secondValue) + + let thirdKey = tracker.instance(for: 42) + expectNotNil(d.value(forKey: thirdKey)) { valueRef in + expectIdentical(valueRef.value, firstValue) + } + _ = consume firstValue + expectNotNil(d.value(forKey: thirdKey)) { valueRef in + expectEqual(valueRef.value.payload, "forty-two") + } + + expectEqual(d.count, 1) + expectFalse(d.isEmpty) + expectFalse(d.isFull) + expectEqual(d.capacity, 20) + expectEqual(d.freeCapacity, 19) + } + } + + func test_updateValue_one() { + typealias Key = LifetimeTracked + typealias Value = LifetimeTracked + withLifetimeTracking { tracker in + var d = RigidDictionary(capacity: 20) + let firstKey = tracker.instance(for: 42) + let firstValue = tracker.instance(for: "forty-two") + expectNil(d.updateValue(firstValue, forKey: firstKey)) + + let secondKey = tracker.instance(for: 42) + let secondValue = tracker.instance(for: "forty-two") + let res = d.updateValue(secondValue, forKey: secondKey) + expectIdentical(res, firstValue) + + let thirdKey = tracker.instance(for: 42) + expectNotNil(d.value(forKey: thirdKey)) { valueRef in + expectIdentical(valueRef.value, secondValue) + } + _ = consume secondValue + expectNotNil(d.value(forKey: thirdKey)) { valueRef in + expectEqual(valueRef.value.payload, "forty-two") + } + + expectEqual(d.count, 1) + expectFalse(d.isEmpty) + expectFalse(d.isFull) + expectEqual(d.capacity, 20) + expectEqual(d.freeCapacity, 19) + } + } + + func test_insertValue_full() { + typealias Key = LifetimeTracked + typealias Value = LifetimeTracked + withEvery("capacity", in: [0, 1, 2, 10, 100, 1000]) { capacity in + withLifetimeTracking { tracker in + var d = RigidDictionary(capacity: capacity) + for i in 0 ..< capacity { + let key = tracker.instance(for: i) + let value = tracker.instance(for: "\(i)") + let remnant = d.insertValue(value, forKey: key) + expectNil(remnant) + } + expectEqual(d.count, capacity) + expectEqual(d.isEmpty, capacity == 0) + expectTrue(d.isFull) + expectEqual(d.capacity, capacity) + expectEqual(d.freeCapacity, 0) + + for i in 0 ..< capacity { + let key = tracker.instance(for: i) + let value = tracker.instance(for: "\(i)") + let remnant = d.insertValue(value, forKey: key) + expectIdentical(remnant, value) + } + expectEqual(d.count, capacity) + expectEqual(d.isEmpty, capacity == 0) + expectTrue(d.isFull) + expectEqual(d.capacity, capacity) + expectEqual(d.freeCapacity, 0) + + for i in 0 ..< capacity { + let dupe = tracker.instance(for: i) + expectNotNil( + d.value(forKey: dupe), + "\(dupe.payload) not found" + ) { valueRef in + expectEqual(valueRef.value.payload, "\(i)") + } + } + } + } + } + + func test_updateValue_full() { + typealias Key = LifetimeTracked + typealias Value = LifetimeTracked + withEvery("capacity", in: [0, 1, 2, 10, 100, 1000]) { capacity in + withLifetimeTracking { tracker in + var d = RigidDictionary(capacity: capacity) + for i in 0 ..< capacity { + let key = tracker.instance(for: i) + let value = tracker.instance(for: "\(i)") + let old = d.updateValue(value, forKey: key) + expectNil(old) + } + expectEqual(d.count, capacity) + expectEqual(d.isEmpty, capacity == 0) + expectTrue(d.isFull) + expectEqual(d.capacity, capacity) + expectEqual(d.freeCapacity, 0) + + for i in 0 ..< capacity { + let key = tracker.instance(for: i) + let value = tracker.instance(for: "\(i)") + let old = d.updateValue(value, forKey: key) + expectNotNil(old) { old in + expectNotIdentical(old, value) + expectEqual(old, value) + } + } + expectEqual(d.count, capacity) + expectEqual(d.isEmpty, capacity == 0) + expectTrue(d.isFull) + expectEqual(d.capacity, capacity) + expectEqual(d.freeCapacity, 0) + + for i in 0 ..< capacity { + let dupe = tracker.instance(for: i) + expectNotNil( + d.value(forKey: dupe), + "\(dupe.payload) not found" + ) { valueRef in + expectEqual(valueRef.value.payload, "\(i)") + } + } + } + } + } + + func test_memoizedValue_ond() { + typealias Key = LifetimeTracked + typealias Value = LifetimeTracked + withLifetimeTracking { tracker in + var d = RigidDictionary(capacity: 20) + let key1 = tracker.instance(for: 42) + let value1 = tracker.instance(for: "\(42)") + do { + let v1 = d.memoizedValue(forKey: key1) { key in + expectIdentical(key, key1) + return value1 + } + expectIdentical(v1.value, value1) + } + + let key2 = tracker.instance(for: 42) + let value2 = tracker.instance(for: "\(42)") + do { + let v2 = d.memoizedValue(forKey: key2) { key in + expectFailure("Cached value not found") + return value2 + } + expectIdentical(v2.value, value1) + } + + let key3 = tracker.instance(for: 42) + expectNotNil(d.value(forKey: key3)) { valueRef in + expectIdentical(valueRef.value, value1) + } + + expectEqual(d.count, 1) + expectFalse(d.isEmpty) + expectFalse(d.isFull) + expectEqual(d.capacity, 20) + expectEqual(d.freeCapacity, 19) + } + } +} + +#endif diff --git a/Tests/BasicContainersTests/RigidSetTests.swift b/Tests/BasicContainersTests/RigidSetTests.swift new file mode 100644 index 00000000..2f91a3ff --- /dev/null +++ b/Tests/BasicContainersTests/RigidSetTests.swift @@ -0,0 +1,214 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +import XCTest +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import _CollectionsTestSupport +import BasicContainers +#endif + +#if compiler(>=6.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS + +class RigidSetTests: CollectionTestCase { + func test_empty() { + let s = RigidSet() + expectEqual(s.count, 0) + expectTrue(s.isEmpty) + expectTrue(s.isFull) + expectEqual(s.capacity, 0) + expectEqual(s.freeCapacity, 0) + } + + func test_init_capacity() { + withSome("capacity", in: 0 ..< 1000) { capacity in + let s = RigidSet(capacity: capacity) + expectEqual(s.count, 0) + expectTrue(s.isEmpty) + expectEqual(s.isFull, capacity == 0) + expectEqual(s.capacity, capacity) + expectEqual(s.freeCapacity, capacity) + } + } + + func test_insert_one() { + withLifetimeTracking { tracker in + var s = RigidSet>(capacity: 20) + let first = tracker.instance(for: 42) + expectNil(s.insert(first)) + let second = tracker.instance(for: 42) + expectIdentical(s.insert(second), second) + + expectTrue(s.contains(first)) + expectTrue(s.contains(second)) + _ = consume first + expectTrue(s.contains(second)) + + expectEqual(s.count, 1) + expectFalse(s.isEmpty) + expectFalse(s.isFull) + expectEqual(s.capacity, 20) + expectEqual(s.freeCapacity, 19) + } + } + + func test_update_one() { + withLifetimeTracking { tracker in + var s = RigidSet>(capacity: 20) + let first = tracker.instance(for: 42) + expectNil(s.update(with: first)) + let second = tracker.instance(for: 42) + expectIdentical(s.update(with: second), first) + + expectTrue(s.contains(first)) + expectTrue(s.contains(second)) + _ = consume second + expectTrue(s.contains(first)) + + expectEqual(s.count, 1) + expectFalse(s.isEmpty) + expectFalse(s.isFull) + expectEqual(s.capacity, 20) + expectEqual(s.freeCapacity, 19) + } + } + + func test_insert_full() { + withEvery("capacity", in: [0, 1, 2, 10, 100, 1000]) { capacity in + withLifetimeTracking { tracker in + var s = RigidSet>(capacity: capacity) + for i in 0 ..< capacity { + let new = tracker.instance(for: i) + let remnant = s.insert(new) + expectNil(remnant) + } + expectEqual(s.count, capacity) + expectEqual(s.isEmpty, capacity == 0) + expectTrue(s.isFull) + expectEqual(s.capacity, capacity) + expectEqual(s.freeCapacity, 0) + + for i in 0 ..< capacity { + let dupe = tracker.instance(for: i) + if s.contains(dupe) { + expectIdentical(s.insert(dupe), dupe) + } else { + expectFailure("\(dupe.payload) not found") + } + } + } + } + } + + func test_update_full() { + withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 200, 201, 202, 203, 1000]) { capacity in + withLifetimeTracking { tracker in + var s = RigidSet>(capacity: capacity) + for i in 0 ..< capacity { + let new = tracker.instance(for: i) + let old = s.update(with: new) + expectNil(old) + } + expectEqual(s.count, capacity) + expectEqual(s.isEmpty, capacity == 0) + expectTrue(s.isFull) + expectEqual(s.capacity, capacity) + expectEqual(s.freeCapacity, 0) + + for i in 0 ..< capacity { + let new = tracker.instance(for: i) + let old = s.update(with: new) + expectNotNil(old) { old in + expectNotIdentical(old, new) + } + } + expectEqual(s.count, capacity) + expectEqual(s.isEmpty, capacity == 0) + expectTrue(s.isFull) + expectEqual(s.capacity, capacity) + expectEqual(s.freeCapacity, 0) + + for i in 0 ..< capacity { + let dupe = tracker.instance(for: i) + expectTrue(s.contains(dupe), "\(dupe) not found") + } + } + } + } + + func test_bucketIterator_consistency() { + withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 1000]) { capacity in + withEvery("maximumCount", in: [1, 2, 3, Int.max]) { maximumCount in + withLifetimeTracking { tracker in + var s = RigidSet>(capacity: capacity) + withEvery("i", in: 0 ..< capacity) { i in + s.insert(tracker.instance(for: i)) + + var it = s._table.makeBucketIterator() + var j = s._table.startBucket + while let next = it.nextOccupiedRegion(maximumCount: maximumCount) { + expectFalse(next.isEmpty, "Empty chunk; j: \(j), next: \(next)") + expectLessThanOrEqual( + next.upperBound.offset - next.lowerBound.offset, + maximumCount, + "Overlong chunk") + if maximumCount == Int.max, j > s._table.startBucket { + expectGreaterThan( + next.lowerBound, j, + "Unnecessarily split run of occupied buckets") + } + while j < next.lowerBound { + context.withTrace("j: \(j)") { + expectFalse(s._table.bitmap.isOccupied(j)) + } + s._table.formBucket(after: &j) + } + while j < next.upperBound { + context.withTrace("j: \(j)") { + expectTrue(s._table.isOccupied(j)) + } + s._table.formBucket(after: &j) + } + } + } + } + } + } + } + + func test_iterate() { + withEvery("capacity", in: [0, 1, 2, 3, 4, 10, 100, 1000]) { capacity in + withEvery("maximumCount", in: [1, 2, 3, Int.max]) { maximumCount in + withLifetimeTracking { tracker in + var s = RigidSet>(capacity: capacity) + withEvery("i", in: 0 ..< capacity) { i in + s.insert(tracker.instance(for: i)) + + var expected = Set(0 ... i) + var it = s.makeBorrowingIterator() + while true { + let next = it.nextSpan(maximumCount: maximumCount) + guard !next.isEmpty else { break } + expectLessThanOrEqual(next.count, maximumCount) + for j in next.indices { + let v = next[j].payload + expectEqual(expected.remove(v), v, "Unexpected item \(v)") + } + } + expectEqual(expected.count, 0, "Iterator skipped items \(expected)") + } + } + } + } + } +} +#endif diff --git a/Tests/ContainersTests/BoxTests.swift b/Tests/ContainersTests/BoxTests.swift index 163dc5d9..0e4d1f7f 100644 --- a/Tests/ContainersTests/BoxTests.swift +++ b/Tests/ContainersTests/BoxTests.swift @@ -33,11 +33,11 @@ final class BoxTests: XCTestCase { #if COLLECTIONS_UNSTABLE_CONTAINERS_PREVIEW var inoutToIntOnHeap = intOnHeap.leak() - XCTAssertEqual(inoutToIntOnHeap[], 123) + XCTAssertEqual(inoutToIntOnHeap.value, 123) - inoutToIntOnHeap[] = 321 + inoutToIntOnHeap.value = 321 - XCTAssertEqual(inoutToIntOnHeap[], 321) + XCTAssertEqual(inoutToIntOnHeap.value, 321) #endif } } diff --git a/Tests/ContainersTests/InoutTests.swift b/Tests/ContainersTests/InoutTests.swift index 9e379ef3..fcc41ba3 100644 --- a/Tests/ContainersTests/InoutTests.swift +++ b/Tests/ContainersTests/InoutTests.swift @@ -23,12 +23,12 @@ final class InoutTests: XCTestCase { var x = 0 var y = Inout(&x) - var v = y[] + var v = y.value XCTAssertEqual(v, 0) - y[] += 10 + y.value += 10 - v = y[] + v = y.value XCTAssertEqual(v, 10) XCTAssertEqual(x, 10) } diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift index 8390202d..5496c075 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift @@ -87,8 +87,8 @@ public func expectNil( message, trapping: trapping, file: file, line: line) } -public func expectNotNil( - _ value: Optional, +public func expectNotNil( + _ value: borrowing Optional, _ message: @autoclosure () -> String = "", trapping: Bool = false, file: StaticString = #filePath, @@ -100,21 +100,22 @@ public func expectNotNil( message, trapping: trapping, file: file, line: line) } -public func expectNotNil( - _ value: Optional, +public func expectNotNil( + _ value: borrowing Optional, _ message: @autoclosure () -> String = "", trapping: Bool = false, file: StaticString = #filePath, line: UInt = #line, - _ handler: (T) throws -> Void = { _ in } + _ handler: (borrowing T) throws -> Void = { _ in } ) rethrows { - if let value = value { + switch value { + case let value?: try handler(value) - return + case nil: + _expectFailure( + "value is nil", + message, trapping: trapping, file: file, line: line) } - _expectFailure( - "value is nil", - message, trapping: trapping, file: file, line: line) } public func expectIdentical( diff --git a/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift b/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift index 0c7ec3b5..1cb908b7 100644 --- a/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift +++ b/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift @@ -10,6 +10,12 @@ // //===----------------------------------------------------------------------===// +#if COLLECTIONS_SINGLE_MODULE +import Collections +#else +import BasicContainers +#endif + /// A type that tracks the number of live instances. /// /// `LifetimeTracked` conforms to `CustomStringConvertible`, and conditionally @@ -72,6 +78,11 @@ extension LifetimeTracked: Hashable where Payload: Hashable { } } +#if compiler(>=6.3) && COLLECTIONS_UNSTABLE_NONCOPYABLE_KEYS +extension LifetimeTracked: GeneralizedEquatable where Payload: Equatable {} +extension LifetimeTracked: GeneralizedHashable where Payload: Hashable {} +#endif + extension LifetimeTracked: Comparable where Payload: Comparable { public static func < (left: LifetimeTracked, right: LifetimeTracked) -> Bool { return left.payload < right.payload diff --git a/Xcode/Collections.xcodeproj/project.pbxproj b/Xcode/Collections.xcodeproj/project.pbxproj index b24fe715..a93559ab 100644 --- a/Xcode/Collections.xcodeproj/project.pbxproj +++ b/Xcode/Collections.xcodeproj/project.pbxproj @@ -65,6 +65,7 @@ 7D2A779C2F27F2BF005780C7 /* Deque+ExpressibleByArrayLiteral.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A775C2F27F2BF005780C7 /* Deque+ExpressibleByArrayLiteral.swift */; }; 7D2A779F2F27F367005780C7 /* InoutTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A779E2F27F367005780C7 /* InoutTests.swift */; }; 7D2A77A02F27F367005780C7 /* BorrowTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D2A779D2F27F367005780C7 /* BorrowTests.swift */; }; + 7D3D2DC92F3E5D110055E70B /* ProtocolGeneralizations.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D3D2DC82F3E5D0E0055E70B /* ProtocolGeneralizations.swift */; }; 7D48BCDC2E51554900D7F6F7 /* ClassBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */; }; 7D48BCDF2E51558700D7F6F7 /* TestPrintable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDD2E51558700D7F6F7 /* TestPrintable.swift */; }; 7D48BCE02E51558700D7F6F7 /* LifetimeTrackedStruct.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D48BCDE2E51558700D7F6F7 /* LifetimeTrackedStruct.swift */; }; @@ -86,11 +87,23 @@ 7D57A2CE2F343CA9002543BD /* ContainerAlgorithms.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2CD2F343CA2002543BD /* ContainerAlgorithms.swift */; }; 7D57A2D02F353946002543BD /* RigidArray+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2CF2F35393E002543BD /* RigidArray+Deprecated.swift */; }; 7D57A2D22F353CA5002543BD /* UniqueArray+Deprecated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D57A2D12F353CA1002543BD /* UniqueArray+Deprecated.swift */; }; + 7D7246872F3D9DDB00112FD0 /* _HTable+Iteration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7246802F3D9DDB00112FD0 /* _HTable+Iteration.swift */; }; + 7D7246882F3D9DDB00112FD0 /* RigidDictionary.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7246832F3D9DDB00112FD0 /* RigidDictionary.swift */; }; + 7D7246892F3D9DDB00112FD0 /* _HTable+Find.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D72467E2F3D9DDB00112FD0 /* _HTable+Find.swift */; }; + 7D72468A2F3D9DDB00112FD0 /* _HTable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D72467A2F3D9DDB00112FD0 /* _HTable.swift */; }; + 7D72468B2F3D9DDB00112FD0 /* _HTable+Insert.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D72467F2F3D9DDB00112FD0 /* _HTable+Insert.swift */; }; + 7D72468C2F3D9DDB00112FD0 /* RigidSet.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7246852F3D9DDB00112FD0 /* RigidSet.swift */; }; + 7D72468D2F3D9DDB00112FD0 /* _HTable+Bucket.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D72467C2F3D9DDB00112FD0 /* _HTable+Bucket.swift */; }; + 7D72468E2F3D9DDB00112FD0 /* _HTable+Bitmap.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D72467B2F3D9DDB00112FD0 /* _HTable+Bitmap.swift */; }; + 7D72468F2F3D9DDB00112FD0 /* _HTable+Small.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7246812F3D9DDB00112FD0 /* _HTable+Small.swift */; }; + 7D7246902F3D9DDB00112FD0 /* _HTable+Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D72467D2F3D9DDB00112FD0 /* _HTable+Constants.swift */; }; + 7D7246922F3D9E6800112FD0 /* RigidSetTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D7246912F3D9E6800112FD0 /* RigidSetTests.swift */; }; 7D9748D42E9748930098631A /* BigString+Chunk+UTF16.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D32E9748930098631A /* BigString+Chunk+UTF16.swift */; }; 7D9748D52E9748930098631A /* BigString+Chunk+UnicodeScalar.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */; }; 7D9748D62E9748930098631A /* BigString+Chunk+Character.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */; }; 7D9748D72E9748930098631A /* BigString+Chunk+Index.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D02E9748930098631A /* BigString+Chunk+Index.swift */; }; 7D9748D82E9748930098631A /* BigString+Chunk+UTF8.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9748D22E9748930098631A /* BigString+Chunk+UTF8.swift */; }; + 7D9B75772F3E65E00048157E /* _Htable+Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B75762F3E65DB0048157E /* _Htable+Debugging.swift */; }; 7D9B859729E4F74400B291CD /* BitArray+Shifts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859129E4F74400B291CD /* BitArray+Shifts.swift */; }; 7D9B859829E4F74400B291CD /* BitArray+Descriptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859229E4F74400B291CD /* BitArray+Descriptions.swift */; }; 7D9B859929E4F74400B291CD /* BitArray+LosslessStringConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7D9B859329E4F74400B291CD /* BitArray+LosslessStringConvertible.swift */; }; @@ -130,6 +143,8 @@ 7DAD89B52E8B09EC00DD5786 /* Debugging.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD89A82E8B09EC00DD5786 /* Debugging.swift */; }; 7DAD89B62E8B09EC00DD5786 /* UnsafeMutableRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD89AE2E8B09EC00DD5786 /* UnsafeMutableRawBufferPointer+Extras.swift */; }; 7DAD89B72E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DAD89AF2E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift */; }; + 7DC85F8D2F3FDC91004A4E3D /* String+Padding.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC85F8C2F3FDC82004A4E3D /* String+Padding.swift */; }; + 7DC85F8F2F43D065004A4E3D /* RigidDictionaryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DC85F8E2F43D05F004A4E3D /* RigidDictionaryTests.swift */; }; 7DE448452F2D3705005853A7 /* BinaryInteger extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE448442F2D36F9005853A7 /* BinaryInteger extensions.swift */; }; 7DE91B2F29CA6721004483EB /* Collections.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7DE91B2629CA6721004483EB /* Collections.framework */; }; 7DE9200D29CA70F3004483EB /* OrderedDictionary+Equatable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DE91E7529CA70F3004483EB /* OrderedDictionary+Equatable.swift */; }; @@ -566,6 +581,7 @@ 7D2A77762F27F2BF005780C7 /* UniqueDeque+Replacements.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UniqueDeque+Replacements.swift"; sourceTree = ""; }; 7D2A779D2F27F367005780C7 /* BorrowTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BorrowTests.swift; sourceTree = ""; }; 7D2A779E2F27F367005780C7 /* InoutTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InoutTests.swift; sourceTree = ""; }; + 7D3D2DC82F3E5D0E0055E70B /* ProtocolGeneralizations.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProtocolGeneralizations.swift; sourceTree = ""; }; 7D48BCC92E51524200D7F6F7 /* CMakeLists.txt */ = {isa = PBXFileReference; lastKnownFileType = text; path = CMakeLists.txt; sourceTree = ""; }; 7D48BCDB2E51554900D7F6F7 /* ClassBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClassBox.swift; sourceTree = ""; }; 7D48BCDD2E51558700D7F6F7 /* TestPrintable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestPrintable.swift; sourceTree = ""; }; @@ -594,11 +610,23 @@ 7D5A64D829CCF0FE00CB2595 /* README.md */ = {isa = PBXFileReference; lastKnownFileType = net.daringfireball.markdown; path = README.md; sourceTree = ""; }; 7D6FEE2F2E8880F6007C1B86 /* BasicContainers.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = BasicContainers.docc; sourceTree = ""; }; 7D6FEE312E88A4B9007C1B86 /* ContainersPreview.docc */ = {isa = PBXFileReference; lastKnownFileType = folder.documentationcatalog; path = ContainersPreview.docc; sourceTree = ""; }; + 7D72467A2F3D9DDB00112FD0 /* _HTable.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = _HTable.swift; sourceTree = ""; }; + 7D72467B2F3D9DDB00112FD0 /* _HTable+Bitmap.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Bitmap.swift"; sourceTree = ""; }; + 7D72467C2F3D9DDB00112FD0 /* _HTable+Bucket.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Bucket.swift"; sourceTree = ""; }; + 7D72467D2F3D9DDB00112FD0 /* _HTable+Constants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Constants.swift"; sourceTree = ""; }; + 7D72467E2F3D9DDB00112FD0 /* _HTable+Find.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Find.swift"; sourceTree = ""; }; + 7D72467F2F3D9DDB00112FD0 /* _HTable+Insert.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Insert.swift"; sourceTree = ""; }; + 7D7246802F3D9DDB00112FD0 /* _HTable+Iteration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Iteration.swift"; sourceTree = ""; }; + 7D7246812F3D9DDB00112FD0 /* _HTable+Small.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_HTable+Small.swift"; sourceTree = ""; }; + 7D7246832F3D9DDB00112FD0 /* RigidDictionary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidDictionary.swift; sourceTree = ""; }; + 7D7246852F3D9DDB00112FD0 /* RigidSet.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidSet.swift; sourceTree = ""; }; + 7D7246912F3D9E6800112FD0 /* RigidSetTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidSetTests.swift; sourceTree = ""; }; 7D9748CF2E9748930098631A /* BigString+Chunk+Character.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Character.swift"; sourceTree = ""; }; 7D9748D02E9748930098631A /* BigString+Chunk+Index.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+Index.swift"; sourceTree = ""; }; 7D9748D12E9748930098631A /* BigString+Chunk+UnicodeScalar.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+UnicodeScalar.swift"; sourceTree = ""; }; 7D9748D22E9748930098631A /* BigString+Chunk+UTF8.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+UTF8.swift"; sourceTree = ""; }; 7D9748D32E9748930098631A /* BigString+Chunk+UTF16.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BigString+Chunk+UTF16.swift"; sourceTree = ""; }; + 7D9B75762F3E65DB0048157E /* _Htable+Debugging.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "_Htable+Debugging.swift"; sourceTree = ""; }; 7D9B859129E4F74400B291CD /* BitArray+Shifts.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Shifts.swift"; sourceTree = ""; }; 7D9B859229E4F74400B291CD /* BitArray+Descriptions.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+Descriptions.swift"; sourceTree = ""; }; 7D9B859329E4F74400B291CD /* BitArray+LosslessStringConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BitArray+LosslessStringConvertible.swift"; sourceTree = ""; }; @@ -639,6 +667,8 @@ 7DAD89AD2E8B09EC00DD5786 /* UnsafeMutableBufferPointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafeMutableBufferPointer+Extras.swift"; sourceTree = ""; }; 7DAD89AE2E8B09EC00DD5786 /* UnsafeMutableRawBufferPointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafeMutableRawBufferPointer+Extras.swift"; sourceTree = ""; }; 7DAD89AF2E8B09EC00DD5786 /* UnsafeRawBufferPointer+Extras.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UnsafeRawBufferPointer+Extras.swift"; sourceTree = ""; }; + 7DC85F8C2F3FDC82004A4E3D /* String+Padding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+Padding.swift"; sourceTree = ""; }; + 7DC85F8E2F43D05F004A4E3D /* RigidDictionaryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RigidDictionaryTests.swift; sourceTree = ""; }; 7DE448442F2D36F9005853A7 /* BinaryInteger extensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BinaryInteger extensions.swift"; sourceTree = ""; }; 7DE448462F2D3940005853A7 /* BitCollections reexports.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BitCollections reexports.swift"; sourceTree = ""; }; 7DE448472F2D3984005853A7 /* DequeModule reexports.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "DequeModule reexports.swift"; sourceTree = ""; }; @@ -1179,6 +1209,39 @@ path = ContainersTests; sourceTree = ""; }; + 7D7246822F3D9DDB00112FD0 /* HashTable */ = { + isa = PBXGroup; + children = ( + 7D3D2DC82F3E5D0E0055E70B /* ProtocolGeneralizations.swift */, + 7D72467A2F3D9DDB00112FD0 /* _HTable.swift */, + 7D72467B2F3D9DDB00112FD0 /* _HTable+Bitmap.swift */, + 7D72467C2F3D9DDB00112FD0 /* _HTable+Bucket.swift */, + 7D72467D2F3D9DDB00112FD0 /* _HTable+Constants.swift */, + 7D72467E2F3D9DDB00112FD0 /* _HTable+Find.swift */, + 7D72467F2F3D9DDB00112FD0 /* _HTable+Insert.swift */, + 7D7246802F3D9DDB00112FD0 /* _HTable+Iteration.swift */, + 7D7246812F3D9DDB00112FD0 /* _HTable+Small.swift */, + 7D9B75762F3E65DB0048157E /* _Htable+Debugging.swift */, + ); + path = HashTable; + sourceTree = ""; + }; + 7D7246842F3D9DDB00112FD0 /* RigidDictionary */ = { + isa = PBXGroup; + children = ( + 7D7246832F3D9DDB00112FD0 /* RigidDictionary.swift */, + ); + path = RigidDictionary; + sourceTree = ""; + }; + 7D7246862F3D9DDB00112FD0 /* RigidSet */ = { + isa = PBXGroup; + children = ( + 7D7246852F3D9DDB00112FD0 /* RigidSet.swift */, + ); + path = RigidSet; + sourceTree = ""; + }; 7DA23F3D2F329A2300E4C03A /* RigidArray */ = { isa = PBXGroup; children = ( @@ -1186,6 +1249,7 @@ 7DA23F362F329A2300E4C03A /* RigidArray+Append.swift */, 7D57A2B72F33FF48002543BD /* RigidArray+Consumption.swift */, 7DA23F372F329A2300E4C03A /* RigidArray+Container.swift */, + 7D57A2CF2F35393E002543BD /* RigidArray+Deprecated.swift */, 7DA23F5B2F32C68B00E4C03A /* RigidArray+Descriptions.swift */, 7DA23F572F32C65900E4C03A /* RigidArray+Equatable.swift */, 7DA23F382F329A2300E4C03A /* RigidArray+Experimental.swift */, @@ -1194,7 +1258,6 @@ 7DA23F3A2F329A2300E4C03A /* RigidArray+Insertions.swift */, 7DA23F3B2F329A2300E4C03A /* RigidArray+Removals.swift */, 7DA23F3C2F329A2300E4C03A /* RigidArray+Replacements.swift */, - 7D57A2CF2F35393E002543BD /* RigidArray+Deprecated.swift */, ); path = RigidArray; sourceTree = ""; @@ -1206,6 +1269,7 @@ 7DA23F3F2F329A2300E4C03A /* UniqueArray+Append.swift */, 7D57A2B92F340B53002543BD /* UniqueArray+Consumption.swift */, 7DA23F552F329E8A00E4C03A /* UniqueArray+Container.swift */, + 7D57A2D12F353CA1002543BD /* UniqueArray+Deprecated.swift */, 7D57A2BB2F342DEE002543BD /* UniqueArray+Descriptions.swift */, 7D57A2BC2F342DEE002543BD /* UniqueArray+Equatable.swift */, 7DA23F402F329A2300E4C03A /* UniqueArray+Experimental.swift */, @@ -1214,7 +1278,6 @@ 7DA23F422F329A2300E4C03A /* UniqueArray+Insertions.swift */, 7DA23F432F329A2300E4C03A /* UniqueArray+Removals.swift */, 7DA23F442F329A2300E4C03A /* UniqueArray+Replacements.swift */, - 7D57A2D12F353CA1002543BD /* UniqueArray+Deprecated.swift */, ); path = UniqueArray; sourceTree = ""; @@ -1570,6 +1633,7 @@ 7DAD89AA2E8B09EC00DD5786 /* LifetimeOverride.swift */, 7DAD89AB2E8B09EC00DD5786 /* RandomAccessCollection+Offsets.swift */, 7D2A77252F27F1D1005780C7 /* Span+Extras.swift */, + 7DC85F8C2F3FDC82004A4E3D /* String+Padding.swift */, 7DAD89AC2E8B09EC00DD5786 /* UnsafeBufferPointer+Extras.swift */, 7DAD89AD2E8B09EC00DD5786 /* UnsafeMutableBufferPointer+Extras.swift */, 7DAD89AE2E8B09EC00DD5786 /* UnsafeMutableRawBufferPointer+Extras.swift */, @@ -2084,6 +2148,9 @@ A93AC20F2E7C841700A824DF /* CMakeLists.txt */, 7DA23F3D2F329A2300E4C03A /* RigidArray */, 7DA23F452F329A2300E4C03A /* UniqueArray */, + 7D7246822F3D9DDB00112FD0 /* HashTable */, + 7D7246862F3D9DDB00112FD0 /* RigidSet */, + 7D7246842F3D9DDB00112FD0 /* RigidDictionary */, 7D6FEE2F2E8880F6007C1B86 /* BasicContainers.docc */, ); path = BasicContainers; @@ -2095,6 +2162,8 @@ A93AC21A2E7C845300A824DF /* ArrayLayout.swift */, A93AC21B2E7C845300A824DF /* RigidArrayTests.swift */, A93AC21C2E7C845300A824DF /* UniqueArrayTests.swift */, + 7D7246912F3D9E6800112FD0 /* RigidSetTests.swift */, + 7DC85F8E2F43D05F004A4E3D /* RigidDictionaryTests.swift */, ); path = BasicContainersTests; sourceTree = ""; @@ -2263,6 +2332,7 @@ 7D2A778C2F27F2BF005780C7 /* UniqueDeque+Prepend.swift in Sources */, 7D2A778D2F27F2BF005780C7 /* UniqueDeque.swift in Sources */, 7D2A778E2F27F2BF005780C7 /* RigidDeque.swift in Sources */, + 7D3D2DC92F3E5D110055E70B /* ProtocolGeneralizations.swift in Sources */, 7D2A778F2F27F2BF005780C7 /* Deque+CustomReflectable.swift in Sources */, 7D2A77902F27F2BF005780C7 /* RigidDeque+Insertions.swift in Sources */, 7D2A77912F27F2BF005780C7 /* RigidDeque+Removals.swift in Sources */, @@ -2276,6 +2346,16 @@ 7D2A77962F27F2BF005780C7 /* RigidDeque+Experimental.swift in Sources */, 7D2A77972F27F2BF005780C7 /* Deque+Testing.swift in Sources */, 7D2A77982F27F2BF005780C7 /* RigidDeque+Replacements.swift in Sources */, + 7D7246872F3D9DDB00112FD0 /* _HTable+Iteration.swift in Sources */, + 7D7246882F3D9DDB00112FD0 /* RigidDictionary.swift in Sources */, + 7D7246892F3D9DDB00112FD0 /* _HTable+Find.swift in Sources */, + 7D72468A2F3D9DDB00112FD0 /* _HTable.swift in Sources */, + 7D72468B2F3D9DDB00112FD0 /* _HTable+Insert.swift in Sources */, + 7D72468C2F3D9DDB00112FD0 /* RigidSet.swift in Sources */, + 7D72468D2F3D9DDB00112FD0 /* _HTable+Bucket.swift in Sources */, + 7D72468E2F3D9DDB00112FD0 /* _HTable+Bitmap.swift in Sources */, + 7D72468F2F3D9DDB00112FD0 /* _HTable+Small.swift in Sources */, + 7D7246902F3D9DDB00112FD0 /* _HTable+Constants.swift in Sources */, 7D2A77992F27F2BF005780C7 /* Deque+Descriptions.swift in Sources */, 7D2A779A2F27F2BF005780C7 /* RigidDeque+Testing.swift in Sources */, 7D2A779B2F27F2BF005780C7 /* UniqueDeque+Experimental.swift in Sources */, @@ -2327,6 +2407,7 @@ 7DE9214E29CA70F4004483EB /* _HashNode+Debugging.swift in Sources */, 7DE920A029CA70F4004483EB /* Rope+Join.swift in Sources */, 7DE9213E29CA70F4004483EB /* TreeSet+SetAlgebra union.swift in Sources */, + 7D9B75772F3E65E00048157E /* _Htable+Debugging.swift in Sources */, 7DE9214829CA70F4004483EB /* _HashNode+Primitive Removals.swift in Sources */, 7DE9216029CA70F4004483EB /* _HashNode+Structural isDisjoint.swift in Sources */, 7DE9203529CA70F3004483EB /* OrderedSet+CustomReflectable.swift in Sources */, @@ -2338,6 +2419,7 @@ 7DE9212A29CA70F4004483EB /* TreeSet+Extras.swift in Sources */, 7DE9209A29CA70F4004483EB /* Rope+Append.swift in Sources */, 7DE9203F29CA70F3004483EB /* OrderedSet+Partial SetAlgebra isDisjoint.swift in Sources */, + 7DC85F8D2F3FDC91004A4E3D /* String+Padding.swift in Sources */, 7DE9208629CA70F4004483EB /* BigString+LosslessStringConvertible.swift in Sources */, 7DE9204329CA70F3004483EB /* _HashTable+Bucket.swift in Sources */, 7DE9216A29CA70F4004483EB /* TreeDictionary.swift in Sources */, @@ -2649,6 +2731,8 @@ 7DE9221B29CA8576004483EB /* DequeInternals.swift in Sources */, 7DEBDB6E29CCE44A00ADC226 /* SortedCollectionAPIChecker.swift in Sources */, 7DE9220929CA8576004483EB /* BitArrayTests.swift in Sources */, + 7DC85F8F2F43D065004A4E3D /* RigidDictionaryTests.swift in Sources */, + 7D7246922F3D9E6800112FD0 /* RigidSetTests.swift in Sources */, 7DE9221629CA8576004483EB /* OrderedSet.UnorderedView Tests.swift in Sources */, 7DEBDB7529CCE44A00ADC226 /* MinimalCollection.swift in Sources */, 7DEBDB8C29CCE44A00ADC226 /* MinimalIterator.swift in Sources */, diff --git a/Xcode/Shared.xcconfig b/Xcode/Shared.xcconfig index c447ce81..fd2d2ca2 100644 --- a/Xcode/Shared.xcconfig +++ b/Xcode/Shared.xcconfig @@ -20,9 +20,12 @@ OTHER_SWIFT_FLAGS = $(inherited) \ -enable-experimental-feature Lifetimes \ -enable-experimental-feature InoutLifetimeDependence \ -enable-experimental-feature SuppressedAssociatedTypes \ + -enable-experimental-feature AddressableParameters \ + -enable-experimental-feature AddressableTypes \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.0: macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2" \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.1: macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0" \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.6: macOS 12.3, iOS 15.4, watchOS 8.5, tvOS 15.4" \ + -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.7: macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0" \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.8: macOS 13.3, iOS 16.4, watchOS 9.4, tvOS 16.4" \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.9: macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0" \ -enable-experimental-feature "AvailabilityMacro=SwiftStdlib 5.10: macOS 14.4, iOS 17.4, watchOS 10.4, tvOS 17.4, visionOS 1.1" \