From 9e7949017a0291e686e8639b97620c85e010b4fc Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Thu, 1 Oct 2026 11:44:47 -0700 Subject: [PATCH] Tests: add `unsafe` keywords where needed --- .../HashNode/_HashTreeStatistics.swift | 2 +- Tests/BasicContainersTests/ArrayLayout.swift | 6 +- .../RigidArrayTests.swift | 12 +- .../BasicContainersTests/RigidSetTests.swift | 14 +- .../UniqueArrayTests.swift | 2 +- Tests/ContainersTests/MutableRefTests.swift | 4 +- Tests/ContainersTests/RefTests.swift | 2 +- Tests/DequeTests/DequeTests.swift | 18 +- Tests/DequeTests/MutableCollectionTests.swift | 6 +- .../RangeReplaceableCollectionTests.swift | 4 +- Tests/DequeTests/RigidDequeTests.swift | 14 +- Tests/DequeTests/UnsafeBufferTrimTests.swift | 68 ++--- .../HashTable/HashTableTests.swift | 273 +++++++++--------- .../OrderedDictionary+Values Tests.swift | 16 +- .../OrderedSet/OrderedSet Diffing Tests.swift | 12 +- Tests/RopeModuleTests/TestBigString.swift | 6 +- .../BTree/Node Utils.swift | 8 +- .../BTree/Node+Balancing Tests.swift | 14 +- .../BTree/NodeTests.swift | 22 +- .../TrailingElementsTests.swift | 52 ++-- .../AssertionContexts/TestContext.swift | 18 +- .../ConformanceCheckers/CheckCollection.swift | 4 +- .../ConformanceCheckers/CheckSequence.swift | 6 +- .../Utilities/IndexRangeCollection.swift | 2 +- .../Utilities/TestPrintable.swift | 16 +- 25 files changed, 301 insertions(+), 300 deletions(-) diff --git a/Sources/HashTreeCollections/HashNode/_HashTreeStatistics.swift b/Sources/HashTreeCollections/HashNode/_HashTreeStatistics.swift index 4d918179..286c17ad 100644 --- a/Sources/HashTreeCollections/HashNode/_HashTreeStatistics.swift +++ b/Sources/HashTreeCollections/HashNode/_HashTreeStatistics.swift @@ -93,7 +93,7 @@ extension _HashNode { _ level: _HashLevel, _ stats: inout _HashTreeStatistics ) { // The empty singleton does not count as a node and occupies no space. - if self.raw.storage === _emptySingleton { return } + if unsafe self.raw.storage === _emptySingleton { return } unsafe read { stats.nodeCount += 1 diff --git a/Tests/BasicContainersTests/ArrayLayout.swift b/Tests/BasicContainersTests/ArrayLayout.swift index 2217a3cd..d37d91c6 100644 --- a/Tests/BasicContainersTests/ArrayLayout.swift +++ b/Tests/BasicContainersTests/ArrayLayout.swift @@ -117,14 +117,14 @@ extension LifetimeTracker { let buffer = UnsafeMutableBufferPointer> .allocate(capacity: layout.capacity) for i in 0 ..< layout.count { - buffer.initializeElement( + unsafe buffer.initializeElement( at: layout.capacity - layout.count + i, to: self.instance(for: generator(i))) } - var span = InputSpan(buffer: buffer, initializedCount: layout.count) + var span = unsafe InputSpan(buffer: buffer, initializedCount: layout.count) body(&span) _ = consume span - buffer.deallocate() + unsafe buffer.deallocate() } #endif diff --git a/Tests/BasicContainersTests/RigidArrayTests.swift b/Tests/BasicContainersTests/RigidArrayTests.swift index f691d9d2..082c0386 100644 --- a/Tests/BasicContainersTests/RigidArrayTests.swift +++ b/Tests/BasicContainersTests/RigidArrayTests.swift @@ -843,15 +843,15 @@ class RigidArrayTests: CollectionTestCase { let additions = UnsafeMutableBufferPointer> .allocate(capacity: c) for i in 0 ..< c { - additions.initializeElement( + unsafe additions.initializeElement( at: i, to: tracker.instance(for: layout.count + i)) } var a = tracker.rigidArray(layout: layout) - a.append(moving: additions) + unsafe a.append(moving: additions) - additions.deallocate() + unsafe additions.deallocate() expectRigidArrayContents( a, @@ -1070,15 +1070,15 @@ class RigidArrayTests: CollectionTestCase { let additions = UnsafeMutableBufferPointer> .allocate(capacity: c) for i in 0 ..< c { - additions.initializeElement( + unsafe additions.initializeElement( at: i, to: tracker.instance(for: layout.count + i)) } var a = tracker.rigidArray(layout: layout) - a.insert(moving: additions, at: i) + unsafe a.insert(moving: additions, at: i) - additions.deallocate() + unsafe additions.deallocate() var expected = Array(0 ..< layout.count) expected.insert(contentsOf: layout.count ..< layout.count + c, at: i) diff --git a/Tests/BasicContainersTests/RigidSetTests.swift b/Tests/BasicContainersTests/RigidSetTests.swift index 100114c2..768ca981 100644 --- a/Tests/BasicContainersTests/RigidSetTests.swift +++ b/Tests/BasicContainersTests/RigidSetTests.swift @@ -256,30 +256,30 @@ class RigidSetTests: CollectionTestCase { withEvery("i", in: 0 ..< capacity) { i in s.insert(tracker.instance(for: i)) - var it = s._table.makeBucketIterator() - var j = s._table.startBucket + var it = unsafe s._table.makeBucketIterator() + var j = unsafe s._table.startBucket while let next = it.nextOccupiedRegion(maxCount: maxCount) { expectFalse(next.isEmpty, "Empty chunk; j: \(j), next: \(next)") expectLessThanOrEqual( next.upperBound.offset - next.lowerBound.offset, maxCount, "Overlong chunk") - if maxCount == Int.max, j > s._table.startBucket { + if maxCount == Int.max, unsafe 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)) + expectFalse(unsafe s._table.bitmap.isOccupied(j)) } - s._table.formBucket(after: &j) + unsafe s._table.formBucket(after: &j) } while j < next.upperBound { context.withTrace("j: \(j)") { - expectTrue(s._table.isOccupied(j)) + expectTrue(unsafe s._table.isOccupied(j)) } - s._table.formBucket(after: &j) + unsafe s._table.formBucket(after: &j) } } } diff --git a/Tests/BasicContainersTests/UniqueArrayTests.swift b/Tests/BasicContainersTests/UniqueArrayTests.swift index 95de79e2..0561837b 100644 --- a/Tests/BasicContainersTests/UniqueArrayTests.swift +++ b/Tests/BasicContainersTests/UniqueArrayTests.swift @@ -1002,7 +1002,7 @@ class UniqueArrayTests: CollectionTestCase { var a = tracker.uniqueArray(layout: layout) trackedAddition.span.withUnsafeBufferPointer { buffer in - _ = a.replaceSubrange(range, copying: buffer) + _ = unsafe a.replaceSubrange(range, copying: buffer) } expectUniqueArrayContents( diff --git a/Tests/ContainersTests/MutableRefTests.swift b/Tests/ContainersTests/MutableRefTests.swift index 9419b12d..f18c9d4b 100644 --- a/Tests/ContainersTests/MutableRefTests.swift +++ b/Tests/ContainersTests/MutableRefTests.swift @@ -109,7 +109,7 @@ final class MutableRefTests: CollectionTestCase { func test_init_unsafeAddress_mutating() { var x = 789 - let pointer = withUnsafeMutablePointer(to: &x) { $0 } + let pointer = withUnsafeMutablePointer(to: &x) { unsafe $0 } var ref = unsafe _MutableRef(unsafeAddress: pointer, mutating: &x) expectEqual(ref.value, 789) ref.value = 111 @@ -120,7 +120,7 @@ final class MutableRefTests: CollectionTestCase { func test_init_unsafeImmortalAddress() { var x = 555 - let pointer = withUnsafeMutablePointer(to: &x) { $0 } + let pointer = withUnsafeMutablePointer(to: &x) { unsafe $0 } var ref = unsafe _MutableRef(unsafeImmortalAddress: pointer) expectEqual(ref.value, 555) ref.value = 666 diff --git a/Tests/ContainersTests/RefTests.swift b/Tests/ContainersTests/RefTests.swift index d7ab5968..04ce05e3 100644 --- a/Tests/ContainersTests/RefTests.swift +++ b/Tests/ContainersTests/RefTests.swift @@ -73,7 +73,7 @@ final class RefTests: CollectionTestCase { func test_init_unsafeAddress_borrowing() { let x = 123 withUnsafePointer(to: x) { pointer in - let ref = Ref(unsafeAddress: pointer, borrowing: x) + let ref = unsafe Ref(unsafeAddress: pointer, borrowing: x) expectEqual(ref.value, 123) } } diff --git a/Tests/DequeTests/DequeTests.swift b/Tests/DequeTests/DequeTests.swift index 62847849..7dbce18e 100644 --- a/Tests/DequeTests/DequeTests.swift +++ b/Tests/DequeTests/DequeTests.swift @@ -157,10 +157,10 @@ final class DequeTests: CollectionTestCase { let (deque, contents) = tracker.deque(with: layout) var it: Deque>.Iterator? - let head = Array>( + let head = unsafe Array>( unsafeUninitializedCapacity: prefix ) { buffer, count in - (it, count) = deque._copyContents(initializing: buffer) + (it, count) = unsafe deque._copyContents(initializing: buffer) } let tail = Array(IteratorSequence(it!)) expectEqualElements(head, contents.prefix(upTo: prefix)) @@ -175,15 +175,15 @@ final class DequeTests: CollectionTestCase { withEvery("count", in: [0, cap / 3, cap / 2, 2 * cap / 3, cap] as Set) { count in withLifetimeTracking { tracker in let contents = tracker.instances(for: 0 ..< count) - let d1 = Deque>( + let d1 = unsafe Deque>( unsafeUninitializedCapacity: cap, initializingWith: { target, c in - expectNotNil(target.baseAddress) + unsafe expectNotNil(target.baseAddress) expectEqual(target.count, cap) expectEqual(c, 0) contents.withUnsafeBufferPointer { source in precondition(source.count <= target.count) - target.baseAddress!.initialize( + unsafe target.baseAddress!.initialize( from: source.baseAddress!, count: source.count) } @@ -205,15 +205,15 @@ final class DequeTests: CollectionTestCase { // This function works around https://bugs.swift.org/browse/SR-14134 let contents = tracker.instances(for: 0 ..< count) expectThrows( - try Deque>( + unsafe try Deque>( unsafeUninitializedCapacity: cap, initializingWith: { target, c in - expectNotNil(target.baseAddress) + unsafe expectNotNil(target.baseAddress) expectEqual(target.count, cap) expectEqual(c, 0) contents.withUnsafeBufferPointer { source in precondition(source.count <= target.count) - target.baseAddress!.initialize( + unsafe target.baseAddress!.initialize( from: source.baseAddress!, count: source.count) } @@ -363,7 +363,7 @@ final class DequeTests: CollectionTestCase { let extra: [NSObject] = (0 ..< appendCount) .map { _ in NSObject() } .withUnsafeBufferPointer { buffer in - NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] + unsafe NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] } withHiddenCopies(if: isShared, of: &deque) { deque in contents.insert(contentsOf: extra, at: 0) diff --git a/Tests/DequeTests/MutableCollectionTests.swift b/Tests/DequeTests/MutableCollectionTests.swift index c4189981..25196157 100644 --- a/Tests/DequeTests/MutableCollectionTests.swift +++ b/Tests/DequeTests/MutableCollectionTests.swift @@ -146,11 +146,11 @@ final class MutableCollectiontests: CollectionTestCase { var (deque, expected) = tracker.deque(with: layout) let replacement = tracker.instances(for: 100 ..< 100 + layout.count) let actual: [LifetimeTracked]? = withHiddenCopies(if: isShared, of: &deque) { deque in - deque.withContiguousMutableStorageIfAvailable { buffer in - let result = Array(buffer) + unsafe deque.withContiguousMutableStorageIfAvailable { buffer in + let result = unsafe Array(buffer) expectEqual(buffer.count, replacement.count, trapping: true) for i in 0 ..< replacement.count { - buffer[i] = replacement[i] + unsafe buffer[i] = replacement[i] } return result } diff --git a/Tests/DequeTests/RangeReplaceableCollectionTests.swift b/Tests/DequeTests/RangeReplaceableCollectionTests.swift index 179f878f..94840e5f 100644 --- a/Tests/DequeTests/RangeReplaceableCollectionTests.swift +++ b/Tests/DequeTests/RangeReplaceableCollectionTests.swift @@ -76,7 +76,7 @@ final class RangeReplaceableCollectionTests: CollectionTestCase { withEvery("count", in: [0, 1, 2, 10, 100]) { count in let contents: [AnyObject] = (0 ..< count).map { _ in NSObject() } let array: [AnyObject] = contents.withUnsafeBufferPointer { buffer in - NSArray(objects: buffer.baseAddress, count: buffer.count) as [AnyObject] + unsafe NSArray(objects: buffer.baseAddress, count: buffer.count) as [AnyObject] } let deque = Deque(array) expectEquivalentElements(deque, contents, by: ===) @@ -250,7 +250,7 @@ final class RangeReplaceableCollectionTests: CollectionTestCase { let extra: [NSObject] = (0 ..< appendCount) .map { _ in NSObject() } .withUnsafeBufferPointer { buffer in - NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] + unsafe NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] } withHiddenCopies(if: isShared, of: &deque) { deque in contents.append(contentsOf: extra) diff --git a/Tests/DequeTests/RigidDequeTests.swift b/Tests/DequeTests/RigidDequeTests.swift index 183300a7..2a4018bc 100644 --- a/Tests/DequeTests/RigidDequeTests.swift +++ b/Tests/DequeTests/RigidDequeTests.swift @@ -270,7 +270,7 @@ final class RigidDequeTests: CollectionTestCase { expectEqual(deque.count, 0) expectEqual(deque.freeCapacity, capacity) if capacity == 0 { - expectNil(deque._handle._buffer.baseAddress) // No allocations + unsafe expectNil(deque._handle._buffer.baseAddress) // No allocations } } } @@ -280,7 +280,7 @@ final class RigidDequeTests: CollectionTestCase { expectEqual(deque.capacity, 0) expectEqual(deque.count, 0) expectEqual(deque.freeCapacity, 0) - expectNil(deque._handle._buffer.baseAddress) // No allocations + unsafe expectNil(deque._handle._buffer.baseAddress) // No allocations } func test_initWithClosure_Full() { @@ -356,13 +356,13 @@ final class RigidDequeTests: CollectionTestCase { let ud = UniqueDeque(copying: tracker.instances(for: 0 ..< 10)) expectEqual(ud.count, 10) expectEqual(tracker.instances, 10) - let buffer = ud._storage._handle._buffer - expectNotNil(buffer.baseAddress) + let buffer = unsafe ud._storage._handle._buffer + unsafe expectNotNil(buffer.baseAddress) let rd = RigidDeque(consuming: ud) expectEqual(rd.count, 10) expectEqual(tracker.instances, 10) - expectEqual(rd._handle._buffer.baseAddress, buffer.baseAddress) + unsafe expectEqual(rd._handle._buffer.baseAddress, buffer.baseAddress) _ = consume rd expectEqual(tracker.instances, 0) @@ -1058,7 +1058,7 @@ final class RigidDequeTests: CollectionTestCase { let extra: [NSObject] = (0 ..< c) .map { _ in NSObject() } .withUnsafeBufferPointer { buffer in - NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] + unsafe NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] } contents.insert(contentsOf: extra, at: 0) deque.prepend(copying: extra) @@ -1081,7 +1081,7 @@ final class RigidDequeTests: CollectionTestCase { let extra: [NSObject] = (0 ..< c) .map { _ in NSObject() } .withUnsafeBufferPointer { buffer in - NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] + unsafe NSArray(objects: buffer.baseAddress, count: buffer.count) as! [NSObject] } contents.append(contentsOf: extra) deque.append(copying: extra) diff --git a/Tests/DequeTests/UnsafeBufferTrimTests.swift b/Tests/DequeTests/UnsafeBufferTrimTests.swift index e55c808b..12f736d9 100644 --- a/Tests/DequeTests/UnsafeBufferTrimTests.swift +++ b/Tests/DequeTests/UnsafeBufferTrimTests.swift @@ -28,19 +28,19 @@ final class UnsafeBufferTrimTests: CollectionTestCase { let values = [10, 20, 30, 40, 50] values.withUnsafeBufferPointer { source in let storage = UnsafeMutableBufferPointer.allocate(capacity: source.count) - defer { storage.deallocate() } - _ = storage.initialize(fromContentsOf: source) - defer { storage.deinitialize() } + defer { unsafe storage.deallocate() } + _ = unsafe storage.initialize(fromContentsOf: source) + defer { unsafe storage.deinitialize() } - var rest = storage - let head = rest._trim(first: 2) - expectEqual(Array(head), [10, 20]) - expectEqual(Array(rest), [30, 40, 50]) + var rest = unsafe storage + let head = unsafe rest._trim(first: 2) + expectEqual(unsafe Array(head), [10, 20]) + expectEqual(unsafe Array(rest), [30, 40, 50]) // Trimming more than the count yields everything. - var all = storage - let everything = all._trim(first: 99) - expectEqual(Array(everything), [10, 20, 30, 40, 50]) + var all = unsafe storage + let everything = unsafe all._trim(first: 99) + expectEqual(unsafe Array(everything), [10, 20, 30, 40, 50]) expectEqual(all.count, 0) } } @@ -49,18 +49,18 @@ final class UnsafeBufferTrimTests: CollectionTestCase { let values = [10, 20, 30, 40, 50] values.withUnsafeBufferPointer { source in let storage = UnsafeMutableBufferPointer.allocate(capacity: source.count) - defer { storage.deallocate() } - _ = storage.initialize(fromContentsOf: source) - defer { storage.deinitialize() } + defer { unsafe storage.deallocate() } + _ = unsafe storage.initialize(fromContentsOf: source) + defer { unsafe storage.deinitialize() } - var rest = storage - let tail = rest._trim(last: 2) - expectEqual(Array(tail), [40, 50]) - expectEqual(Array(rest), [10, 20, 30]) + var rest = unsafe storage + let tail = unsafe rest._trim(last: 2) + expectEqual(unsafe Array(tail), [40, 50]) + expectEqual(unsafe Array(rest), [10, 20, 30]) - var all = storage - let everything = all._trim(last: 99) - expectEqual(Array(everything), [10, 20, 30, 40, 50]) + var all = unsafe storage + let everything = unsafe all._trim(last: 99) + expectEqual(unsafe Array(everything), [10, 20, 30, 40, 50]) expectEqual(all.count, 0) } } @@ -68,14 +68,14 @@ final class UnsafeBufferTrimTests: CollectionTestCase { func test_immutableBuffer_trimFirst() { let values = [10, 20, 30, 40, 50] values.withUnsafeBufferPointer { source in - var rest = source + var rest = unsafe source let head = rest._trim(first: 2) - expectEqual(Array(head), [10, 20]) - expectEqual(Array(rest), [30, 40, 50]) + expectEqual(unsafe Array(head), [10, 20]) + expectEqual(unsafe Array(rest), [30, 40, 50]) - var all = source + var all = unsafe source let everything = all._trim(first: 99) - expectEqual(Array(everything), [10, 20, 30, 40, 50]) + expectEqual(unsafe Array(everything), [10, 20, 30, 40, 50]) expectEqual(all.count, 0) } } @@ -83,14 +83,14 @@ final class UnsafeBufferTrimTests: CollectionTestCase { func test_immutableBuffer_trimLast() { let values = [10, 20, 30, 40, 50] values.withUnsafeBufferPointer { source in - var rest = source + var rest = unsafe source let tail = rest._trim(last: 2) - expectEqual(Array(tail), [40, 50]) - expectEqual(Array(rest), [10, 20, 30]) + expectEqual(unsafe Array(tail), [40, 50]) + expectEqual(unsafe Array(rest), [10, 20, 30]) - var all = source + var all = unsafe source let everything = all._trim(last: 99) - expectEqual(Array(everything), [10, 20, 30, 40, 50]) + expectEqual(unsafe Array(everything), [10, 20, 30, 40, 50]) expectEqual(all.count, 0) } } @@ -98,13 +98,13 @@ final class UnsafeBufferTrimTests: CollectionTestCase { func test_trim_zeroIsNoOp() { let values = [1, 2, 3] values.withUnsafeBufferPointer { source in - var a = source + var a = unsafe source expectEqual(a._trim(first: 0).count, 0) - expectEqual(Array(a), [1, 2, 3]) + expectEqual(unsafe Array(a), [1, 2, 3]) - var b = source + var b = unsafe source expectEqual(b._trim(last: 0).count, 0) - expectEqual(Array(b), [1, 2, 3]) + expectEqual(unsafe Array(b), [1, 2, 3]) } } } diff --git a/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift b/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift index 54cd5487..7a2bb21c 100644 --- a/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift +++ b/Tests/OrderedCollectionsTests/HashTable/HashTableTests.swift @@ -54,10 +54,10 @@ class HashTableTests: CollectionTestCase { expectEqual(s5.header.reservedScale, 0) expectTrue(s5.description.starts(with: "_HashTable(scale: 5, reservedScale: 0, bias: 0, seed: ")) expectTrue(s5.header.description.starts(with: "_HashTable.Header(scale: 5, reservedScale: 0, bias: 0, seed: ")) - s5.read { hashTable in + unsafe s5.read { hashTable in for i in 0 ..< 32 { let bucket = Bucket(offset: i) - expectNil(hashTable[bucket], "\(bucket.offset)") + expectNil(unsafe hashTable[bucket], "\(bucket.offset)") } } @@ -66,10 +66,10 @@ class HashTableTests: CollectionTestCase { expectEqual(s6.header.reservedScale, 0) expectTrue(s6.description.starts(with: "_HashTable(scale: 6, reservedScale: 0, bias: 0, seed: ")) expectTrue(s6.header.description.starts(with: "_HashTable.Header(scale: 6, reservedScale: 0, bias: 0, seed: ")) - s6.read { hashTable in + unsafe s6.read { hashTable in for i in 0 ..< 64 { let bucket = Bucket(offset: i) - expectNil(hashTable[bucket], "\(bucket.offset)") + expectNil(unsafe hashTable[bucket], "\(bucket.offset)") } } @@ -81,53 +81,53 @@ class HashTableTests: CollectionTestCase { func test_Storage_read() { let s5 = _HashTable(scale: 5) - s5.read { hashTable in - expectEqual(hashTable.scale, 5) - expectEqual(hashTable.reservedScale, 0) - expectEqual(hashTable.seed, s5.header.seed) - expectTrue(hashTable.description.starts(with: "_HashTable.UnsafeHandle(scale: 5, reservedScale: 0, bias: 0, seed: ")) + unsafe s5.read { hashTable in + expectEqual(unsafe hashTable.scale, 5) + expectEqual(unsafe hashTable.reservedScale, 0) + expectEqual(unsafe hashTable.seed, s5.header.seed) + expectTrue(unsafe hashTable.description.starts(with: "_HashTable.UnsafeHandle(scale: 5, reservedScale: 0, bias: 0, seed: ")) } let s6 = _HashTable(scale: 6) - s6.read { hashTable in - expectEqual(hashTable.scale, 6) - expectEqual(hashTable.reservedScale, 0) - expectEqual(hashTable.seed, s6.header.seed) - expectTrue(hashTable.description.starts(with: "_HashTable.UnsafeHandle(scale: 6, reservedScale: 0, bias: 0, seed: ")) + unsafe s6.read { hashTable in + expectEqual(unsafe hashTable.scale, 6) + expectEqual(unsafe hashTable.reservedScale, 0) + expectEqual(unsafe hashTable.seed, s6.header.seed) + expectTrue(unsafe hashTable.description.starts(with: "_HashTable.UnsafeHandle(scale: 6, reservedScale: 0, bias: 0, seed: ")) } } func test_counts() { let s5 = _HashTable(scale: 5) - s5.read { hashTable in - expectEqual(hashTable.bucketCount, 32) - expectEqual(hashTable.bitCount, 5 * 32) - expectEqual(hashTable.wordCount, 3) // 2.5 rounded up - expectEqual(hashTable.capacity, 24) // 0.75 * 32 + unsafe s5.read { hashTable in + expectEqual(unsafe hashTable.bucketCount, 32) + expectEqual(unsafe hashTable.bitCount, 5 * 32) + expectEqual(unsafe hashTable.wordCount, 3) // 2.5 rounded up + expectEqual(unsafe hashTable.capacity, 24) // 0.75 * 32 } let s6 = _HashTable(scale: 6) - s6.read { hashTable in - expectEqual(hashTable.bucketCount, 64) - expectEqual(hashTable.bitCount, 6 * 64) - expectEqual(hashTable.wordCount, 6) - expectEqual(hashTable.capacity, 48) // 0.75 * 64 + unsafe s6.read { hashTable in + expectEqual(unsafe hashTable.bucketCount, 64) + expectEqual(unsafe hashTable.bitCount, 6 * 64) + expectEqual(unsafe hashTable.wordCount, 6) + expectEqual(unsafe hashTable.capacity, 48) // 0.75 * 64 } let s12 = _HashTable(scale: 12) - s12.read { hashTable in - expectEqual(hashTable.bucketCount, 4096) - expectEqual(hashTable.bitCount, 12 * 4096) - expectEqual(hashTable.wordCount, 768) - expectEqual(hashTable.capacity, 3072) // 0.75 * 4096 + unsafe s12.read { hashTable in + expectEqual(unsafe hashTable.bucketCount, 4096) + expectEqual(unsafe hashTable.bitCount, 12 * 4096) + expectEqual(unsafe hashTable.wordCount, 768) + expectEqual(unsafe hashTable.capacity, 3072) // 0.75 * 4096 } } func test_bucket_after() { withEvery("scale", in: [5, 6, 12]) { scale in let storage = _HashTable(scale: scale) - storage.read { hashTable in - withEvery("offset", in: 0 ..< hashTable.bucketCount) { offset in + unsafe storage.read { hashTable in + withEvery("offset", in: unsafe 0 ..< hashTable.bucketCount) { offset in let input = Bucket(offset: offset) - let expected = Bucket(offset: offset == hashTable.bucketCount - 1 ? 0 : offset + 1) - let actual = hashTable.bucket(after: input) + let expected = Bucket(offset: unsafe offset == hashTable.bucketCount - 1 ? 0 : offset + 1) + let actual = unsafe hashTable.bucket(after: input) expectEqual(actual, expected) } } @@ -136,11 +136,11 @@ class HashTableTests: CollectionTestCase { func test_bucket_before() { withEvery("scale", in: [5, 6, 12]) { scale in let storage = _HashTable(scale: scale) - storage.read { hashTable in - withEvery("offset", in: 0 ..< hashTable.bucketCount) { offset in + unsafe storage.read { hashTable in + withEvery("offset", in: unsafe 0 ..< hashTable.bucketCount) { offset in let input = Bucket(offset: offset) - let expected = Bucket(offset: offset == 0 ? hashTable.bucketCount - 1 : offset - 1) - let actual = hashTable.bucket(before: input) + let expected = Bucket(offset: unsafe offset == 0 ? hashTable.bucketCount - 1 : offset - 1) + let actual = unsafe hashTable.bucket(before: input) expectEqual(actual, expected) } } @@ -149,10 +149,10 @@ class HashTableTests: CollectionTestCase { func test_word_after() { withEvery("scale", in: [5, 6, 12]) { scale in let storage = _HashTable(scale: scale) - storage.read { hashTable in - withEvery("input", in: 0 ..< hashTable.wordCount) { input in - let expected = (input == hashTable.wordCount - 1 ? 0 : input + 1) - let actual = hashTable.word(after: input) + unsafe storage.read { hashTable in + withEvery("input", in: unsafe 0 ..< hashTable.wordCount) { input in + let expected = unsafe (input == hashTable.wordCount - 1 ? 0 : input + 1) + let actual = unsafe hashTable.word(after: input) expectEqual(actual, expected) } } @@ -161,10 +161,10 @@ class HashTableTests: CollectionTestCase { func test_word_before() { withEvery("scale", in: [5, 6, 12]) { scale in let storage = _HashTable(scale: scale) - storage.read { hashTable in - withEvery("input", in: 0 ..< hashTable.wordCount) { input in - let expected = (input == 0 ? hashTable.wordCount - 1 : input - 1) - let actual = hashTable.word(before: input) + unsafe storage.read { hashTable in + withEvery("input", in: unsafe 0 ..< hashTable.wordCount) { input in + let expected = unsafe (input == 0 ? hashTable.wordCount - 1 : input - 1) + let actual = unsafe hashTable.word(before: input) expectEqual(actual, expected) } } @@ -173,13 +173,13 @@ class HashTableTests: CollectionTestCase { func test_coordinates_for_bucket() { withEvery("scale", in: [5, 6, 12]) { scale in let storage = _HashTable(scale: scale) - storage.read { hashTable in - withEvery("offset", in: 0 ..< hashTable.bucketCount) { offset in - let (word, bit) = hashTable.position(of: Bucket(offset: offset)) + unsafe storage.read { hashTable in + withEvery("offset", in: unsafe 0 ..< hashTable.bucketCount) { offset in + let (word, bit) = unsafe hashTable.position(of: Bucket(offset: offset)) expectGreaterThanOrEqual(bit, 0) expectGreaterThanOrEqual(word, 0) expectLessThan(bit, 64) - expectLessThan(word, hashTable.wordCount) + expectLessThan(word, unsafe hashTable.wordCount) let pos = 64 * word + bit expectEqual(pos % scale, 0) expectEqual(pos / scale, offset) @@ -191,12 +191,12 @@ class HashTableTests: CollectionTestCase { func test_bucketContents_forValue() { withEvery("scale", in: [5, 6, 12]) { scale in let storage = _HashTable(scale: scale) - storage.read { hashTable in - expectEqual(hashTable._bucketContents(for: nil), 0) - expectEqual(hashTable._value(forBucketContents: 0), nil) - withEvery("value", in: 0 ..< hashTable.bucketCount - 1) { value in - let contents = hashTable._bucketContents(for: value) - expectEqual(hashTable._value(forBucketContents: contents), value) + unsafe storage.read { hashTable in + expectEqual(unsafe hashTable._bucketContents(for: nil), 0) + expectEqual(unsafe hashTable._value(forBucketContents: 0), nil) + withEvery("value", in: unsafe 0 ..< hashTable.bucketCount - 1) { value in + let contents = unsafe hashTable._bucketContents(for: value) + expectEqual(unsafe hashTable._value(forBucketContents: contents), value) } } } @@ -207,16 +207,16 @@ class HashTableTests: CollectionTestCase { let storage = _HashTable(scale: scale) let bucketCount = 1 << scale let contents: [Int?] = Array(0 ..< bucketCount - 1) + [nil] - storage.update { hashTable in + unsafe storage.update { hashTable in for offset in 0 ..< bucketCount { let bucket = Bucket(offset: offset) - hashTable[bucket] = contents[offset] + unsafe hashTable[bucket] = contents[offset] } } - storage.read { hashTable in + unsafe storage.read { hashTable in withEvery("offset", in: 0 ..< bucketCount) { offset in let bucket = Bucket(offset: offset) - expectEqual(hashTable[bucket], contents[offset]) + expectEqual(unsafe hashTable[bucket], contents[offset]) } } } @@ -246,10 +246,10 @@ class HashTableTests: CollectionTestCase { contents.removeLast(contents.count - bucketCount) let storage = _HashTable(scale: scale) - storage.update { hashTable in + unsafe storage.update { hashTable in for offset in 0 ..< bucketCount { let bucket = Bucket(offset: offset) - hashTable[bucket] = contents[offset] + unsafe hashTable[bucket] = contents[offset] } } return (storage, contents) @@ -271,8 +271,8 @@ class HashTableTests: CollectionTestCase { chainLength: chainLength, holeLength: holeLength, startingAt: startOffset) - return try storage.update { hashTable in - try body(hashTable, contents) + return unsafe try storage.update { hashTable in + unsafe try body(hashTable, contents) } } @@ -290,35 +290,36 @@ class HashTableTests: CollectionTestCase { /// bucket. The last bucket remains unoccupied. /// /// This is useful for testing all possible bucket values. + @unsafe func withSampleHashTable( scale: Int, body: (_UnsafeHashTable, [Int?]) throws -> R ) rethrows -> R { let (table, contents) = sampleTable(scale: scale) - return try table.update { hashTable in - try body(hashTable, contents) + return unsafe try table.update { hashTable in + unsafe try body(hashTable, contents) } } func test_bucketIterator_read() { withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - withSampleHashTable(scale: scale) { hashTable, contents in + unsafe withSampleHashTable(scale: scale) { hashTable, contents in // Start an iterator at the first bucket and cycle through // all buckets twice, checking the values we see at every step. let bucket = Bucket(offset: 0) - var it = hashTable.bucketIterator(startingAt: bucket) + var it = unsafe hashTable.bucketIterator(startingAt: bucket) expectEqual(it.currentBucket, bucket) expectEqual(it.isOccupied, contents[bucket.offset] != nil) - expectEqual(it.currentValue, contents[bucket.offset]) + expectEqual(unsafe it.currentValue, contents[bucket.offset]) withEvery("iteration", in: 0 ..< 2) { iteration in - var c = hashTable.bucketCount + var c = unsafe hashTable.bucketCount if iteration == 1 { c /= 2 } // Don't let advance() trap withEvery("offset", in: 0 ..< c) { offset in let expected = contents[offset] expectEqual(it.currentBucket, Bucket(offset: offset)) expectEqual(it.isOccupied, expected != nil) - expectEqual(it.currentValue, expected) - it.advance() + expectEqual(unsafe it.currentValue, expected) + unsafe it.advance() } } } @@ -330,7 +331,7 @@ class HashTableTests: CollectionTestCase { withEvery("chainLength", in: [1, 2, 3, 4]) { chainLength in withEvery("holeLength", in: [1, 2, 3]) { holeLength in withEvery("startOffset", in: 0 ... chainLength) { startOffset in - withSampleHashTable( + unsafe withSampleHashTable( scale: scale, chainLength: chainLength, holeLength: holeLength, @@ -339,19 +340,19 @@ class HashTableTests: CollectionTestCase { // Start an iterator at the first bucket and cycle through // all buckets twice, checking the values we see at every step. let bucket = Bucket(offset: 0) - var it = hashTable.bucketIterator(startingAt: bucket) + var it = unsafe hashTable.bucketIterator(startingAt: bucket) expectEqual(it.currentBucket, bucket) expectEqual(it.isOccupied, contents[bucket.offset] != nil) - expectEqual(it.currentValue, contents[bucket.offset]) + expectEqual(unsafe it.currentValue, contents[bucket.offset]) withEvery("iteration", in: 0 ..< 2) { iteration in - var c = hashTable.bucketCount + var c = unsafe hashTable.bucketCount if iteration == 1 { c /= 2 } // Don't let advance() trap withEvery("offset", in: 0 ..< c) { offset in let expected = contents[offset] expectEqual(it.currentBucket, Bucket(offset: offset)) expectEqual(it.isOccupied, expected != nil) - expectEqual(it.currentValue, expected) - it.advance() + expectEqual(unsafe it.currentValue, expected) + unsafe it.advance() } } } @@ -363,20 +364,20 @@ class HashTableTests: CollectionTestCase { func test_bucketIterator_start_in_middle() { withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - withSampleHashTable(scale: scale) { hashTable, contents in - var expected = hashTable.bucketIterator(startingAt: Bucket(offset: 0)) + unsafe withSampleHashTable(scale: scale) { hashTable, contents in + var expected = unsafe hashTable.bucketIterator(startingAt: Bucket(offset: 0)) // Start a new iterator at every bucket and check that its initial // state matches exactly what we'd get by starting at the first // bucket and advancing step by step to the same position. - withEvery("start", in: 0 ..< hashTable.bucketCount) { start in + withEvery("start", in: unsafe 0 ..< hashTable.bucketCount) { start in let bucket = Bucket(offset: start) - let actual = hashTable.bucketIterator(startingAt: bucket) + let actual = unsafe hashTable.bucketIterator(startingAt: bucket) expectEqual(expected.currentBucket, bucket) - expectEqual(expected.currentValue, contents[start]) - expectTrue(actual.isIdentical(to: expected)) + expectEqual(unsafe expected.currentValue, contents[start]) + expectTrue(unsafe actual.isIdentical(to: expected)) - expected.advance() + unsafe expected.advance() } } } @@ -387,29 +388,29 @@ class HashTableTests: CollectionTestCase { withEvery("chainLength", in: [1, 2, 3, 4]) { chainLength in withEvery("holeLength", in: [1, 2, 3]) { holeLength in withEvery("startOffset", in: 0 ... chainLength) { startOffset in - withSampleHashTable( + unsafe withSampleHashTable( scale: scale, chainLength: chainLength, holeLength: holeLength, startingAt: startOffset ) { hashTable, contents in - var expected = hashTable.bucketIterator(startingAt: Bucket(offset: 0)) + var expected = unsafe hashTable.bucketIterator(startingAt: Bucket(offset: 0)) // Start a new iterator at every bucket and check that its initial // state is match exactly what we'd get by starting at the first // bucket and advancing step by step to the same position. - withEvery("start", in: 0 ..< hashTable.bucketCount) { start in + unsafe withEvery("start", in: 0 ..< hashTable.bucketCount) { start in let bucket = Bucket(offset: start) - let actual = hashTable.bucketIterator(startingAt: bucket) + let actual = unsafe hashTable.bucketIterator(startingAt: bucket) expectEqual(expected.currentBucket, bucket) - expectEqual(expected.currentValue, contents[start]) + expectEqual(unsafe expected.currentValue, contents[start]) expectEqual(actual.currentBucket, bucket) - expectEqual(actual.currentValue, contents[start]) + expectEqual(unsafe actual.currentValue, contents[start]) - expectTrue(actual.isIdentical(to: expected)) + expectTrue(unsafe actual.isIdentical(to: expected)) - expected.advance() + unsafe expected.advance() } } } @@ -423,26 +424,26 @@ class HashTableTests: CollectionTestCase { withEvery("chainLength", in: [1, 2, 3, 4]) { chainLength in withEvery("holeLength", in: [1, 2, 3]) { holeLength in withEvery("startOffset", in: 0 ... chainLength) { startOffset in - withSampleHashTable( + unsafe withSampleHashTable( scale: scale, chainLength: chainLength, holeLength: holeLength, startingAt: startOffset ) { hashTable, contents in var offset = 0 - var it = hashTable.bucketIterator(startingAt: Bucket(offset: offset)) + var it = unsafe hashTable.bucketIterator(startingAt: Bucket(offset: offset)) let step = 2 - for _ in 0 ..< hashTable.bucketCount { + for _ in unsafe 0 ..< hashTable.bucketCount { if let value = contents[offset] { // `advance(until:)` should not move if we're already on the right value. - it.advance(until: value) + unsafe it.advance(until: value) expectEqual(it.currentBucket.offset, offset) // `advance(until:)` should stop when it find the value we're looking for, // or at the next hole, whichever comes first. - it.advance(until: value + step) - expectTrue(it.currentValue == nil || it.currentValue == value + step) + unsafe it.advance(until: value + step) + expectTrue(unsafe it.currentValue == nil || it.currentValue == value + step) var o = offset while true { o += 1 @@ -453,13 +454,13 @@ class HashTableTests: CollectionTestCase { offset = o } else { // `advance(until:)` should not move if we're on a hole. - it.advance(until: 0) + unsafe it.advance(until: 0) expectEqual(it.currentBucket.offset, offset) // Move to the next bucket. offset += 1 if offset == contents.count { offset = 0 } - it.advance() + unsafe it.advance() } } } @@ -474,14 +475,14 @@ class HashTableTests: CollectionTestCase { withEvery("chainLength", in: [1, 2, 3, 4]) { chainLength in withEvery("holeLength", in: [1, 2, 3]) { holeLength in withEvery("startOffset", in: 0 ... chainLength) { startOffset in - withSampleHashTable( + unsafe withSampleHashTable( scale: scale, chainLength: chainLength, holeLength: holeLength, startingAt: startOffset ) { hashTable, contents in var offset = 0 - var it = hashTable.bucketIterator(startingAt: Bucket(offset: offset)) + var it = unsafe hashTable.bucketIterator(startingAt: Bucket(offset: offset)) let holeCount = contents.reduce(into: 0) { count, item in if item == nil { count += 1 } @@ -489,9 +490,9 @@ class HashTableTests: CollectionTestCase { for _ in 0 ..< holeCount * 3 / 2 { if contents[offset] != nil { - it.advanceToNextUnoccupiedBucket() + unsafe it.advanceToNextUnoccupiedBucket() - expectNil(it.currentValue) + expectNil(unsafe it.currentValue) while contents[offset] != nil { offset += 1 @@ -500,13 +501,13 @@ class HashTableTests: CollectionTestCase { expectEqual(it.currentBucket.offset, offset) } else { // `advanceToNextUnoccupiedBucket()` should not move if we're already on a hole. - it.advanceToNextUnoccupiedBucket() + unsafe it.advanceToNextUnoccupiedBucket() expectEqual(it.currentBucket.offset, offset) // Move to the next bucket. offset += 1 if offset == contents.count { offset = 0 } - it.advance() + unsafe it.advance() } } } @@ -518,24 +519,24 @@ class HashTableTests: CollectionTestCase { func test_bucketIterator_write() { withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in - withSampleHashTable(scale: scale) { hashTable, contents in + unsafe withSampleHashTable(scale: scale) { hashTable, contents in let storage = _HashTable(scale: scale) let bucketCount = 1 << scale let contents: [Int?] = Array(0 ..< bucketCount - 1) + [nil] - storage.update { hashTable in + unsafe storage.update { hashTable in // Start an iterator at the first bucket and cycle through // all buckets, updating values at every step. let bucket = Bucket(offset: 0) - var it = hashTable.bucketIterator(startingAt: bucket) + var it = unsafe hashTable.bucketIterator(startingAt: bucket) withEvery("writeOffset", in: 0 ..< contents.count) { writeOffset in - it.currentValue = contents[writeOffset] - it.advance() + unsafe it.currentValue = contents[writeOffset] + unsafe it.advance() } // Cycle through one more time, verifying that contents match. - it = hashTable.bucketIterator(startingAt: bucket) + unsafe it = hashTable.bucketIterator(startingAt: bucket) withEvery("readOffset", in: 0 ..< contents.count) { readOffset in - expectEqual(it.currentValue, contents[readOffset]) - it.advance() + expectEqual(unsafe it.currentValue, contents[readOffset]) + unsafe it.advance() } } } @@ -546,15 +547,15 @@ class HashTableTests: CollectionTestCase { withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in let (s1, contents) = sampleTable(scale: scale) let s2 = s1.copy() - s1.read { original in - s2.read { copy in - expectEqual(copy.scale, original.scale) - expectEqual(copy.reservedScale, original.reservedScale) - expectEqual(copy.seed, original.seed) - var it = copy.bucketIterator(startingAt: Bucket(offset: 0)) + unsafe s1.read { original in + unsafe s2.read { copy in + unsafe expectEqual(copy.scale, original.scale) + unsafe expectEqual(copy.reservedScale, original.reservedScale) + unsafe expectEqual(copy.seed, original.seed) + var it = unsafe copy.bucketIterator(startingAt: Bucket(offset: 0)) withEvery("offset", in: 0 ..< contents.count) { offset in - expectEqual(it.currentValue, contents[offset]) - it.advance() + unsafe expectEqual(it.currentValue, contents[offset]) + unsafe it.advance() } } } @@ -565,19 +566,19 @@ class HashTableTests: CollectionTestCase { withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in let (storage, contents) = sampleTable(scale: scale) withEvery("bias", in: [0, 1, -1, 2, -2, 30, -30]) { bias in - storage.update { hashTable in hashTable.bias = bias } - storage.read { hashTable in - var it = hashTable.bucketIterator(startingAt: Bucket(offset: 0)) + unsafe storage.update { hashTable in unsafe hashTable.bias = bias } + unsafe storage.read { hashTable in + var it = unsafe hashTable.bucketIterator(startingAt: Bucket(offset: 0)) repeat { if let v = contents[it.currentBucket.offset] { - let m = hashTable.bucketCount - 1 + let m = unsafe hashTable.bucketCount - 1 var expected = (v + bias) % m if expected < 0 { expected += m } - expectEqual(it.currentValue, expected) + unsafe expectEqual(it.currentValue, expected) } else { - expectNil(it.currentValue) + unsafe expectNil(it.currentValue) } - it.advance() + unsafe it.advance() } while it.currentBucket.offset != 0 } } @@ -587,12 +588,12 @@ class HashTableTests: CollectionTestCase { func test_rawSubscript() { withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in let (storage, contents) = sampleTable(scale: scale) - storage.read { hashTable in + unsafe storage.read { hashTable in var bucket = Bucket(offset: 0) repeat { - let expected = hashTable._bucketContents(for: contents[bucket.offset]) - expectEqual(hashTable[raw: bucket], expected) - bucket = hashTable.bucket(after: bucket) + let expected = unsafe hashTable._bucketContents(for: contents[bucket.offset]) + expectEqual(unsafe hashTable[raw: bucket], expected) + bucket = unsafe hashTable.bucket(after: bucket) } while bucket.offset != 0 } } @@ -601,11 +602,11 @@ class HashTableTests: CollectionTestCase { func test_isOccupied() { withEvery("scale", in: [5, 6, 7, 8, 12]) { scale in let (storage, contents) = sampleTable(scale: scale) - storage.read { hashTable in + unsafe storage.read { hashTable in var bucket = Bucket(offset: 0) repeat { - expectEqual(hashTable.isOccupied(bucket), contents[bucket.offset] != nil) - bucket = hashTable.bucket(after: bucket) + expectEqual(unsafe hashTable.isOccupied(bucket), contents[bucket.offset] != nil) + bucket = unsafe hashTable.bucket(after: bucket) } while bucket.offset != 0 } } diff --git a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift index 0dbf0697..18b4dcf5 100644 --- a/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedDictionary/OrderedDictionary+Values Tests.swift @@ -189,8 +189,8 @@ class OrderedDictionaryValueTests: CollectionTestCase { typealias R = [LifetimeTracked] let actual = withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d -> R in - d.values.withUnsafeBufferPointer { buffer -> R in - Array(buffer) + unsafe d.values.withUnsafeBufferPointer { buffer -> R in + unsafe Array(buffer) } } expectEqualElements(actual, reference.map { $0.value }) @@ -208,11 +208,11 @@ class OrderedDictionaryValueTests: CollectionTestCase { typealias R = [LifetimeTracked] let actual = withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d -> R in - d.values.withUnsafeMutableBufferPointer { buffer -> R in - let result = Array(buffer) + unsafe d.values.withUnsafeMutableBufferPointer { buffer -> R in + let result = unsafe Array(buffer) expectEqual(buffer.count, replacement.count, trapping: true) for i in 0 ..< replacement.count { - buffer[i] = replacement[i] + unsafe buffer[i] = replacement[i] } return result } @@ -236,11 +236,11 @@ class OrderedDictionaryValueTests: CollectionTestCase { typealias R = [LifetimeTracked] let actual = withHiddenCopies(if: isShared, of: &d, checker: { $0._checkInvariants() }) { d -> R? in - d.values.withContiguousMutableStorageIfAvailable { buffer -> R in - let result = Array(buffer) + unsafe d.values.withContiguousMutableStorageIfAvailable { buffer -> R in + let result = unsafe Array(buffer) expectEqual(buffer.count, replacement.count, trapping: true) for i in 0 ..< replacement.count { - buffer[i] = replacement[i] + unsafe buffer[i] = replacement[i] } return result } diff --git a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift index 367fc0bf..3a4c79a4 100644 --- a/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift +++ b/Tests/OrderedCollectionsTests/OrderedSet/OrderedSet Diffing Tests.swift @@ -22,13 +22,13 @@ import _CollectionsTestSupport class MeasuringHashable: Hashable { nonisolated(unsafe) static var equalityChecks = 0 static func == (lhs: MeasuringHashable, rhs: MeasuringHashable) -> Bool { - MeasuringHashable.equalityChecks += 1 + unsafe MeasuringHashable.equalityChecks += 1 return lhs._inner == rhs._inner } nonisolated(unsafe) static var hashChecks = 0 func hash(into hasher: inout Hasher) { - MeasuringHashable.hashChecks += 1 + unsafe MeasuringHashable.hashChecks += 1 _inner.hash(into: &hasher) } @@ -43,8 +43,8 @@ class MeasuringHashable: Hashable { class OrderedSetDiffingTests: CollectionTestCase { func _validatePerformance(from a: OrderedSet, to b: OrderedSet) { - MeasuringHashable.equalityChecks = 0 - MeasuringHashable.hashChecks = 0 + unsafe MeasuringHashable.equalityChecks = 0 + unsafe MeasuringHashable.hashChecks = 0 let _ = OrderedSet(a.map({MeasuringHashable($0)})).difference(from: OrderedSet(b.map({MeasuringHashable($0)}))) let n = a.count + b.count @@ -52,8 +52,8 @@ class OrderedSetDiffingTests: CollectionTestCase { /* Expect linear performance, which we can fence in testing as * "less than nlogn" since diffing generally tends to be at least n**2 */ - expectLessThan(MeasuringHashable.equalityChecks, n * n.bitWidth) - expectLessThan(MeasuringHashable.hashChecks, n * n.bitWidth) + expectLessThan(unsafe MeasuringHashable.equalityChecks, n * n.bitWidth) + expectLessThan(unsafe MeasuringHashable.hashChecks, n * n.bitWidth) } func _validate(from a: Array, to b: Array, mutations: Int? = nil) { diff --git a/Tests/RopeModuleTests/TestBigString.swift b/Tests/RopeModuleTests/TestBigString.swift index dec41cd5..e2135fae 100644 --- a/Tests/RopeModuleTests/TestBigString.swift +++ b/Tests/RopeModuleTests/TestBigString.swift @@ -11,7 +11,7 @@ // //===----------------------------------------------------------------------===// -@preconcurrency import XCTest +@unsafe @preconcurrency import XCTest #if COLLECTIONS_SINGLE_MODULE import Collections #else @@ -25,8 +25,8 @@ class TestBigString: CollectionTestCase { override class func setUp() { // Turn off output buffering. - setbuf(stdout, nil) - setbuf(stderr, nil) + unsafe setbuf(stdout, nil) + unsafe setbuf(stderr, nil) super.setUp() } diff --git a/Tests/SortedCollectionsTests/BTree/Node Utils.swift b/Tests/SortedCollectionsTests/BTree/Node Utils.swift index 668ba281..a4269711 100644 --- a/Tests/SortedCollectionsTests/BTree/Node Utils.swift +++ b/Tests/SortedCollectionsTests/BTree/Node Utils.swift @@ -42,20 +42,20 @@ struct NodeTemplate { } func matches(_ node: _Node) -> Bool { - return node.read { handle in - if self.keys.count != handle.elementCount { return false } + return unsafe node.read { handle in + if unsafe self.keys.count != handle.elementCount { return false } if (self.children == nil) != handle.isLeaf { return false } if let children = self.children { for (i, child) in children.enumerated() { - if !child.matches(handle[childAt: i]) { + if unsafe !child.matches(handle[childAt: i]) { return false } } } for (i, key) in self.keys.enumerated() { - if handle[keyAt: i] != key { + if unsafe handle[keyAt: i] != key { return false } } diff --git a/Tests/SortedCollectionsTests/BTree/Node+Balancing Tests.swift b/Tests/SortedCollectionsTests/BTree/Node+Balancing Tests.swift index 442b9ed0..532778d1 100644 --- a/Tests/SortedCollectionsTests/BTree/Node+Balancing Tests.swift +++ b/Tests/SortedCollectionsTests/BTree/Node+Balancing Tests.swift @@ -79,7 +79,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.rotateRight(atSlot: 0) } + unsafe node.update { unsafe $0.rotateRight(atSlot: 0) } expectTrue( tree { @@ -106,7 +106,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.rotateRight(atSlot: 0) } + unsafe node.update { unsafe $0.rotateRight(atSlot: 0) } expectTrue( tree { @@ -134,7 +134,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.rotateLeft(atSlot: 0) } + unsafe node.update { unsafe $0.rotateLeft(atSlot: 0) } expectTrue( tree { @@ -161,7 +161,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.rotateLeft(atSlot: 0) } + unsafe node.update { unsafe $0.rotateLeft(atSlot: 0) } expectTrue( tree { @@ -180,7 +180,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.rotateLeft(atSlot: 0) } + unsafe node.update { unsafe $0.rotateLeft(atSlot: 0) } expectTrue( tree { @@ -206,7 +206,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.collapse(atSlot: 0) } + unsafe node.update { unsafe $0.collapse(atSlot: 0) } expectTrue( tree { @@ -231,7 +231,7 @@ final class NodeBalancingTests: CollectionTestCase { } var node = t.toNode(ofCapacity: 2) - node.update { $0.collapse(atSlot: 0) } + unsafe node.update { unsafe $0.collapse(atSlot: 0) } expectTrue( tree { diff --git a/Tests/SortedCollectionsTests/BTree/NodeTests.swift b/Tests/SortedCollectionsTests/BTree/NodeTests.swift index c5072166..0a631315 100644 --- a/Tests/SortedCollectionsTests/BTree/NodeTests.swift +++ b/Tests/SortedCollectionsTests/BTree/NodeTests.swift @@ -98,17 +98,17 @@ final class NodeTests: CollectionTestCase { let newKey = position * 2 + 1 - let splinter: _Node.Splinter? = node.update { handle in - let index = handle.endSlot(forKey: newKey) - return handle.insertElement((newKey, newKey * 2), withRightChild: nil, atSlot: index) + let splinter: _Node.Splinter? = unsafe node.update { handle in + let index = unsafe handle.endSlot(forKey: newKey) + return unsafe handle.insertElement((newKey, newKey * 2), withRightChild: nil, atSlot: index) } insertSortedValue(newKey, into: &array) expectNil(splinter) - node.read { handle in - let keys = UnsafeBufferPointer(start: handle.keys, count: handle.elementCount) - expectEqualElements(keys, array) - expectEqual(handle.subtreeCount, count + 1) + unsafe node.read { handle in + let keys = unsafe UnsafeBufferPointer(start: handle.keys, count: handle.elementCount) + unsafe expectEqualElements(keys, array) + unsafe expectEqual(handle.subtreeCount, count + 1) } } } @@ -120,9 +120,9 @@ final class NodeTests: CollectionTestCase { withEvery("keys", in: 0...capacity) { keys in withEvery("duplicates", in: 0...keys) { duplicates in withEveryNode(ofCapacity: capacity, keys: keys, duplicates: duplicates) { node, array, duplicatedKey in - node.read { handle in + unsafe node.read { handle in expectEqual( - handle.startSlot(forKey: duplicatedKey), + unsafe handle.startSlot(forKey: duplicatedKey), findFirstIndexOf(duplicatedKey, in: array) ) } @@ -137,8 +137,8 @@ final class NodeTests: CollectionTestCase { withEvery("keys", in: 0...capacity) { keys in withEvery("duplicates", in: 0...keys) { duplicates in withEveryNode(ofCapacity: capacity, keys: keys, duplicates: duplicates) { node, array, duplicatedKey in - node.read { handle in - expectEqual( + unsafe node.read { handle in + unsafe expectEqual( handle.endSlot(forKey: duplicatedKey), findLastIndexOf(duplicatedKey, in: array) ) diff --git a/Tests/TrailingElementsTests/TrailingElementsTests.swift b/Tests/TrailingElementsTests/TrailingElementsTests.swift index 9546468c..9c12fe3f 100644 --- a/Tests/TrailingElementsTests/TrailingElementsTests.swift +++ b/Tests/TrailingElementsTests/TrailingElementsTests.swift @@ -33,7 +33,7 @@ extension Coordinates: TrailingElements { var trailingCount: Int { numCoordinates } } -struct OneByteWithPointers: TrailingElements { +struct OneByteWithPointers: @unsafe TrailingElements { var byte: UInt8 init(count: Int) { @@ -44,7 +44,7 @@ struct OneByteWithPointers: TrailingElements { var trailingCount: Int { Int(byte) } } -struct ManyBytesWithPointers: TrailingElements { +struct ManyBytesWithPointers: @unsafe TrailingElements { var bytes: ( UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, @@ -108,78 +108,78 @@ struct TrailingElementsTests { @Test(arguments: 0 ... 10) func underalignedByteOnHeap(count: Int) { - var pointers = TrailingArray( + var pointers = unsafe TrailingArray( header: OneByteWithPointers(count: count) ) { outputSpan in for i in 0...stride) + unsafe pointers.withUnsafeMutablePointers { headerPtr, elementsPtr in + let p1 = unsafe headerPtr.advanced(by: MemoryLayout.stride) let p2 = elementsPtr.baseAddress - #expect(UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) + #expect(unsafe UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) } } @Test(arguments: 0 ... 10) func underalignedByteOnStack(count: Int) { - TrailingArray.withTemporaryValue(header: OneByteWithPointers(count: count)) { outputSpan in + unsafe TrailingArray.withTemporaryValue(header: OneByteWithPointers(count: count)) { outputSpan in for i in 0...stride) + unsafe pointers.withUnsafeMutablePointers { headerPtr, elementsPtr in + let p1 = unsafe headerPtr.advanced(by: MemoryLayout.stride) let p2 = elementsPtr.baseAddress - #expect(UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) + #expect(unsafe UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) } } } @Test(arguments: 0 ... 10) func underalignedBytesOnHeap(count: Int) { - var pointers = TrailingArray(header: ManyBytesWithPointers(count: count)) { outputSpan in + var pointers = unsafe TrailingArray(header: ManyBytesWithPointers(count: count)) { outputSpan in for i in 0...stride) + unsafe pointers.withUnsafeMutablePointers { headerPtr, elementsPtr in + let p1 = unsafe headerPtr.advanced(by: MemoryLayout.stride) let p2 = elementsPtr.baseAddress - #expect(UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) + #expect(unsafe UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) } } @Test(arguments: 0 ... 10) func underalignedBytesOnStack(count: Int) { - TrailingArray.withTemporaryValue(header: ManyBytesWithPointers(count: count)) { outputSpan in + unsafe TrailingArray.withTemporaryValue(header: ManyBytesWithPointers(count: count)) { outputSpan in for i in 0...stride) + unsafe pointers.withUnsafeMutablePointers { headerPtr, elementsPtr in + let p1 = unsafe headerPtr.advanced(by: MemoryLayout.stride) let p2 = elementsPtr.baseAddress - #expect(UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) + #expect(unsafe UnsafeMutableRawPointer(p1) == UnsafeMutableRawPointer(p2)) } } } diff --git a/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift b/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift index ca58b228..c1ff5a47 100644 --- a/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift +++ b/Tests/_CollectionsTestSupport/AssertionContexts/TestContext.swift @@ -30,7 +30,7 @@ public final class TestContext { extension TestContext { public static var current: TestContext { - guard let current = _current else { + guard let current = unsafe _current else { fatalError("There is no current test context") } return current @@ -47,13 +47,13 @@ extension TestContext { } public static func push(_ context: TestContext) { - precondition(_current == nil, "Cannot nest test contexts") - _current = context + precondition(unsafe _current == nil, "Cannot nest test contexts") + unsafe _current = context } public static func pop(_ context: TestContext) { - precondition(_current === context, "Cannot pop mismatching context") - _current = nil + precondition(unsafe _current === context, "Cannot pop mismatching context") + unsafe _current = nil } } @@ -79,7 +79,7 @@ extension TestContext { } public static func ==(left: Self, right: Self) -> Bool { - left.label == right.label + unsafe left.label == right.label && left.file.utf8Start == right.file.utf8Start && left.file.utf8CodeUnitCount == right.file.utf8CodeUnitCount && left.line == right.line @@ -87,7 +87,7 @@ extension TestContext { public func hash(into hasher: inout Hasher) { hasher.combine(label) - hasher.combine(file.utf8Start) + unsafe hasher.combine(file.utf8Start) hasher.combine(file.utf8CodeUnitCount) hasher.combine(line) } @@ -205,7 +205,7 @@ extension TestContext { } public static func incrementFailureCount() -> Bool { - guard let context = _current else { return true } + guard let context = unsafe _current else { return true } let result = context._failureCount < maximumFailureCount context._failureCount += 1 return result @@ -215,7 +215,7 @@ extension TestContext { _ message: String = "", title: String = "Trace" ) -> String { - guard let context = _current else { return message } + guard let context = unsafe _current else { return message } return context.currentTrace(message, title: title) } diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift index 00144c92..587c3012 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckCollection.swift @@ -31,10 +31,10 @@ extension Sequence { func _contentsByCopyContents(_ count: Int? = nil) -> [Element] { var it: Iterator? - var result = Array( + var result = unsafe Array( unsafeUninitializedCapacity: count ?? self.underestimatedCount ) { buffer, count in - (it, count) = self._copyContents(initializing: buffer) + (it, count) = unsafe self._copyContents(initializing: buffer) } while let next = it!.next() { result.append(next) diff --git a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift index c331c766..4ad5289d 100644 --- a/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift +++ b/Tests/_CollectionsTestSupport/ConformanceCheckers/CheckSequence.swift @@ -56,7 +56,7 @@ public func checkSequence( do { let seq = sequenceGenerator() let r: Int? = seq.withContiguousStorageIfAvailable { buffer in - expectEquivalentElements(buffer, expectedContents, by: areEquivalent) + unsafe expectEquivalentElements(buffer, expectedContents, by: areEquivalent) return 42 } expectTrue(r == 42 || r == nil) @@ -78,10 +78,10 @@ public func checkSequence( let seq = sequenceGenerator() let underestimatedCount = seq.underestimatedCount var state: (it: S.Iterator, count: Int)! - var array = Array( + var array = unsafe Array( unsafeUninitializedCapacity: underestimatedCount ) { buffer, count in - state = seq._copyContents(initializing: buffer) + state = unsafe seq._copyContents(initializing: buffer) count = state.count } expectEqual(state.count, underestimatedCount) diff --git a/Tests/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift b/Tests/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift index bfb27c67..cd7dfd72 100644 --- a/Tests/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift +++ b/Tests/_CollectionsTestSupport/Utilities/IndexRangeCollection.swift @@ -84,7 +84,7 @@ extension IndexRangeCollection: RandomAccessCollection { public subscript(position: Index) -> Range { precondition(position._end <= _bounds.count) - return Range( + return unsafe Range( uncheckedBounds: ( lower: _bounds.lowerBound.advanced(by: position._start), upper: _bounds.lowerBound.advanced(by: position._end))) diff --git a/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift b/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift index 89e6a4f3..47c693c6 100644 --- a/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift +++ b/Tests/_CollectionsTestSupport/Utilities/TestPrintable.swift @@ -67,13 +67,13 @@ internal func _bufferDescription( extension UnsafeRawBufferPointer: TestPrintable { public var testDescription: String { - _bufferDescription( + unsafe _bufferDescription( "UnsafeRawBufferPointer", start: baseAddress, count: count) } } extension UnsafeMutableRawBufferPointer: TestPrintable { public var testDescription: String { - _bufferDescription( + unsafe _bufferDescription( "UnsafeMutableRawBufferPointer", start: baseAddress, count: count) } } @@ -81,14 +81,14 @@ extension UnsafeBufferPointer: TestPrintable where Element: ~Copyable { public var testDescription: String { - _bufferDescription("UnsafeBufferPointer", start: baseAddress, count: count) + unsafe _bufferDescription("UnsafeBufferPointer", start: baseAddress, count: count) } } extension UnsafeMutableBufferPointer: TestPrintable where Element: ~Copyable { public var testDescription: String { - _bufferDescription( + unsafe _bufferDescription( "UnsafeMutableBufferPointer", start: baseAddress, count: count) } } @@ -97,7 +97,7 @@ where Element: ~Copyable extension Span: TestPrintable where Element: ~Copyable { public var testDescription: String { self.withUnsafeBufferPointer { buffer in - _bufferDescription("Span", start: buffer.baseAddress, count: buffer.count) + unsafe _bufferDescription("Span", start: buffer.baseAddress, count: buffer.count) } } } @@ -105,7 +105,7 @@ extension Span: TestPrintable where Element: ~Copyable { extension MutableSpan: TestPrintable where Element: ~Copyable { public var testDescription: String { self.withUnsafeBufferPointer { buffer in - _bufferDescription("MutableSpan", start: buffer.baseAddress, count: buffer.count) + unsafe _bufferDescription("MutableSpan", start: buffer.baseAddress, count: buffer.count) } } } @@ -116,7 +116,7 @@ extension OutputSpan: TestPrintable where Element: ~Copyable { return self.span.withUnsafeBufferPointer { buffer in """ OutputSpan(\ - start: \(buffer.baseAddress?._description ?? "nil"), \ + start: \(unsafe buffer.baseAddress?._description ?? "nil"), \ capacity: \(capacity), \ count: \(buffer.count)) """ @@ -132,7 +132,7 @@ extension InputSpan: TestPrintable where Element: ~Copyable { return self.span.withUnsafeBufferPointer { buffer in """ InputSpan(\ - start: \(buffer.baseAddress?._description ?? "nil"), \ + start: \(unsafe buffer.baseAddress?._description ?? "nil"), \ capacity: \(capacity), \ count: \(buffer.count)) """