From 225bd07e56c4714a4a70951f9ddd829165988563 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 31 Aug 2026 19:18:33 -0700 Subject: [PATCH 1/2] RigidSet, UniqueSet: Add Container conformance --- .../HashTable/_HTable+Bitmap.swift | 82 ++++++++++++++++++- .../HashTable/_HTable+Bucket.swift | 14 ++++ .../HashTable/_HTable+Insert.swift | 4 +- .../HashTable/_HTable+Iteration.swift | 18 ++-- .../RigidSet/RigidSet+Debugging.swift | 12 ++- .../RigidSet/RigidSet+Index.swift | 82 ++++++++++++++++++- .../RigidSet/RigidSet+Iterable.swift | 55 ++++++++++--- .../UniqueSet/UniqueSet+Index.swift | 16 ++++ .../Conformances/RigidSet+Container.swift | 35 +++++++- .../Conformances/UniqueSet+Container.swift | 29 +++++++ 10 files changed, 316 insertions(+), 31 deletions(-) diff --git a/Sources/BasicContainers/HashTable/_HTable+Bitmap.swift b/Sources/BasicContainers/HashTable/_HTable+Bitmap.swift index 63f0f394..75779880 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Bitmap.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Bitmap.swift @@ -35,6 +35,9 @@ extension _HTable { } extension _HTable.Bitmap { + @usableFromInline + package typealias Word = _HTable.Word + @_transparent @inlinable package func isValid(_ bucket: Bucket) -> Bool { @@ -79,7 +82,7 @@ extension _HTable.Bitmap { @inlinable package func firstOccupiedBucket(from start: Bucket) -> Bucket? { - assert(isValid(start)) + guard isValid(start) else { return nil } var word = start.word var bits = _words[word] @@ -97,11 +100,33 @@ extension _HTable.Bitmap { } } + @inlinable + package func firstOccupiedBucket( + from start: Bucket, limit: Bucket + ) -> Bucket { + assert(isValid(start) && start <= limit && limit.word <= _words.count) + var word = start.word + var bits = _words[word] + bits.removeAll(upTo: start.bit) + while word < limit.word { + if let bit = bits.firstMember { + return Bucket(word: word, bit: bit) + } + word &+= 1 + bits = word < _words.count ? _words[word] : .empty + } + bits.removeAll(from: limit.bit) + if let bit = bits.firstMember { + return Bucket(word: word, bit: bit) + } + return limit + } + /// Note: If the bitmap has fewer than Word.capacity bits, then this may /// report an unoccupied bit beyond the end of its actual size. @inlinable - package func firstUnoccupiedBucket(from start: Bucket) -> Bucket { - assert(isValid(start)) + package func collisionChainEnd(from start: Bucket) -> Bucket { + assert(isOccupied(start)) var word = start.word var bits = _words[word] bits.insertAll(upTo: start.bit) @@ -120,5 +145,56 @@ extension _HTable.Bitmap { bits = _words[word] } } + + /// Note: If the bitmap has fewer than Word.capacity bits, then this may + /// report an unoccupied bit beyond the end of its actual size. + internal func _nextOccupiedChunkEnd( + from start: Bucket, + maxCount: Int + ) -> Bucket { + assert(isValid(start)) + var word = start.word + var bits = _words[word] + bits.insertAll(upTo: start.bit) + var remainder = Swift.min( + UInt(bitPattern: maxCount) &+ start.bit, + UInt(bitPattern: (_words.count &- start.word) &* Word.capacity)) + while true { + bits.formComplement() + if let bit = bits.firstMember { + return Bucket(word: word, bit: Swift.min(bit, remainder)) + } + if remainder < Word.capacity { + break + } + word &+= 1 + remainder &-= Word._capacity + guard remainder > 0 else { break } + assert(word < _words.count) + bits = _words[word] + } + return Bucket(word: word, bit: remainder) + } + + @usableFromInline + package func nextOccupiedRegion( + from bucket: inout Bucket, + maxCount: Int, + limit: Bucket + ) -> Range { + assert(isOccupied(bucket)) + assert(bucket <= limit) + assert(maxCount > 0) + let end = self._nextOccupiedChunkEnd( + from: bucket, + maxCount: Swift.min(maxCount, limit.offset &- bucket.offset)) + let result = Range(uncheckedBounds: (bucket, end)) + if isValid(end), !isOccupied(end) { + bucket = firstOccupiedBucket(from: end, limit: limit) + } else { + bucket = end + } + return result + } } #endif diff --git a/Sources/BasicContainers/HashTable/_HTable+Bucket.swift b/Sources/BasicContainers/HashTable/_HTable+Bucket.swift index 898caed3..31bcc7a0 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Bucket.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Bucket.swift @@ -82,6 +82,20 @@ extension _HTable.Bucket: Comparable { } } +extension _HTable.Bucket: Hashable { + @_transparent + @usableFromInline + package func hash(into hasher: inout Hasher) { + hasher.combine(self.offset) + } + + @_transparent + @usableFromInline + package func _rawHashValue(seed: Int) -> Int { + self.offset._rawHashValue(seed: seed) + } +} + extension _HTable.Bucket { @_alwaysEmitIntoClient @_transparent diff --git a/Sources/BasicContainers/HashTable/_HTable+Insert.swift b/Sources/BasicContainers/HashTable/_HTable+Insert.swift index 2829a2c1..c74ebf89 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Insert.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Insert.swift @@ -41,9 +41,9 @@ extension _HTable { #if COLLECTIONS_NO_ROBIN_HOOD_HASHING let ideal = idealBucket(forHashValue: hashValue) let bitmap = self.bitmap - var actual = bitmap.firstUnoccupiedBucket(from: ideal) + var actual = bitmap.collisionChainEnd(from: ideal) if actual._offset >= self.bucketCount { - actual = bitmap.firstUnoccupiedBucket(from: Bucket(offset: 0)) + actual = bitmap.collisionChainEnd(from: Bucket(offset: 0)) } bitmap.setOccupied(actual) let probeLength = self.probeLength(from: ideal, to: actual) diff --git a/Sources/BasicContainers/HashTable/_HTable+Iteration.swift b/Sources/BasicContainers/HashTable/_HTable+Iteration.swift index 728ee918..bd7970c3 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Iteration.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Iteration.swift @@ -131,7 +131,14 @@ extension _HTable.BucketIterator { restart() } - + @usableFromInline + @_lifetime(self: copy self) + package mutating func advanceToEnd() { + _bucket = _endBucket + _nextBits = .empty + _nextBitCount = 0 + } + @usableFromInline @discardableResult @_lifetime(self: copy self) @@ -139,9 +146,7 @@ extension _HTable.BucketIterator { assert(!isAtEnd) _bucket.advanceToNextWord() if isAtEnd { - _bucket = _endBucket - _nextBits = .empty - _nextBitCount = 0 + advanceToEnd() return false } if let words = _words{ @@ -170,8 +175,7 @@ extension _HTable.BucketIterator { assert(!isAtEnd) _bucket._offset &+= 1 if isAtEnd { - _nextBits = .empty - _nextBitCount = 0 + advanceToEnd() return false } guard let words = _words else { return true } @@ -373,7 +377,7 @@ extension _HTable.BucketIterator { let end = self.currentBucket return Range(uncheckedBounds: (start, end)) } - + @usableFromInline @_lifetime(self: copy self) package mutating func nextUnoccupiedRegion( diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift b/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift index bd561f84..a9362064 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift @@ -118,8 +118,10 @@ extension RigidSet where Element: ~Copyable { histogram += "\n" sum += (length + 1) * count } - let avg = Double((sum * 1000 + 500) / _table.count) / 1000.0 - str += " AVG: \(avg)\n" + if _table.count > 0 { + let avg = Double((sum * 1000 + 500) / _table.count) / 1000.0 + str += " AVG: \(avg)\n" + } str += histogram } do { @@ -136,8 +138,10 @@ extension RigidSet where Element: ~Copyable { histogram += "\n" sum += length * count } - let avg = Double((sum * 1000 + 500) / _table.storageCapacity) / 1000.0 - str += " AVG: \(avg)\n" + if _table.storageCapacity > 0 { + let avg = Double((sum * 1000 + 500) / _table.storageCapacity) / 1000.0 + str += " AVG: \(avg)\n" + } str += histogram } return str diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Index.swift b/Sources/BasicContainers/RigidSet/RigidSet+Index.swift index c294ae4a..78005d74 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Index.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Index.swift @@ -11,12 +11,16 @@ // //===----------------------------------------------------------------------===// +#if !COLLECTIONS_SINGLE_MODULE +import InternalCollectionsUtilities +#endif + #if compiler(>=6.4) && UnstableHashedContainers @available(SwiftStdlib 5.0, *) extension RigidSet where Element: ~Copyable { @frozen - public struct Index: Equatable { + public struct Index: Equatable, Hashable, CustomDebugStringConvertible { @_alwaysEmitIntoClient package var _bucket: _HTable.Bucket @@ -46,6 +50,21 @@ extension RigidSet where Element: ~Copyable { public static func ==(left: Self, right: Self) -> Bool { left._bucket == right._bucket } + + @_alwaysEmitIntoClient + public func hash(into hasher: inout Hasher) { + hasher.combine(self._bucket) + } + + @_alwaysEmitIntoClient + public func _rawHashValue(seed: Int) -> Int { + self._bucket._rawHashValue(seed: seed) + } + + @_alwaysEmitIntoClient + public var debugDescription: String { + "@\(_bucket.offset)" + } } @inlinable @@ -67,7 +86,15 @@ extension RigidSet where Element: ~Copyable { package func _isOccupied(_ bucket: _Bucket) -> Bool { _table.isValid(bucket) && _table.isOccupied(bucket) } - + + @_alwaysEmitIntoClient + @_transparent + package func _checkValidIndex(_ index: Index) -> Void { + precondition( + _isOccupied(index._bucket) || index == endIndex, + "Index out of bounds") + } + @_alwaysEmitIntoClient @_transparent package func _checkItemIndex(_ index: Index) -> Void { @@ -102,6 +129,57 @@ extension RigidSet where Element: ~Copyable { return _memberPtr(at: index._bucket).pointee } } + + @inlinable + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index + ) -> Span { + _checkValidIndex(index) + if index == endIndex { return .init() } + if _table.isSmall { + let start = Int(index._offset) + let end = _table.count + let items = _memberBuf.extracting(start ..< end) + index = Index(_offset: end) + let span = Span(_unsafeElements: items) + return _overrideLifetime(span, borrowing: self) + } + let buckets = _table.bitmap.nextOccupiedRegion( + from: &index._bucket, maxCount: .max, limit: _table.endBucket) + let span = Span( + _unsafeStart: _memberPtr(at: buckets.lowerBound), + count: buckets._offsets.count) + return _overrideLifetime(span, borrowing: self) + } + + @inlinable + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index, maxCount: Int, limitedBy limit: Index + ) -> Span { + _checkValidIndex(index) + _checkValidIndex(limit) + precondition(maxCount > 0, "maxCount must be positive") + if index == endIndex { return .init() } + let limit = limit._offset < index._offset ? endIndex : limit + if _table.isSmall { + let start = Int(index._offset) + var c = Swift.min(maxCount, _table.count - start) + var end = start + end._advance(by: &c, limitedBy: Int(limit._offset)) + let items = _memberBuf.extracting(start ..< end) + index = Index(_offset: end) + let span = Span(_unsafeElements: items) + return _overrideLifetime(span, borrowing: self) + } + let buckets = _table.bitmap.nextOccupiedRegion( + from: &index._bucket, maxCount: maxCount, limit: limit._bucket) + let span = Span( + _unsafeStart: _memberPtr(at: buckets.lowerBound), + count: buckets._offsets.count) + return _overrideLifetime(span, borrowing: self) + } } #endif diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Iterable.swift b/Sources/BasicContainers/RigidSet/RigidSet+Iterable.swift index c2628fe4..8231f874 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Iterable.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Iterable.swift @@ -31,6 +31,14 @@ extension RigidSet: Iterable where Element: ~Copyable { BorrowingIterator(_set: self) } + @_alwaysEmitIntoClient + package borrowing func _validateIterator( + _ iterator: borrowing BorrowingIterator + ) -> Bool { + iterator._baseAddress == UnsafePointer(self._members) + && iterator._bucketIterator._words == UnsafePointer(self._table._bitmap) + } + @frozen public struct BorrowingIterator: BorrowingIteratorProtocol, @@ -38,26 +46,44 @@ extension RigidSet: Iterable where Element: ~Copyable { ~Escapable { @_alwaysEmitIntoClient - internal var _baseAddress: UnsafePointer? + package var _baseAddress: UnsafePointer? @_alwaysEmitIntoClient - internal var _bucketIterator: _HTable.BucketIterator - + package var _bucketIterator: _HTable.BucketIterator + + @_alwaysEmitIntoClient + package var _endBucket: _Bucket + @_alwaysEmitIntoClient @_lifetime(borrow _set) - internal init( + package init( _set: borrowing RigidSet ) { self._baseAddress = .init(_set._members) self._bucketIterator = _set._table.makeBucketIterator() + self._endBucket = self._bucketIterator._endBucket + _bucketIterator.advanceToOccupied() + } + + @_alwaysEmitIntoClient + @_lifetime(borrow _set) + package init( + _set: borrowing RigidSet, + from start: Index, + to end: Index + ) { + self._baseAddress = .init(_set._members) + self._bucketIterator = _set._table.makeBucketIterator(from: start._bucket) + self._endBucket = end._bucket + _bucketIterator.advanceToOccupied() } @_alwaysEmitIntoClient @_lifetime(copy self) - internal func _span(over buckets: Range<_Bucket>) -> Span { + internal func _span(from start: _Bucket, to end: _Bucket) -> Span { let items = UnsafeBufferPointer( - start: _baseAddress.unsafelyUnwrapped + buckets.lowerBound.offset, - count: buckets.upperBound.offset - buckets.lowerBound.offset) + start: _baseAddress.unsafelyUnwrapped + start.offset, + count: end.offset - start.offset) return _overrideLifetime(Span(_unsafeElements: items), copying: self) } @@ -65,12 +91,19 @@ extension RigidSet: Iterable where Element: ~Copyable { @_lifetime(&self) public mutating func nextSpan(maxCount: Int = .max) -> Span { precondition(maxCount > 0, "maxCount must be positive") - guard - let next = _bucketIterator.nextOccupiedRegion(maxCount: maxCount) - else { + let start = _bucketIterator.currentBucket + if start >= _endBucket { return .init() } - return _span(over: next) + assert(_bucketIterator.isOccupied) + _bucketIterator.advanceToUnoccupied(maxCount: maxCount) + var end = _bucketIterator.currentBucket + _bucketIterator.advanceToOccupied() + if _endBucket < end { + end = _endBucket + _bucketIterator.advanceToEnd() + } + return _span(from: start, to: end) } } } diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift index 615a0ab2..63022f99 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Index.swift @@ -59,6 +59,22 @@ extension UniqueSet where Element: ~Copyable { _storage[index] } } + + @inlinable + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index + ) -> Span { + _storage.nextSpan(after: &index) + } + + @inlinable + @_lifetime(borrow self) + public func nextSpan( + after index: inout Index, maxCount: Int, limitedBy limit: Index + ) -> Span { + _storage.nextSpan(after: &index, maxCount: maxCount, limitedBy: limit) + } } #endif diff --git a/Sources/ContainersPreview/Conformances/RigidSet+Container.swift b/Sources/ContainersPreview/Conformances/RigidSet+Container.swift index 42565ab4..fe014935 100644 --- a/Sources/ContainersPreview/Conformances/RigidSet+Container.swift +++ b/Sources/ContainersPreview/Conformances/RigidSet+Container.swift @@ -15,10 +15,41 @@ import BasicContainers #endif -#if compiler(>=6.4) && UnstableHashedContainers +#if compiler(>=6.4) && UnstableContainersPreview && UnstableHashedContainers @available(SwiftStdlib 5.0, *) -extension RigidSet where Element: ~Copyable { +extension RigidSet: Container where Element: ~Copyable { + @_alwaysEmitIntoClient + public func currentIndex(of iterator: inout BorrowingIterator) -> Index { + precondition(_validateIterator(iterator)) + if iterator._bucketIterator.isAtEnd { + return Index(_bucket: iterator._endBucket) + } + return Index(_bucket: iterator._bucketIterator.currentBucket) + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator( + from start: Index, to end: Index + ) -> BorrowingIterator { + _checkValidIndex(start) + _checkValidIndex(end) + return BorrowingIterator(_set: self, from: start, to: end) + } } +#if false // FIXME +@available(SwiftStdlib 5.0, *) +extension RigidSet: DrainableContainer where Element: ~Copyable { + public struct SubrangeConsumer: ~Copyable & ~Escapable { + //... + } + + public func consume(_ subrange: Range) -> SubrangeConsumer { + //... + } +} +#endif + #endif diff --git a/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift b/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift index 3eb8356a..164b21b9 100644 --- a/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift +++ b/Sources/ContainersPreview/Conformances/UniqueSet+Container.swift @@ -18,6 +18,35 @@ import SpanPreview #if compiler(>=6.4) && UnstableContainersPreview && UnstableHashedContainers +@available(SwiftStdlib 5.0, *) +extension UniqueSet: Container where Element: ~Copyable { + @_alwaysEmitIntoClient + public func currentIndex(of iterator: inout BorrowingIterator) -> Index { + _storage.currentIndex(of: &iterator) + } + + @_alwaysEmitIntoClient + @_lifetime(borrow self) + public func makeBorrowingIterator( + from start: Index, to end: Index + ) -> BorrowingIterator { + _storage.makeBorrowingIterator(from: start, to: end) + } +} + +#if false // FIXME +@available(SwiftStdlib 5.0, *) +extension UniqueSet: DrainableContainer where Element: ~Copyable { + public struct SubrangeConsumer: ~Copyable & ~Escapable { + //... + } + + public func consume(_ subrange: Range) -> SubrangeConsumer { + //... + } +} +#endif + @available(SwiftStdlib 5.0, *) extension UniqueSet where Element: ~Copyable { @_alwaysEmitIntoClient From 1f94ac8f549699afe2cbffcb2c86e64dcfdca37b Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Mon, 31 Aug 2026 19:19:28 -0700 Subject: [PATCH 2/2] Implement (partial) Container validation --- .../RigidArrayTests.swift | 2 +- .../BasicContainersTests/RigidSetTests.swift | 31 + .../UniqueArrayTests.swift | 10 +- .../BasicContainersTests/UniqueSetTests.swift | 32 +- .../AssertionContexts/Assertions.swift | 17 + .../ConformanceCheckers/CheckContainer.swift | 574 +++++++++++++++--- .../Utilities/LifetimeTracked.swift | 8 +- .../Utilities/LifetimeTrackedStruct.swift | 7 +- .../Utilities/TestPrintable.swift | 18 + 9 files changed, 596 insertions(+), 103 deletions(-) diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index d9266036..4a83fa3e 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -82,7 +82,7 @@ class RigidArrayTests: CollectionTestCase { expectRigidArrayContents(items, equalTo: expected) #if compiler(>=6.4) && UnstableContainersPreview if #available(SwiftStdlib 6.4, *) { - checkIterable(items, expectedContents: expected) + checkContainer(items, expectedContents: expected) } #endif } diff --git a/Tests/BasicContainersTests/RigidSetTests.swift b/Tests/BasicContainersTests/RigidSetTests.swift index 5ab6a976..d98f9680 100644 --- a/Tests/BasicContainersTests/RigidSetTests.swift +++ b/Tests/BasicContainersTests/RigidSetTests.swift @@ -16,6 +16,7 @@ import XCTest import Collections #else import _CollectionsTestSupport +import InternalCollectionsUtilities import BasicContainers import ContainersPreview #endif @@ -281,6 +282,36 @@ class RigidSetTests: CollectionTestCase { } } +#if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) + func test_validate_Container() { + withEvery("count", in: [0, 10, 100, 1000]) { count in + withLifetimeTracking { tracker in + var items: RigidSet> = .init(capacity: count) + for i in 0 ..< count { + guard items.insert(tracker.structInstance(for: i)) == nil else { + expectFailure("Duplicate item \(i)") + return + } + } + + // Get expected contents by iterating once. + var expected: [Int] = [] + var it = items.makeBorrowingIterator() + while let v = it.next()?.value.payload { + expected.append(v) + } + + //items._dump(bitmap: true) + checkContainer( + items, + expectedContents: expected, + by: { $0.payload == $1 }) + } + } + } +#endif + func test_probeLengths() { let c1 = 500 let scale = _HTable.minimumScale(forCapacity: c1) diff --git a/Tests/BasicContainersTests/UniqueArrayTests.swift b/Tests/BasicContainersTests/UniqueArrayTests.swift index a8278def..06e96fb7 100644 --- a/Tests/BasicContainersTests/UniqueArrayTests.swift +++ b/Tests/BasicContainersTests/UniqueArrayTests.swift @@ -16,6 +16,7 @@ import XCTest import Collections #else import _CollectionsTestSupport +import InternalCollectionsUtilities import BasicContainers #endif @@ -74,6 +75,8 @@ class UniqueArrayTests: CollectionTestCase { expectEqual(MemoryLayout?>.stride, 3 * word) } +#if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) func test_validate_Container() { withSomeArrayLayouts("layout", ofCapacities: [0, 10, 100]) { layout in withLifetimeTracking { tracker in @@ -81,14 +84,11 @@ class UniqueArrayTests: CollectionTestCase { let expected = (0 ..< layout.count).map { tracker.instance(for: $0) } expectEqual(tracker.instances, 2 * layout.count) expectUniqueArrayContents(items, equalTo: expected) -#if compiler(>=6.4) && UnstableContainersPreview - if #available(SwiftStdlib 6.4, *) { - checkIterable(items, expectedContents: expected) - } -#endif + checkContainer(items, expectedContents: expected) } } } +#endif func test_basics() { withLifetimeTracking { tracker in diff --git a/Tests/BasicContainersTests/UniqueSetTests.swift b/Tests/BasicContainersTests/UniqueSetTests.swift index f169c258..3a6cf445 100644 --- a/Tests/BasicContainersTests/UniqueSetTests.swift +++ b/Tests/BasicContainersTests/UniqueSetTests.swift @@ -16,6 +16,7 @@ import XCTest import Collections #else import _CollectionsTestSupport +import InternalCollectionsUtilities import BasicContainers #endif @@ -134,7 +135,36 @@ class UniqueSetTests: CollectionTestCase { expectEqual(set.capacity, expectedCapacities[j]) } } - + +#if compiler(>=6.4) && UnstableContainersPreview + @available(SwiftStdlib 6.4, *) + func test_validate_Container() { + withEvery("count", in: [0, 10, 100, 1000]) { count in + withLifetimeTracking { tracker in + var items: UniqueSet> = .init(minimumCapacity: count) + for i in 0 ..< count { + guard items.insert(tracker.structInstance(for: i)) == nil else { + expectFailure("Duplicate item \(i)") + return + } + } + + // Get expected contents by iterating once. + var expected: [Int] = [] + var it = items.makeBorrowingIterator() + while let v = it.next()?.value.payload { + expected.append(v) + } + + checkContainer( + items, + expectedContents: expected, + by: { $0.payload == $1 }) + } + } + } +#endif + func test_iteration_indexAfter() { let c = 1000 withLifetimeTracking { tracker in diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift index b05ed3fa..b6b9d3a5 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/Assertions.swift @@ -214,6 +214,23 @@ public func expectEquivalent( #if compiler(>=6.2) // FIXME: Remove when CustomStringConvertible starts supporting // noncopyable/nonescapable types. +public func expectEquivalent< + A: TestPrintable & ~Copyable & ~Escapable, + B +>( + _ left: borrowing A, _ right: borrowing B, + by areEquivalent: (borrowing A, borrowing B) -> Bool, + _ message: @autoclosure () -> String = "", + trapping: Bool = false, + file: StaticString = #filePath, + line: UInt = #line +) { + if areEquivalent(left, right) { return } + _expectFailure( + "'\(left.testDescription)' is not equivalent to '\(right)'", + message, trapping: trapping, file: file, line: line) +} + public func expectEquivalent< A: ~Copyable & ~Escapable, B diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift index c3755d46..0616fb02 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckContainer.swift @@ -11,7 +11,6 @@ // //===----------------------------------------------------------------------===// -#if compiler(>=6.4) && UnstableContainersPreview import XCTest #if COLLECTIONS_SINGLE_MODULE import Collections @@ -19,19 +18,21 @@ import Collections import ContainersPreview #endif +#if compiler(>=6.4) && UnstableContainersPreview @available(SwiftStdlib 6.4, *) @inlinable -public func checkIterable< - S: Iterable & ~Copyable & ~Escapable, - Expected: Sequence +public func checkContainer< + C: Container & ~Copyable & ~Escapable, + Expected: Sequence >( - _ iterable: borrowing S, + _ container: borrowing C, expectedContents: Expected, file: StaticString = #filePath, line: UInt = #line -) throws(S.Failure) where S.Element: Equatable { - try checkIterable( - iterable, +) throws(C.Failure) +where C.Element: Equatable { + checkContainer( + container, expectedContents: expectedContents, by: ==, file: file, line: line) @@ -39,100 +40,493 @@ public func checkIterable< @available(SwiftStdlib 6.4, *) @inlinable -public func checkIterable< - S: Iterable & ~Copyable & ~Escapable, - Expected: Sequence +public func checkContainer< + C: Container & ~Copyable & ~Escapable, + Expected: Sequence >( - _ iterable: borrowing S, + _ container: borrowing C, expectedContents: Expected, - by areEquivalent: (S.Element, S.Element) -> Bool, + by areEquivalent: (borrowing C.Element, Expected.Element) -> Bool, file: StaticString = #filePath, line: UInt = #line -) throws(S.Failure) where S.Element: Equatable { - let entry = TestContext.current.push("checkIterable", file: file, line: line) +) throws(C.Failure) where C.Element: Copyable { + checkContainer( + container, + expectedContents: expectedContents, + by: areEquivalent, + printer: { "\($0)" }, + file: file, + line: line) +} + +@available(SwiftStdlib 6.4, *) +@inlinable +public func checkContainer< + C: Container & ~Copyable & ~Escapable, + Expected: Sequence +>( + _ container: borrowing C, + expectedContents: Expected, + by areEquivalent: (borrowing C.Element, Expected.Element) -> Bool, + file: StaticString = #filePath, + line: UInt = #line +) throws(C.Failure) where C.Element: TestPrintable & ~Copyable { + checkContainer( + container, + expectedContents: expectedContents, + by: areEquivalent, + printer: { $0.testDescription }, + file: file, + line: line) +} + +public struct ValidationError: Error { + public let message: String + public let file: StaticString + public let line: UInt + + public init( + _ message: String, + file: StaticString = #filePath, + line: UInt = #line + ) { + self.message = message + self.file = file + self.line = line + } + + public init( + _ message: String, + _ values: KeyValuePairs, + file: StaticString = #filePath, + line: UInt = #line + ) { + var message = "\(message)\n" + for (key, value) in values { + message += " \(key): \(value)\n" + } + self.message = message + self.file = file + self.line = line + } +} + +@available(SwiftStdlib 6.4, *) +@inlinable +public func checkContainer< + C: Container & ~Copyable & ~Escapable, + Expected: Sequence +>( + _ container: borrowing C, + expectedContents: Expected, + by areEquivalent: (borrowing C.Element, Expected.Element) -> Bool, + printer: (borrowing C.Element) -> String, + file: StaticString = #filePath, + line: UInt = #line +) where C.Element: ~Copyable { + let entry = TestContext.current.push("checkContainer", file: file, line: line) defer { TestContext.current.pop(entry) } + do { + try validateContainer( + container, + expectedContents: expectedContents, + by: areEquivalent, + printer: printer) + } catch { + expectFailure(error.message, file: file, line: line) + } +} + + +@available(SwiftStdlib 6.4, *) +@inlinable +public func validateContainer< + C: Container & ~Copyable & ~Escapable, + Expected: Sequence +>( + _ container: borrowing C, + expectedContents: Expected, + by areEquivalent: (borrowing C.Element, Expected.Element) -> Bool, + printer: (borrowing C.Element) -> String, + file: StaticString = #filePath, + line: UInt = #line +) throws(ValidationError) where C.Element: ~Copyable { let expectedContents = Array(expectedContents) - expectLessThanOrEqual(iterable.underestimatedCount, expectedContents.count) - - // Check that the spans seem plausibly sized and that the indices are monotonic. - let spanShapes: [Range] = try { () throws(S.Failure) in - var r: [Range] = [] - var pos = 0 - var it = iterable.makeBorrowingIterator() - while true { - let origPos = pos - let span = try it.nextSpan() - pos += span.count - if span.isEmpty { - break - } - r.append(origPos ..< pos) - } - return r - }() - expectEqual( - spanShapes.Swift::reduce(into: 0, { $0 += $1.count }), expectedContents.count, - "Container's count does not match the sum of its spans") - - // Check that the spans have stable sizes and the expected contents. - do { - var pos = 0 - var it = iterable.makeBorrowingIterator() - var spanIndex = 0 - while true { - let span = try it.nextSpan() - if span.isEmpty { break } - expectEqual( - span.count, spanShapes[spanIndex].count, - "Container has nondeterministic span sizes") - for i in 0 ..< span.count { - expectEqual(span[i], expectedContents[pos]) - pos += 1 - } - spanIndex += 1 - } - expectEqual(spanIndex, spanShapes.endIndex) - expectEqual(pos, expectedContents.count) + // *** isEmpty, count, underestimatedCount + let underestimatedCount = container.underestimatedCount + let count = container.count + let isEmpty = container.isEmpty + guard count >= 0 else { + throw ValidationError( + "`count` must be nonnegative", + ["count": count]) } - - // Check that we can iterate one by one. - do { - var pos = 0 - var it = iterable.makeBorrowingIterator() - while true { - let span = try it.nextSpan(maxCount: 1) - if span.isEmpty { break } - expectEqual(span.count, 1) - for i in 0 ..< span.count { - expectEqual(span[i], expectedContents[pos]) - pos += 1 - } - } - expectEqual(pos, expectedContents.count) + guard underestimatedCount >= 0 else { + throw ValidationError( + "`underestimatedCount` must be nonnegative", + ["underestimatedCount": underestimatedCount]) + } + guard underestimatedCount <= count else { + throw ValidationError( + "`underestimatedCount` must be less than or equal to `count`", + ["underestimatedCount": underestimatedCount, + "count": count]) + } + guard isEmpty == (count == 0) else { + throw ValidationError( + "`isEmpty` must be consistent with `count`", + ["isEmpty": isEmpty, + "count": count]) } - // Check that we can iterate with huge maximum counts - do { - var pos = 0 - var it = iterable.makeBorrowingIterator() - var spanIndex = 0 - while true { - let span = try it.nextSpan(maxCount: Int.max) - if span.isEmpty { break } - expectEqual( - span.count, spanShapes[spanIndex].count, - "Container has inconsistent/nondeterministic span sizes") - for i in 0 ..< span.count { - expectEqual(span[i], expectedContents[pos]) - pos += 1 - } - spanIndex += 1 - } - expectEqual(spanIndex, spanShapes.endIndex) - expectEqual(pos, expectedContents.count) + // *** startIndex, endIndex + let startIndex = container.startIndex + let endIndex = container.endIndex + guard isEmpty == (startIndex == endIndex) else { + throw ValidationError( + "`isEmpty` must be consistent with `startIndex`/`endIndex` equality", + ["isEmpty": isEmpty, + "startIndex": startIndex, + "endIndex": endIndex]) } + // *** index(after:), formIndex(after:) + var indices: [C.Index] = [] + do { + var i = startIndex + for offset in 0 ..< count { + indices.append(i) + let j = container.index(after: i) + var k = i + container.formIndex(after: &k) + guard j == k else { + throw ValidationError( + "`index(after:)` must be consistent with `formIndex(after:)`", + ["offset": offset, + "index": i, + "index(after:) result": j, + "formIndex(after:) result": k]) + } + guard (offset == count - 1) == (j == endIndex) else { + throw ValidationError( + "`index(after:)` must reach `endIndex` after precisely `count` steps", + ["offset": offset, + "index": i, + "index(after:) result": j, + "endIndex": endIndex]) + } + i = j + } + } + guard indices.count == count else { + throw ValidationError( + "index(after:) exposes the wrong number of indices", + ["indexCount": indices.count, + "count": count]) + } + for offset in indices.indices { + let i = indices[offset] + guard areEquivalent(container[i], expectedContents[offset]) else { + throw ValidationError( + "`subscript(Index)` must expose the expected contents", + ["offset": offset, + "index": i, + "expected": expectedContents[offset], + "actual": printer(container[i]) + ]) + } + } + let allIndices = indices + [endIndex] + + // FIXME: Add throwing versions of checkEquatable/checkHashable/checkComparable + //checkHashable(allIndices, equalityOracle: ==) + + // *** nextSpan(after:) + + let chunks = container._chunks() + do { + // Check that the spans seem plausibly sized and that the indices are monotonic. + let sum = chunks.reduce(into: 0, { $0 += $1.count }) + guard sum == count else { + throw ValidationError( + "`nextSpan(after:)` must expose `count` elements", + ["count": count, + "sum of span counts": sum]) + } + var j = 0 + for i in chunks.indices { + let chunk = chunks[i] + precondition(allIndices[j] == chunk.start) + guard j + chunk.count < allIndices.count else { + throw ValidationError( + "`nextSpan(after:)` must expose monotonically increasing span boundaries consistent with `index(after:)`", + ["chunk start": chunk.start, + "chunk end": chunk.end, + "chunk count": chunk.count]) + } + guard + j + chunk.count < allIndices.count, + allIndices[j + chunk.count] == chunk.end + else { + throw ValidationError( + "`nextSpan(after:)` must expose monotonically increasing span boundaries consistent with `index(after:)`", + ["chunk start": chunk.start, + "chunk end": chunk.end, + "chunk count": chunk.count, + "expected chunk end": allIndices[j + chunk.count]]) + } + j += chunk.count + } + } + + do { + // Check that contents match expectations. + var i = container.startIndex + var offset = 0 + var chunkIndex = 0 + while true { + let start = i + let span = container.nextSpan(after: &i) + guard !span.isEmpty else { break } + let expected = chunks[chunkIndex] + guard + span.count == expected.count, + start == expected.start, + i == expected.end + else { + throw ValidationError( + "`nextSpan(after:)` must expose stable chunk boundaries across repeated iterations", + ["offset": offset, + "actual start": start, + "actual end": i, + "actual count": span.count, + "expected start": expected.start, + "expected end": expected.end, + "expected count": expected.count]) + } + for k in span.indices { + guard areEquivalent(span[k], expectedContents[offset]) else { + throw ValidationError( + "`nextSpan(after:)` must expose the expected contents", + ["offset": offset, + "chunk start": i, + "chunk offset": k, + "actual content": printer(span[k]), + "expected content": expectedContents[offset]]) + } + offset += 1 + } + chunkIndex += 1 + } + guard i == container.endIndex else { + throw ValidationError( + "`nextSpan(after:)` must stop at the container's `endIndex`", + ["endIndex": container.endIndex, + "end": i]) + } + } + + // *** nextSpan(after:maxCount:limitedBy:) + func checkNextSpan(maxCount: Int) throws(ValidationError) { + var offset = 0 + var i = startIndex + while true { + let start = i + let span = container.nextSpan(after: &i, maxCount: maxCount) + if span.isEmpty { break } + guard span.count <= maxCount else { + throw ValidationError( + "`nextSpan(after:maxCount:limitedBy:)` must observe `maxCount`", + ["container offset": offset, + "index": start, + "maxCount": maxCount, + "returned span count": span.count]) + } + for i in 0 ..< span.count { + guard areEquivalent(span[i], expectedContents[offset]) else { + throw ValidationError( + "`nextSpan(after:maxCount:limitedBy:)` must expose the expected contents", + ["index": start, + "maxCount": maxCount, + "offset within span": i, + "actual content": printer(span[i]), + "expected content": expectedContents[offset]]) + } + offset += 1 + } + } + guard offset == count else { + throw ValidationError( + "`nextSpan(after:maxCount:limitedBy:)` must expose `count` elements", + ["maxCount": maxCount, + "count": count, + "sum of span counts": offset]) + } + } + try checkNextSpan(maxCount: 1) + try checkNextSpan(maxCount: 2) + try checkNextSpan(maxCount: Int.max) + try checkNextSpan(maxCount: Int.max - 1) + + // *** `BorrowingIterator` + + do { + // Check that the iterator exposes consistent chunks. + let iteratorChunks = container.makeBorrowingIterator()._spanCounts() + let sum = iteratorChunks.reduce(into: 0, { $0 += $1 }) + guard sum == count else { + throw ValidationError( + "`BorrowingIterator` must expose `count` elements", + ["count": count, + "sum of span counts": sum]) + } + guard iteratorChunks == chunks.map({ $0.count }) else { + throw ValidationError( + "`BorrowingIterator` and `nextSpan` must expose consistent span boundaries", + ["nextSpan chunk sizes": chunks.map({ $0.count }), + "iterator chunk sizes": iteratorChunks]) + } + } + + func checkIterator(maxCount: Int) throws(ValidationError) { + var offset = 0 + var it = container.makeBorrowingIterator() + while true { + let i = allIndices[offset] + let j = container.currentIndex(of: &it) + guard j == i else { + throw ValidationError( + "`currentIndex(of:)` must return the iterator's current position", + ["actual": j, + "expected": i]) + } + let span = it.nextSpan(maxCount: maxCount) + if span.isEmpty { break } + guard span.count <= maxCount else { + throw ValidationError( + "`BorrowingIterator.nextSpan(maxCount:)` must observe `maxCount`", + ["container offset": offset, + "maxCount": maxCount, + "returned span count": span.count]) + } + for i in 0 ..< span.count { + guard areEquivalent(span[i], expectedContents[offset]) else { + throw ValidationError( + "`BorrowingIterator.nextSpan(maxCount:)` must expose the expected contents", + ["container offset": offset, + "maxCount": maxCount, + "offset within span": i, + "actual content": printer(span[i]), + "expected content": expectedContents[offset]]) + } + offset += 1 + } + } + guard offset == count else { + throw ValidationError( + "`BorrowingIterator.nextSpan(maxCount:)` must expose `count` elements", + ["maxCount": maxCount, + "expected count": count, + "actual count": offset]) + } + let i = container.currentIndex(of: &it) + guard i == endIndex else { + throw ValidationError( + "`currentIndex(of:)` must return `endIndex` at the end of iteration", + ["actual": i, + "expected": endIndex]) + } + } + try checkIterator(maxCount: 1) + try checkIterator(maxCount: 2) + try checkIterator(maxCount: Int.max) + try checkIterator(maxCount: Int.max - 1) + + // *** formIndex(_:offsetBy:limitedBy:)` + do { + let limits = Set([0, allIndices.count - 1, allIndices.count / 2]).sorted() + for l in limits { + for i in 0 ..< count { + let max = (l >= i ? l - i + 2 : count - i) + let deltas = ( + [0, 1, 2, 10, 20, max / 2, max - 2, max - 1, max] as Set + ).filter { $0 < max && $0 >= 0 }.sorted() + for delta in deltas { + var index = allIndices[i] + var n = delta + let limit = allIndices[l] + container.formIndex(&index, offsetBy: &n, limitedBy: limit) + let j = i + delta + if i > l || j <= l { + guard index == allIndices[j], n == 0 else { + throw ValidationError( + "`formIndex(_:offsetBy:limitedBy:)` must run to completion when the limit doesn't apply", + ["input index": allIndices[i], + "input delta": delta, + "expected index": allIndices[j], + "expected delta": 0, + "actual index": index, + "actual delta": n]) + } + } else { + guard index == limit, n == delta - l + i else { + throw ValidationError( + "`formIndex(_:offsetBy:limitedBy:)` must report partial succcess when the limit applies", + ["input index": allIndices[i], + "input delta": delta, + "expected index": limit, + "expected delta": delta - l + i, + "actual index": index, + "actual delta": n]) + } + } + } + } + } + } +} + +@available(SwiftStdlib 6.4, *) +extension BorrowingIteratorProtocol +where + Self: ~Copyable & ~Escapable, + Element: ~Copyable +{ + @inlinable + internal consuming func _spanCounts() throws(Failure) -> [Int] { + var result: [Int] = [] + var it = consume self + while true { + let c = try it.nextSpan().count + guard c > 0 else { break } + result.append(c) + } + return result + } +} + +@available(SwiftStdlib 6.4, *) +extension Container where Self: ~Copyable & ~Escapable, Element: ~Copyable { + @inlinable + internal borrowing func _chunks( + maxCount: Int? = nil + ) -> [(start: Index, end: Index, count: Int)] { + var result: [(start: Index, end: Index, count: Int)] = [] + var i = self.startIndex + while i != self.endIndex { + let start = i + let span: Span + if let maxCount { + span = self.nextSpan(after: &i, maxCount: maxCount) + } else { + span = self.nextSpan(after: &i) + } + guard !span.isEmpty else { break } + result.append((start, i, span.count)) + } + return result + } } #endif diff --git a/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift b/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift index 504d7743..b2f26e3a 100644 --- a/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift +++ b/Tests/_CollectionsTestSupport/Utilities/LifetimeTracked.swift @@ -54,11 +54,13 @@ public class LifetimeTracked { } extension LifetimeTracked: CustomStringConvertible { - public var description: String { - return "\(payload)" - } + public var description: String { "\(payload)" } } +#if compiler(>=6.2) +extension LifetimeTracked: TestPrintable {} +#endif + extension LifetimeTracked: Equatable where Payload: Equatable { public static func == (left: LifetimeTracked, right: LifetimeTracked) -> Bool { return left.payload == right.payload diff --git a/Tests/_CollectionsTestSupport/Utilities/LifetimeTrackedStruct.swift b/Tests/_CollectionsTestSupport/Utilities/LifetimeTrackedStruct.swift index d0c3e67c..9346ecdf 100644 --- a/Tests/_CollectionsTestSupport/Utilities/LifetimeTrackedStruct.swift +++ b/Tests/_CollectionsTestSupport/Utilities/LifetimeTrackedStruct.swift @@ -62,14 +62,15 @@ public struct LifetimeTrackedStruct: ~Copyable { } #if compiler(>=6.2) -extension LifetimeTrackedStruct: TestPrintable where Payload: TestPrintable & ~Copyable { +extension LifetimeTrackedStruct: TestPrintable +where Payload: TestPrintable & ~Copyable { public var testDescription: String { - return "\(payload.testDescription)" + "\(payload.testDescription)" } } #endif -#if compiler(>=6.4) && UnstableHashedContainers +#if compiler(>=6.4) extension LifetimeTrackedStruct: Equatable where Payload: Equatable & ~Copyable { public static func == (left: borrowing Self, right: borrowing Self) -> Bool { return left.payload == right.payload diff --git a/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift b/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift index 8348e4b8..0892e3a6 100644 --- a/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift +++ b/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift @@ -34,6 +34,24 @@ public protocol TestPrintable: ~Copyable, ~Escapable { var testDescription: String { get } } +extension TestPrintable where Self: CustomStringConvertible { + @inlinable + public var testDescription: String { description } +} +extension TestPrintable where Self: CustomDebugStringConvertible { + @inlinable + public var testDescription: String { debugDescription } +} +extension TestPrintable where Self: CustomStringConvertible & CustomDebugStringConvertible { + @inlinable + public var testDescription: String { description } +} + +extension Int: TestPrintable {} +extension UInt: TestPrintable {} +extension String: TestPrintable {} +extension Bool: TestPrintable {} + extension _Pointer { internal var _description: String { let hex = String(UInt(bitPattern: self), radix: 16)