mirror of
https://github.com/apple/swift-collections
synced 2026-11-30 05:18:44 +00:00
Merge pull request #713 from lorentey/container-updates
Conform RigidSet/UniqueSet to Container and add Container validator
This commit is contained in:
19 files changed
+912
-134
No files matched your search
@@ -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<Bucket> {
|
||||
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
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Element> {
|
||||
_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<Element> {
|
||||
_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
|
||||
@@ -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<Element>?
|
||||
package var _baseAddress: UnsafePointer<Element>?
|
||||
|
||||
@_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<Element>
|
||||
) {
|
||||
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<Element>,
|
||||
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<Element> {
|
||||
internal func _span(from start: _Bucket, to end: _Bucket) -> Span<Element> {
|
||||
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<Element> {
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,6 +59,22 @@ extension UniqueSet where Element: ~Copyable {
|
||||
_storage[index]
|
||||
}
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_lifetime(borrow self)
|
||||
public func nextSpan(
|
||||
after index: inout Index
|
||||
) -> Span<Element> {
|
||||
_storage.nextSpan(after: &index)
|
||||
}
|
||||
|
||||
@inlinable
|
||||
@_lifetime(borrow self)
|
||||
public func nextSpan(
|
||||
after index: inout Index, maxCount: Int, limitedBy limit: Index
|
||||
) -> Span<Element> {
|
||||
_storage.nextSpan(after: &index, maxCount: maxCount, limitedBy: limit)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -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<Index>) -> SubrangeConsumer {
|
||||
//...
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -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<Index>) -> SubrangeConsumer {
|
||||
//...
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
@available(SwiftStdlib 5.0, *)
|
||||
extension UniqueSet where Element: ~Copyable {
|
||||
@_alwaysEmitIntoClient
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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<LifetimeTrackedStruct<Int>> = .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)
|
||||
|
||||
@@ -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<UniqueArray<Int>?>.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
|
||||
|
||||
@@ -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<LifetimeTrackedStruct<Int>> = .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
|
||||
|
||||
@@ -214,6 +214,23 @@ public func expectEquivalent<A, B>(
|
||||
#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
|
||||
|
||||
@@ -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<S.Element>
|
||||
public func checkContainer<
|
||||
C: Container & ~Copyable & ~Escapable,
|
||||
Expected: Sequence<C.Element>
|
||||
>(
|
||||
_ 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<S.Element>
|
||||
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<String, Any>,
|
||||
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<Int>] = try { () throws(S.Failure) in
|
||||
var r: [Range<Int>] = []
|
||||
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<Element>
|
||||
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
|
||||
@@ -54,11 +54,13 @@ public class LifetimeTracked<Payload> {
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -62,14 +62,15 @@ public struct LifetimeTrackedStruct<Payload: ~Copyable>: ~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
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user