diff --git a/Sources/BasicContainers/HashTable/_HTable+Bitmap.swift b/Sources/BasicContainers/HashTable/_HTable+Bitmap.swift index e1a0e9f6..b6f96ae9 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Bitmap.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Bitmap.swift @@ -18,6 +18,7 @@ import InternalCollectionsUtilities extension _HTable { @usableFromInline @frozen + @safe package struct Bitmap: ~Copyable, ~Escapable { @usableFromInline package typealias Bucket = _HTable.Bucket @@ -28,7 +29,7 @@ extension _HTable { @_alwaysEmitIntoClient @_lifetime(borrow table) package init(table: borrowing _HTable) { - self._words = .init(start: table._bitmap, count: table.wordCount) + unsafe self._words = .init(start: table._bitmap, count: table.wordCount) } } } @@ -39,42 +40,43 @@ extension _HTable.Bitmap { @_transparent @inlinable + @safe package func isValid(_ bucket: Bucket) -> Bool { - bucket.word < _words.count + unsafe bucket.word < _words.count } @_transparent @inlinable package func isOccupied(_ bucket: Bucket) -> Bool { assert(isValid(bucket)) - return _words[bucket.word].contains(bucket.bit) + return unsafe _words[bucket.word].contains(bucket.bit) } @_transparent @inlinable package func setOccupied(_ bucket: Bucket) { assert(isValid(bucket)) - _words[bucket.word].set(bucket.bit) + unsafe _words[bucket.word].set(bucket.bit) } @_transparent @inlinable package func clearOccupied(_ bucket: Bucket) { assert(isValid(bucket)) - _words[bucket.word].clear(bucket.bit) + unsafe _words[bucket.word].clear(bucket.bit) } @_transparent @inlinable package func clearAll() { - _words.update(repeating: .empty) + unsafe _words.update(repeating: .empty) } @_alwaysEmitIntoClient package func occupiedCount() -> Int { var c = 0 - for i in 0 ..< _words.count { - c += _words[i].count + for i in unsafe 0 ..< _words.count { + unsafe c += _words[i].count } return c } @@ -84,7 +86,7 @@ extension _HTable.Bitmap { guard isValid(start) else { return nil } var word = start.word - var bits = _words[word] + var bits = unsafe _words[word] bits.removeAll(upTo: start.bit) while true { @@ -92,10 +94,10 @@ extension _HTable.Bitmap { return Bucket(word: word, bit: bit) } word &+= 1 - if word >= _words.count { + if unsafe word >= _words.count { return nil } - bits = _words[word] + unsafe bits = _words[word] } } @@ -103,16 +105,16 @@ extension _HTable.Bitmap { package func firstOccupiedBucket( from start: Bucket, limit: Bucket ) -> Bucket { - assert(isValid(start) && start <= limit && limit.word <= _words.count) + assert(unsafe isValid(start) && start <= limit && limit.word <= _words.count) var word = start.word - var bits = _words[word] + var bits = unsafe _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 + unsafe bits = word < _words.count ? _words[word] : .empty } bits.removeAll(from: limit.bit) if let bit = bits.firstMember { @@ -127,7 +129,7 @@ extension _HTable.Bitmap { package func collisionChainEnd(from start: Bucket) -> Bucket { assert(isOccupied(start)) var word = start.word - var bits = _words[word] + var bits = unsafe _words[word] bits.insertAll(upTo: start.bit) var wrapped = false while true { @@ -136,12 +138,12 @@ extension _HTable.Bitmap { return Bucket(word: word, bit: bit) } word &+= 1 - if word >= _words.count { + if unsafe word >= _words.count { precondition(!wrapped, "Corrupt hash table") wrapped = true word = 0 } - bits = _words[word] + unsafe bits = _words[word] } } @@ -153,9 +155,9 @@ extension _HTable.Bitmap { ) -> Bucket { assert(isValid(start)) var word = start.word - var bits = _words[word] + var bits = unsafe _words[word] bits.insertAll(upTo: start.bit) - var remainder = Swift.min( + var remainder = unsafe Swift.min( UInt(bitPattern: maxCount) &+ start.bit, UInt(bitPattern: (_words.count &- start.word) &* Word.capacity)) while true { @@ -169,8 +171,8 @@ extension _HTable.Bitmap { word &+= 1 remainder &-= Word._capacity guard remainder > 0 else { break } - assert(word < _words.count) - bits = _words[word] + assert(unsafe word < _words.count) + unsafe bits = _words[word] } return Bucket(word: word, bit: remainder) } @@ -187,7 +189,7 @@ extension _HTable.Bitmap { let end = self._nextOccupiedChunkEnd( from: bucket, maxCount: Swift.min(maxCount, limit.offset &- bucket.offset)) - let result = Range(uncheckedBounds: (bucket, end)) + let result = unsafe Range(uncheckedBounds: (bucket, end)) if isValid(end), !isOccupied(end) { bucket = firstOccupiedBucket(from: end, limit: limit) } else { diff --git a/Sources/BasicContainers/HashTable/_HTable+Bucket.swift b/Sources/BasicContainers/HashTable/_HTable+Bucket.swift index 076f0e4c..ee96eed0 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Bucket.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Bucket.swift @@ -21,6 +21,7 @@ extension _HTable { /// to a function that expects a word index, or vice versa. @usableFromInline @frozen + @safe package struct Bucket { @usableFromInline internal typealias Word = _HTable.Word @@ -127,11 +128,11 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { package subscript(bucket: _HTable.Bucket) -> Element { @_transparent unsafeAddress { - return .init(_ptr(at: bucket.offset)) + return unsafe .init(_ptr(at: bucket.offset)) } @_transparent nonmutating unsafeMutableAddress { - return _ptr(at: bucket.offset) + return unsafe _ptr(at: bucket.offset) } } @@ -140,7 +141,7 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { package func _ptr( at bucket: _HTable.Bucket ) -> UnsafeMutablePointer { - _ptr(at: bucket.offset) + unsafe _ptr(at: bucket.offset) } @_alwaysEmitIntoClient @@ -149,13 +150,13 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { at bucket: _HTable.Bucket, to value: consuming Element ) { - initializeElement(at: bucket.offset, to: value) + unsafe initializeElement(at: bucket.offset, to: value) } @_alwaysEmitIntoClient @_transparent package func _extracting(_ buckets: Range<_HTable.Bucket>) -> Self { - _extracting( + unsafe _extracting( uncheckedFrom: buckets.lowerBound.offset, to: buckets.upperBound.offset) } @@ -166,7 +167,7 @@ extension Range where Bound == _HTable.Bucket { package var _offsets: Range { @_transparent get { - .init(uncheckedBounds: (lowerBound.offset, upperBound.offset)) + unsafe .init(uncheckedBounds: (lowerBound.offset, upperBound.offset)) } } } diff --git a/Sources/BasicContainers/HashTable/_HTable+Insert.swift b/Sources/BasicContainers/HashTable/_HTable+Insert.swift index bda1d380..84c4210c 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Insert.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Insert.swift @@ -17,13 +17,13 @@ extension _HTable { swapper: (Bucket) -> Void, ) -> Bucket { assert(isSmall) - if _count > 0 { + if self.count > 0 { // Scramble order by swapping the new item in the middle of the table. - swapper(Bucket(offset: _count / 2)) + swapper(Bucket(offset: self.count / 2)) } - let r = Bucket(offset: _count) - _count &+= 1 - _maxProbeLength = _count + let r = Bucket(offset: self.count) + unsafe _count &+= 1 + _maxProbeLength = self.count return r } @@ -75,7 +75,7 @@ extension _HTable { probeLength &+= 1 } bitmap.setOccupied(b) - _count &+= 1 + unsafe _count &+= 1 if probeLength > _maxProbeLength { _maxProbeLength = probeLength } diff --git a/Sources/BasicContainers/HashTable/_HTable+Iteration.swift b/Sources/BasicContainers/HashTable/_HTable+Iteration.swift index 8636adf8..ae9fa90c 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Iteration.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Iteration.swift @@ -37,6 +37,7 @@ extension _HTable { /// iterator values outside the closure call that produced the original /// hash table. @usableFromInline + @safe package struct BucketIterator: ~Escapable { @usableFromInline package typealias Bucket = _HTable.Bucket @@ -72,17 +73,17 @@ extension _HTable { assert(table.isValid(bucket) || bucket == table.endBucket) assert(table.endBucket.bit == 0 || table.endBucket.word == 0) // We rely on this throughout the code below self._bucket = bucket - if let bitmap = table._bitmap { - self._words = .init(bitmap) + if let bitmap = unsafe table._bitmap { + unsafe self._words = .init(bitmap) self._endBucket = table.endBucket - self._nextBits = bitmap[_bucket.word].shiftedDown(by: _bucket.bit) + self._nextBits = unsafe bitmap[_bucket.word].shiftedDown(by: _bucket.bit) if table.endBucket._offset < Word.capacity { self._nextBitCount = UInt8(table.endBucket.bit &- _bucket.bit) } else { self._nextBitCount = UInt8(Word._capacity &- _bucket.bit) } } else { - self._words = nil + unsafe self._words = nil self._endBucket = Bucket(offset: table.count) // Note: not capacity! self._nextBits = .empty self._nextBitCount = 0 @@ -108,7 +109,7 @@ extension _HTable.BucketIterator { @_transparent package var isOccupied: Bool { assert(!isAtEnd) - if _words == nil { return true } + if unsafe _words == nil { return true } return _nextBits.contains(0) } @@ -117,8 +118,8 @@ extension _HTable.BucketIterator { package mutating func restart() { _wrapped = true _bucket._offset = 0 - if let words = _words { - _nextBits = words[_bucket.word] + if let words = unsafe _words { + _nextBits = unsafe words[_bucket.word] _nextBitCount = UInt8(Swift.min(Word._capacity, _endBucket._offset)) } } @@ -148,8 +149,8 @@ extension _HTable.BucketIterator { advanceToEnd() return false } - if let words = _words{ - _nextBits = words[_bucket.word] + if let words = unsafe _words { + _nextBits = unsafe words[_bucket.word] _nextBitCount = UInt8(Word._capacity) } return true @@ -161,8 +162,8 @@ extension _HTable.BucketIterator { _bucket.advanceToNextWord() if isAtEnd { _wrap() - } else if let words = _words { - _nextBits = words[_bucket.word] + } else if let words = unsafe _words { + _nextBits = unsafe words[_bucket.word] _nextBitCount = UInt8(Word._capacity) } } @@ -177,14 +178,14 @@ extension _HTable.BucketIterator { advanceToEnd() return false } - guard let words = _words else { return true } + guard let words = unsafe _words else { return true } assert(_nextBitCount > 0) _nextBitCount &-= 1 if _nextBitCount > 0 { _nextBits = _nextBits.shiftedDown(by: 1) } else { assert(_bucket.bit == 0) - _nextBits = words[_bucket.word] + _nextBits = unsafe words[_bucket.word] _nextBitCount = UInt8(Word._capacity) } return true @@ -198,13 +199,13 @@ extension _HTable.BucketIterator { _wrap() return } - guard let words = _words else { return } + guard let words = unsafe _words else { return } assert(_nextBitCount > 0) _nextBitCount &-= 1 if _nextBitCount > 0 { _nextBits = _nextBits.shiftedDown(by: 1) } else { - _nextBits = words[_bucket.word] + _nextBits = unsafe words[_bucket.word] _nextBitCount = UInt8(Word._capacity) } } @@ -215,7 +216,7 @@ extension _HTable.BucketIterator { @_lifetime(self: copy self) package mutating func advanceToOccupied() -> Bool { if isAtEnd { return false } - if _words == nil { + if unsafe _words == nil { return true } while true { @@ -239,7 +240,7 @@ extension _HTable.BucketIterator { ) -> Bool { var remainder = UInt(bitPattern: maxCount) if isAtEnd { return false } - if _words == nil { + if unsafe _words == nil { let delta = Swift.min(_endBucket._offset &- _bucket._offset, remainder) _bucket._offset &+= delta return true @@ -269,7 +270,7 @@ extension _HTable.BucketIterator { @usableFromInline @_lifetime(self: copy self) package mutating func wrapToOccupied() { - if _words == nil { + if unsafe _words == nil { wrapToNextBit() return } @@ -290,7 +291,7 @@ extension _HTable.BucketIterator { @_lifetime(self: copy self) package mutating func advanceToUnoccupied() -> Bool { assert(!isAtEnd) - if _words == nil { + if unsafe _words == nil { _bucket = _endBucket return false } @@ -317,7 +318,7 @@ extension _HTable.BucketIterator { assert(maxCount > 0) assert(!isAtEnd) var remainder = UInt(bitPattern: maxCount) - if _words == nil { + if unsafe _words == nil { let delta = Swift.min(_endBucket._offset &- _bucket._offset, remainder) _bucket._offset &+= delta return false @@ -348,7 +349,7 @@ extension _HTable.BucketIterator { @usableFromInline @_lifetime(self: copy self) package mutating func wrapToUnoccupied() { - if _words == nil { + if unsafe _words == nil { _bucket = _endBucket return } @@ -374,7 +375,7 @@ extension _HTable.BucketIterator { let start = self.currentBucket self.advanceToUnoccupied(maxCount: maxCount) let end = self.currentBucket - return Range(uncheckedBounds: (start, end)) + return unsafe Range(uncheckedBounds: (start, end)) } @usableFromInline @@ -388,6 +389,6 @@ extension _HTable.BucketIterator { let start = self.currentBucket self.advanceToOccupied(maxCount: maxCount) let end = self.currentBucket - return Range(uncheckedBounds: (start, end)) + return unsafe Range(uncheckedBounds: (start, end)) } } diff --git a/Sources/BasicContainers/HashTable/_HTable+Removal.swift b/Sources/BasicContainers/HashTable/_HTable+Removal.swift index ac604e0c..2e8db228 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Removal.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Removal.swift @@ -17,11 +17,12 @@ extension _HTable { /// is created, the table remains in an inconsistent state until one of /// `resolveHole` or `finalizeHole` is called on the same bucket. @usableFromInline + @unsafe package mutating func createHole( at bucket: Bucket ) { assert(isOccupied(bucket)) - _count &-= 1 + unsafe _count &-= 1 } /// Restore hash table invariants after a hole was created by `createHole`. @@ -29,13 +30,14 @@ extension _HTable { /// reach the end of the affected chain of occupied buckets. @usableFromInline @discardableResult + @unsafe package mutating func resolveHole( at bucket: Bucket, hashGenerator: (Bucket) -> Int, mover: (Bucket, Bucket) -> Void, ) -> Bucket { if isSmall { - return finalizeHole(at: bucket, mover: mover) + return unsafe finalizeHole(at: bucket, mover: mover) } assert(isOccupied(bucket)) @@ -88,8 +90,8 @@ extension _HTable { // incremental updates here (like the original thesis suggests), but it's // unclear if the benefits of that would outweigh the costs.) // (FIXME: Try it and see.) - if _maxProbeLength > _count { - _maxProbeLength = _count + if _maxProbeLength > self.count { + _maxProbeLength = self.count } return hole @@ -102,14 +104,15 @@ extension _HTable { /// does enough to allow the hash table to get resized. @discardableResult @usableFromInline + @unsafe package mutating func finalizeHole( at bucket: Bucket, mover: (Bucket, Bucket) -> Void, ) -> Bucket { assert(isValid(bucket)) if isSmall { - let last = Bucket(offset: _count) // Note: _count was decreased by createHole - _maxProbeLength = _count + let last = Bucket(offset: self.count) // Note: _count was decreased by createHole + _maxProbeLength = self.count guard bucket < last else { return bucket } mover(last, bucket) return last diff --git a/Sources/BasicContainers/HashTable/_HTable+Resizing.swift b/Sources/BasicContainers/HashTable/_HTable+Resizing.swift index 2e211be8..d31674e3 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Resizing.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Resizing.swift @@ -25,7 +25,7 @@ extension _HTable { // Let's reverse the order of members, to emphasize that this is not an // ordered container. let c = source.count - self._count = c + unsafe self._count = c self._maxProbeLength = c var dst = Bucket(offset: c) var it = source.makeBucketIterator() diff --git a/Sources/BasicContainers/HashTable/_HTable+Sizing.swift b/Sources/BasicContainers/HashTable/_HTable+Sizing.swift index 6afede12..ed8b65fc 100644 --- a/Sources/BasicContainers/HashTable/_HTable+Sizing.swift +++ b/Sources/BasicContainers/HashTable/_HTable+Sizing.swift @@ -18,6 +18,7 @@ import InternalCollectionsUtilities extension _HTable { /// The minimum hash table scale. @_alwaysEmitIntoClient + @safe package static var minimumScale: UInt8 { @_effects(readnone) @_transparent @@ -28,6 +29,7 @@ extension _HTable { /// The maximum hash table scale. @_alwaysEmitIntoClient + @safe package static var maximumScale: UInt8 { @_effects(readnone) @_transparent @@ -38,6 +40,7 @@ extension _HTable { /// The maximum number of items for which we do not create a hash table. @usableFromInline + @safe package static var maximumUnhashedCount: Int { @_effects(readnone) get { @@ -47,6 +50,7 @@ extension _HTable { @inlinable @inline(__always) + @safe package static func wordCount(forScale scale: UInt8) -> Int { guard scale > 0 else { return 0 } let shift = Swift.max(UInt(scale), Word.wordShift) - Word.wordShift @@ -74,24 +78,29 @@ extension _HTable { /// The numerator of the maximum hash table load factor. @_transparent + @safe internal static var _maxLFNum: UInt { 7 } /// The denominator of the maximum hash table load factor. @_transparent + @safe internal static var _maxLFDenom: UInt { 8 } /// The numerator of the minimum hash table load factor. @_transparent + @safe internal static var _minLFNum: UInt { 1 } /// The denominator of minimum hash table load factor. @_alwaysEmitIntoClient @_transparent + @safe internal static var _minLFDenom: UInt { 8 } /// The minimum number of items that can be held in a hash table of the given scale. @usableFromInline @_effects(readnone) + @safe package static func minimumCapacity(forScale scale: UInt8) -> Int { guard scale >= minimumScale else { return 0 } precondition(scale <= maximumScale) @@ -102,6 +111,7 @@ extension _HTable { /// The maximum number of items that can be held in a hash table of the given scale. @usableFromInline @_effects(readnone) + @safe package static func maximumCapacity(forScale scale: UInt8) -> Int { let scale = Swift.max(scale, minimumScale &- 1) let bucketCount: UInt = 1 &<< scale @@ -112,6 +122,7 @@ extension _HTable { /// The minimum hash table scale that can hold the specified number of elements. @usableFromInline @_effects(readnone) + @safe package static func minimumScale(forCapacity capacity: Int) -> UInt8 { guard capacity > maximumUnhashedCount else { return 0 } let capacity = UInt(truncatingIfNeeded: Swift.max(capacity, 1)) @@ -132,6 +143,7 @@ extension _HTable { @usableFromInline @_effects(readnone) + @safe package static func dynamicStorageParameters( minimumCapacity: Int ) -> (scale: UInt8, capacity: Int) { diff --git a/Sources/BasicContainers/HashTable/_HTable.swift b/Sources/BasicContainers/HashTable/_HTable.swift index acf98f42..172faf96 100644 --- a/Sources/BasicContainers/HashTable/_HTable.swift +++ b/Sources/BasicContainers/HashTable/_HTable.swift @@ -17,28 +17,35 @@ import InternalCollectionsUtilities @usableFromInline @frozen +@safe package struct _HTable: ~Copyable { @usableFromInline package typealias Word = _UnsafeBitSet._Word @_alwaysEmitIntoClient + @unsafe // FIXME: Only mutations are unsafe package var _count: Int @_alwaysEmitIntoClient + @unsafe // FIXME: Only mutations are unsafe package var _capacity: Int @_alwaysEmitIntoClient + @unsafe package let _bitmap: UnsafeMutablePointer? @_alwaysEmitIntoClient + @safe package var _maxProbeLength: Int @_alwaysEmitIntoClient + @safe package let scale: UInt8 // FIXME: Add a reservedScale for UniqueSet/UniqueDictonary @inlinable + @safe internal init( _capacity: Int, scale: UInt8 @@ -46,22 +53,23 @@ package struct _HTable: ~Copyable { assert( _capacity >= Self.minimumCapacity(forScale: scale) && _capacity <= Self.maximumCapacity(forScale: scale)) - self._count = 0 - self._capacity = _capacity + unsafe self._count = 0 + unsafe self._capacity = _capacity self._maxProbeLength = 0 self.scale = scale if scale == 0 { - self._bitmap = nil + unsafe self._bitmap = nil } else { assert(scale >= Self.minimumScale && scale <= Self.maximumScale) let wordCount = _HTable.wordCount(forScale: scale) let bitmap = UnsafeMutablePointer.allocate(capacity: wordCount) - bitmap.initialize(repeating: .empty, count: wordCount) - self._bitmap = bitmap + unsafe bitmap.initialize(repeating: .empty, count: wordCount) + unsafe self._bitmap = bitmap } } @inlinable + @safe internal init(capacity: Int) { assert(capacity >= 0) self.init( @@ -70,6 +78,7 @@ package struct _HTable: ~Copyable { } @inlinable + @safe internal init(minimumCapacity: Int) { precondition(minimumCapacity >= 0, "Capacity must be nonnegative") let p = Self.dynamicStorageParameters(minimumCapacity: minimumCapacity) @@ -79,44 +88,50 @@ package struct _HTable: ~Copyable { @_alwaysEmitIntoClient deinit { - _bitmap?.deallocate() + unsafe _bitmap?.deallocate() } } extension _HTable { @_alwaysEmitIntoClient @_transparent + @safe package var isSmall: Bool { - _bitmap == nil + unsafe _bitmap == nil } @_alwaysEmitIntoClient @_transparent + @safe package var count: Int { - _count + unsafe _assumeNonNegative(_count) } @_alwaysEmitIntoClient @_transparent + @safe package var capacity: Int { - _capacity + unsafe _assumeNonNegative(_capacity) } @_alwaysEmitIntoClient @_transparent + @safe package var isEmpty: Bool { - _count == 0 + count == 0 } @_alwaysEmitIntoClient @_transparent + @safe package var isFull: Bool { - _count == capacity + count == capacity } @_alwaysEmitIntoClient @_transparent + @safe package var wordCount: Int { if isSmall { return 0 } return Word.wordCount(forBitCount: bucketCount) @@ -126,18 +141,21 @@ extension _HTable { extension _HTable { @_alwaysEmitIntoClient @_transparent + @safe package var startBucket: Bucket { Bucket(offset: 0) } @_alwaysEmitIntoClient @_transparent + @safe package var endBucket: Bucket { Bucket(offset: bucketCount) } @_alwaysEmitIntoClient @_transparent + @safe package var storageCapacity: Int { if isSmall { return capacity } return 1 &<< scale @@ -145,18 +163,21 @@ extension _HTable { @_alwaysEmitIntoClient @_transparent + @safe package var bucketCount: UInt { UInt(bitPattern: storageCapacity) } @_transparent @inlinable + @safe package func isValid(_ bucket: Bucket) -> Bool { bucket._offset < bucketCount } @_transparent @inlinable + @safe package func wrapBucket(after bucket: inout Bucket) { assert(isValid(bucket)) bucket._offset &+= 1 @@ -167,12 +188,14 @@ extension _HTable { @_transparent @inlinable + @safe package func formBucket(after bucket: inout Bucket) { assert(isValid(bucket)) bucket._offset &+= 1 } @inlinable + @safe package var bitmap: Bitmap { @_lifetime(borrow self) get { @@ -182,20 +205,23 @@ extension _HTable { @_transparent @inlinable + @safe package func isOccupied(_ bucket: Bucket) -> Bool { - if isSmall { return bucket._offset < _count } + if isSmall { return bucket._offset < count } return bitmap.isOccupied(bucket) } } extension _HTable { @_transparent + @safe internal func idealBucket(forHashValue hashValue: Int) -> Bucket { let hashValue = UInt(truncatingIfNeeded: hashValue) return Bucket(offset: hashValue & (bucketCount &- 1)) } @_transparent + @safe internal func probeLength( from start: Bucket, to end: Bucket @@ -207,6 +233,7 @@ extension _HTable { } @_transparent + @safe internal func probeLength( forHashValue hashValue: Int, in bucket: Bucket @@ -218,8 +245,9 @@ extension _HTable { extension _HTable { @usableFromInline + @safe package mutating func clear() { - self._count = 0 + unsafe self._count = 0 self.bitmap.clearAll() self._maxProbeLength = 0 } @@ -227,8 +255,9 @@ extension _HTable { extension _HTable { @usableFromInline + @safe package func isTriviallyIdentical(to other: borrowing Self) -> Bool { - self._count == other._count + unsafe self._count == other._count && self._capacity == other._capacity && self._bitmap == other._bitmap && self._maxProbeLength == other._maxProbeLength diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift index 85af5f81..f390b7a8 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Append.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Append.swift @@ -22,7 +22,7 @@ extension RigidArray where Element: ~Copyable { @unsafe internal mutating func _appendUnchecked(_ item: consuming Element) { unsafe _storage.initializeElement(at: _count, to: item) - _count &+= 1 + unsafe _count &+= 1 } /// Adds an element to the end of the array. @@ -86,14 +86,14 @@ extension RigidArray where Element: ~Copyable { ) throws(E) -> Range { precondition(newItemCount >= 0, "Cannot add a negative number of items") precondition(freeCapacity >= newItemCount, "RigidArray capacity overflow") - let buffer = _freeSpace._extracting(first: newItemCount) - var span = OutputSpan(buffer: buffer, initializedCount: 0) + let buffer = unsafe _freeSpace._extracting(first: newItemCount) + var span = unsafe OutputSpan(buffer: buffer, initializedCount: 0) defer { - _count &+= span.finalize(for: buffer) + unsafe _count &+= unsafe span.finalize(for: buffer) span = OutputSpan() } try initializer(&span) - return Range(uncheckedBounds: (count, count &+ span.count)) + return unsafe Range(uncheckedBounds: (count, count &+ span.count)) } } @@ -105,13 +105,13 @@ extension RigidArray where Element: ~Copyable { moving items: UnsafeMutableBufferPointer ) -> Range { guard items.count > 0 else { - return Range(uncheckedBounds: (_count, _count)) + return unsafe Range(uncheckedBounds: (self.count, self.count)) } let c = unsafe _freeSpace._moveInitializePrefix(from: items) assert(c == items.count) - let origCount = _count - _count &+= items.count - return Range(uncheckedBounds: (origCount, _count)) + let origCount = self.count + unsafe _count &+= items.count + return unsafe Range(uncheckedBounds: (origCount, self.count)) } /// Moves the elements of a buffer to the end of this array, leaving the @@ -127,6 +127,7 @@ extension RigidArray where Element: ~Copyable { /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func append( moving items: UnsafeMutableBufferPointer ) -> Range { @@ -151,8 +152,8 @@ extension RigidArray where Element: ~Copyable { moving items: inout InputSpan ) -> Range { // FIXME: Remove this when `InputSpan` starts conforming to RangeReplaceableContainer - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(last: count) count = 0 return unsafe self.append(moving: source) } @@ -176,8 +177,8 @@ extension RigidArray where Element: ~Copyable { ) -> Range { // FIXME: Remove this when `OutputSpan` starts conforming to RangeReplaceableContainer precondition(items.count <= freeCapacity, "RigidArray capacity overflow") - return items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + return unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe _appendUnchecked(moving: source) } @@ -213,13 +214,13 @@ extension RigidArray { copying newElements: UnsafeBufferPointer ) -> Range { guard newElements.count > 0 else { - return Range(uncheckedBounds: (_count, _count)) + return unsafe Range(uncheckedBounds: (self.count, self.count)) } unsafe _freeSpace.baseAddress.unsafelyUnwrapped.initialize( from: newElements.baseAddress.unsafelyUnwrapped, count: newElements.count) - let origCount = _count - _count &+= newElements.count - return Range(uncheckedBounds: (origCount, _count)) + let origCount = self.count + unsafe _count &+= newElements.count + return unsafe Range(uncheckedBounds: (origCount, self.count)) } /// Copies the elements of a buffer to the end of this array. @@ -234,6 +235,7 @@ extension RigidArray { /// - Complexity: O(`newElements.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func append( copying newElements: UnsafeBufferPointer ) -> Range { @@ -255,6 +257,7 @@ extension RigidArray { /// - Complexity: O(`items.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func append( copying items: UnsafeMutableBufferPointer ) -> Range { @@ -285,7 +288,7 @@ extension RigidArray { prefixOf items: S ) -> S.Iterator { let (it, c) = unsafe items._copyContents(initializing: _freeSpace) - _count += c + unsafe _count += c return it } @@ -298,8 +301,8 @@ extension RigidArray { copying newElements: borrowing Source ) throws(Source.Failure) where Source.Element == Element { - let target = _freeSpace - _count += try newElements._copyContents(intoPrefixOf: target) + let target = unsafe _freeSpace + unsafe _count += try newElements._copyContents(intoPrefixOf: target) } #endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift index fc5fc1b8..c62def77 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Consumption.swift @@ -21,12 +21,12 @@ import SpanPreview extension RigidArray where Element: ~Copyable { @_lifetime(&self) public mutating func _consumeAll() -> InputSpan { - let buffer = _items - self._count = 0 - let result = InputSpan( + let buffer = unsafe _items + unsafe self._count = 0 + let result = unsafe InputSpan( buffer: buffer, initializedCount: buffer.count) - return _overrideLifetime(result, mutating: &self) + return unsafe _overrideLifetime(result, mutating: &self) } /// Remove the specified subrange of items from this array, @@ -54,13 +54,13 @@ extension RigidArray where Element: ~Copyable { return subrange.lowerBound } let buffer = unsafe _storage.extracting(subrange) - var span = InputSpan(buffer: buffer, initializedCount: buffer.count) + var span = unsafe InputSpan(buffer: buffer, initializedCount: buffer.count) consumer(&span) _ = consume span - _closeGap(at: subrange.lowerBound, count: subrange.count) - _count -= subrange.count + unsafe _closeGap(at: subrange.lowerBound, count: subrange.count) + unsafe _count -= subrange.count return subrange.lowerBound } @@ -133,9 +133,9 @@ extension RigidArray where Element: ~Copyable { consumingWith consumer: (inout InputSpan) -> Void ) { precondition( - n >= 0 && n <= _count, + n >= 0 && n <= self.count, "Count of elements to consume is out of bounds") - self.consumeSubrange(_count &- n ..< _count, consumingWith: consumer) + self.consumeSubrange(self.count &- n ..< self.count, consumingWith: consumer) } } #endif @@ -157,40 +157,44 @@ extension RigidArray where Element: ~Copyable { extension RigidArray where Element: ~Copyable { @available(SwiftStdlib 5.0, *) @frozen + @safe public struct SubrangeConsumer: ~Copyable, ~Escapable { // FIXME: We have to use our own MutableRef because the standard one // provides no access to the underlying pointer. See deinit why we need it. @usableFromInline + @unsafe internal var _base: _MutableRef @usableFromInline + @unsafe internal var _offsetRange: Range @usableFromInline + @unsafe internal var _remainder: UnsafeMutableBufferPointer @_alwaysEmitIntoClient @inline(__always) @_lifetime(&_base) internal init(_base: inout RigidArray, offsetRange: Range) { - - self._remainder = _base._storage._extracting(unchecked: offsetRange) - self._base = _MutableRef(&_base) - self._offsetRange = offsetRange + _base._checkValidBounds(offsetRange) + unsafe self._remainder = _base._storage._extracting(unchecked: offsetRange) + unsafe self._base = _MutableRef(&_base) + unsafe self._offsetRange = offsetRange } @inlinable deinit { - self._remainder.deinitialize() + unsafe self._remainder.deinitialize() // FIXME: This needs to be written as // self._base.value.closeGap(offsets: self._offsetRange) // but unfortunately we cannot mutate self in deinit yet. // MutableRef's dereferencing operation is necessarily declared mutating // to avoid exclusivity violations. - self._base._pointer.pointee + unsafe self._base._pointer.pointee ._closeGap(at: _offsetRange.lowerBound, count: _offsetRange.count) - self._base._pointer.pointee._count -= _offsetRange.count + unsafe self._base._pointer.pointee._count -= _offsetRange.count } } } @@ -201,25 +205,25 @@ extension RigidArray.SubrangeConsumer where Element: ~Copyable { @inlinable public var count: Int { - _remainder.count + unsafe _remainder.count } @inlinable @_lifetime(&self) @_lifetime(self: copy self) public mutating func drainNext(maxCount: Int) -> InputSpan { - if _remainder.isEmpty { + if unsafe _remainder.isEmpty { return .init() } - let buffer = _remainder._trim(first: maxCount) - return _overrideLifetime( + let buffer = unsafe _remainder._trim(first: maxCount) + return unsafe _overrideLifetime( InputSpan(buffer: buffer, initializedCount: buffer.count), mutating: &self) } @inlinable public consuming func finalize() -> Index { - _offsetRange.lowerBound + unsafe _offsetRange.lowerBound } } #endif diff --git a/Sources/BasicContainers/RigidArray/RigidArray+ContainerOperations.swift b/Sources/BasicContainers/RigidArray/RigidArray+ContainerOperations.swift index 13c4f7eb..1c09a053 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+ContainerOperations.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+ContainerOperations.swift @@ -29,7 +29,7 @@ extension RigidArray where Element: ~Copyable { /// - Complexity: O(1) @inlinable @inline(__always) - public var count: Int { _count } + public var count: Int { unsafe _assumeNonNegative(_count) } } @available(SwiftStdlib 5.0, *) @@ -68,7 +68,7 @@ extension RigidArray where Element: ~Copyable { @_transparent package func _checkItemIndex(_ index: Int) { precondition( - UInt(bitPattern: index) < UInt(bitPattern: _count), + UInt(bitPattern: index) < UInt(bitPattern: self.count), "Index out of bounds") } @@ -76,7 +76,7 @@ extension RigidArray where Element: ~Copyable { @_transparent package func _checkValidIndex(_ index: Int) { precondition( - UInt(bitPattern: index) <= UInt(bitPattern: _count), + UInt(bitPattern: index) <= UInt(bitPattern: self.count), "Index out of bounds") } @@ -84,7 +84,7 @@ extension RigidArray where Element: ~Copyable { @_transparent package func _checkValidBounds(_ subrange: Range) { precondition( - subrange.lowerBound >= 0 && subrange.upperBound <= _count, + subrange.lowerBound >= 0 && subrange.upperBound <= self.count, "Index range out of bounds") } } @@ -92,18 +92,20 @@ extension RigidArray where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable @inline(__always) + @unsafe package func _ptr(to index: Int) -> UnsafePointer { _checkItemIndex(index) - let p = _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) - return UnsafePointer(p) + let p = unsafe _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) + return unsafe UnsafePointer(p) } @inlinable @inline(__always) + @unsafe package mutating func _mutablePtr( to index: Int ) -> UnsafeMutablePointer { _checkItemIndex(index) - return _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) + return unsafe _storage.baseAddress.unsafelyUnwrapped.advanced(by: index) } #if compiler(>=6.4) @@ -119,12 +121,12 @@ extension RigidArray where Element: ~Copyable { @inline(__always) @_unsafeSelfDependentResult borrow { - _ptr(to: position).pointee + unsafe _ptr(to: position).pointee } @inline(__always) @_unsafeSelfDependentResult mutate { - &_mutablePtr(to: position).pointee + unsafe &_mutablePtr(to: position).pointee } } #else @@ -397,7 +399,7 @@ extension RigidArray where Element: ~Copyable { after index: inout Int ) -> MutableSpan { _checkValidIndex(index) - return _mutableSpan(in: Range(uncheckedBounds: (index, count))) + return _mutableSpan(in: unsafe Range(uncheckedBounds: (index, count))) } @inlinable @@ -410,7 +412,7 @@ extension RigidArray where Element: ~Copyable { precondition(maxCount > 0, "maxCount must be positive") let end = index._clampedUp( towards: count, maxDistance: maxCount, limitedBy: limit) - return _mutableSpan(in: Range(uncheckedBounds: (index, end))) + return _mutableSpan(in: unsafe Range(uncheckedBounds: (index, end))) } @_alwaysEmitIntoClient @@ -437,6 +439,6 @@ extension RigidArray where Element: ~Copyable { precondition(maxCount > 0, "maxCount must be positive") let start = index index = start &- Swift.min(maxCount, start) - return _span(in: Range(uncheckedBounds: (start, index))) + return _span(in: unsafe Range(uncheckedBounds: (start, index))) } } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift index eae0a943..57b2abc1 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Deprecated.swift @@ -166,11 +166,12 @@ extension RigidArray { @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") @_alwaysEmitIntoClient + @unsafe public mutating func replace( removing subrange: Range, moving newElements: UnsafeMutableBufferPointer, ) { - replaceSubrange(subrange, moving: newElements) + unsafe replaceSubrange(subrange, moving: newElements) } @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") @@ -202,20 +203,22 @@ extension RigidArray { @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") @inlinable + @unsafe public mutating func replace( removing subrange: Range, copying newElements: UnsafeBufferPointer ) { - replaceSubrange(subrange, copying: newElements) + unsafe replaceSubrange(subrange, copying: newElements) } @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") @inlinable + @unsafe public mutating func replace( removing subrange: Range, copying newElements: UnsafeMutableBufferPointer ) { - replaceSubrange(subrange, copying: newElements) + unsafe replaceSubrange(subrange, copying: newElements) } @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift b/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift index f2677916..86d7e5ab 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Equatable.swift @@ -18,7 +18,7 @@ import InternalCollectionsUtilities @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { public func isTriviallyIdentical(to other: borrowing Self) -> Bool { - self._storage._isIdentical(to: other._storage) + unsafe self._storage._isIdentical(to: other._storage) && self._count == other._count } } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift index f068a023..949a9c6d 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Initializers.swift @@ -23,8 +23,8 @@ extension RigidArray where Element: ~Copyable { @inlinable public init() { unsafe _ptr = ._dangling() - _capacity = 0 - _count = 0 + unsafe _capacity = 0 + unsafe _count = 0 } /// Initializes a new rigid array with the specified capacity and no elements. @@ -33,12 +33,12 @@ extension RigidArray where Element: ~Copyable { precondition(capacity >= 0, "Array capacity must be nonnegative") if capacity > 0 { unsafe _ptr = .allocate(capacity: capacity) - _capacity = capacity + unsafe _capacity = capacity } else { unsafe _ptr = ._dangling() - _capacity = 0 + unsafe _capacity = 0 } - _count = 0 + unsafe _count = 0 } } @@ -78,7 +78,7 @@ extension RigidArray /*where Element: Copyable*/ { public init(repeating repeatedValue: Element, count: Int) { self.init(capacity: count) unsafe _freeSpace.initialize(repeating: repeatedValue) - _count = count + unsafe _count = count } } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift index 811dc09c..e58bb010 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Insertions.swift @@ -47,7 +47,7 @@ extension RigidArray where Element: ~Copyable { assert(last == target.endIndex) } unsafe _storage.initializeElement(at: index, to: item) - _count += 1 + unsafe _count += 1 return index } } @@ -106,13 +106,13 @@ extension RigidArray where Element: ~Copyable { precondition(newItemCount >= 0, "Cannot add a negative number of items") precondition(newItemCount <= freeCapacity, "RigidArray capacity overflow") let target = unsafe _openGap(at: index, count: newItemCount) - _count &+= newItemCount - var span = OutputSpan(buffer: target, initializedCount: 0) + unsafe _count &+= newItemCount + var span = unsafe OutputSpan(buffer: target, initializedCount: 0) defer { - let c = span.finalize(for: target) + let c = unsafe span.finalize(for: target) if c < newItemCount { - _closeGap(at: index &+ c, count: newItemCount &- c) - _count &-= newItemCount &- c + unsafe _closeGap(at: index &+ c, count: newItemCount &- c) + unsafe _count &-= newItemCount &- c } span = OutputSpan() } @@ -147,7 +147,7 @@ extension RigidArray where Element: ~Copyable { at index: Int ) -> Range { insert(addingCount: items.count, at: index) { target in - target._append(moving: items) + unsafe target._append(moving: items) } } @@ -175,8 +175,8 @@ extension RigidArray where Element: ~Copyable { at index: Int ) -> Range { // FIXME: Remove when InputSpan starts conforming to RangeReplaceableContainer - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(last: count) count = 0 return unsafe self.insert(moving: source, at: index) } @@ -206,8 +206,8 @@ extension RigidArray where Element: ~Copyable { at index: Int ) -> Range { // FIXME: Remove when OutputSpan starts conforming to RangeReplaceableContainer - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe self.insert(moving: source, at: index) } @@ -279,7 +279,7 @@ extension RigidArray { return index ..< index } return self.insert(addingCount: newElements.count, at: index) { target in - target._append(copying: newElements) + unsafe target._append(copying: newElements) } } @@ -358,7 +358,7 @@ extension RigidArray { let res: Range? = items.withContiguousStorageIfAvailable { buffer in precondition(buffer.count == newCount, "Broken Collection: mismatching count") return self.insert(addingCount: buffer.count, at: index) { target in - target._append(copying: buffer) + unsafe target._append(copying: buffer) } } if let res { return res } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift index 2acc3030..da70e35f 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Removals.swift @@ -23,7 +23,7 @@ extension RigidArray where Element: ~Copyable { @inlinable public mutating func removeAll() { unsafe _items.deinitialize() - _count = 0 + unsafe _count = 0 } /// Removes and returns the element at the specified position. @@ -60,8 +60,8 @@ extension RigidArray where Element: ~Copyable { public mutating func remove(at index: Int) -> Element { _checkItemIndex(index) let old = unsafe _storage.moveElement(from: index) - _closeGap(at: index, count: 1) - _count -= 1 + unsafe _closeGap(at: index, count: 1) + unsafe _count -= 1 return old } @@ -76,8 +76,8 @@ extension RigidArray where Element: ~Copyable { @discardableResult public mutating func removeLast() -> Element { precondition(!isEmpty, "Cannot remove last element from an empty array") - let old = unsafe _storage.moveElement(from: _count - 1) - _count -= 1 + let old = unsafe _storage.moveElement(from: self.count - 1) + unsafe _count -= 1 return old } @@ -96,12 +96,12 @@ extension RigidArray where Element: ~Copyable { public mutating func removeLast(_ k: Int) { if k == 0 { return } precondition( - k >= 0 && k <= _count, + k >= 0 && k <= self.count, "Count of elements to remove is out of bounds") unsafe _storage.extracting( - Range(uncheckedBounds: (_count - k, _count)) + Range(uncheckedBounds: (self.count - k, self.count)) ).deinitialize() - _count &-= k + unsafe _count &-= k } /// Removes the specified subrange of elements from the array. @@ -120,8 +120,8 @@ extension RigidArray where Element: ~Copyable { _checkValidBounds(bounds) guard !bounds.isEmpty else { return bounds.lowerBound } unsafe _storage.extracting(bounds).deinitialize() - _closeGap(at: bounds.lowerBound, count: bounds.count) - _count -= bounds.count + unsafe _closeGap(at: bounds.lowerBound, count: bounds.count) + unsafe _count -= bounds.count return bounds.lowerBound } diff --git a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift index ba7fd185..14dd1a10 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray+Replacements.swift @@ -70,11 +70,12 @@ extension RigidArray where Element: ~Copyable { precondition( newItemCount - subrange.count <= freeCapacity, "RigidArray capacity overflow") - return try _uncheckedReplaceSubrange( + return unsafe try _uncheckedReplaceSubrange( subrange, addingCount: newItemCount, initializingWith: initializer) } @_alwaysEmitIntoClient + @unsafe internal mutating func _uncheckedReplaceSubrange( _ subrange: Range, addingCount newItemCount: Int, @@ -82,20 +83,20 @@ extension RigidArray where Element: ~Copyable { ) throws(E) -> Range { // Destroy removed items unsafe _items.extracting(subrange).deinitialize() - let target = _resizeGap(in: subrange, to: newItemCount) - var span = OutputSpan(buffer: target, initializedCount: 0) + let target = unsafe _resizeGap(in: subrange, to: newItemCount) + var span = unsafe OutputSpan(buffer: target, initializedCount: 0) defer { - let c = span.finalize(for: target) + let c = unsafe span.finalize(for: target) if c < newItemCount { - self._closeGap( + unsafe self._closeGap( at: subrange.lowerBound &+ c, count: newItemCount &- c) - _count &-= newItemCount &- c + unsafe _count &-= newItemCount &- c } span = OutputSpan() } try initializer(&span) - return Range(uncheckedBounds: ( + return unsafe Range(uncheckedBounds: ( subrange.lowerBound, subrange.lowerBound + newItemCount)) } } @@ -163,7 +164,7 @@ extension RigidArray where Element: ~Copyable { precondition( newItemCount - subrange.count <= freeCapacity, "RigidArray capacity overflow") - return try _uncheckedReplaceSubrange( + return unsafe try _uncheckedReplaceSubrange( subrange, consumingWith: consumer, addingCount: newItemCount, @@ -171,6 +172,7 @@ extension RigidArray where Element: ~Copyable { } @_alwaysEmitIntoClient + @unsafe internal mutating func _uncheckedReplaceSubrange( _ subrange: Range, consumingWith consumer: (inout InputSpan) -> Void, @@ -180,27 +182,27 @@ extension RigidArray where Element: ~Copyable { do { // Consume items to be removed let buffer = unsafe _storage.extracting(subrange) - var span = InputSpan(buffer: buffer, initializedCount: buffer.count) + var span = unsafe InputSpan(buffer: buffer, initializedCount: buffer.count) consumer(&span) _ = consume span } do { // Insert new items - let target = _resizeGap(in: subrange, to: newItemCount) - var span = OutputSpan(buffer: target, initializedCount: 0) + let target = unsafe _resizeGap(in: subrange, to: newItemCount) + var span = unsafe OutputSpan(buffer: target, initializedCount: 0) defer { - let c = span.finalize(for: target) + let c = unsafe span.finalize(for: target) if c < newItemCount { - self._closeGap( + unsafe self._closeGap( at: subrange.lowerBound &+ c, count: newItemCount &- c) - _count &-= newItemCount &- c + unsafe _count &-= newItemCount &- c } span = OutputSpan() } try initializer(&span) } - return Range(uncheckedBounds: ( + return unsafe Range(uncheckedBounds: ( subrange.lowerBound, subrange.lowerBound + newItemCount)) } #endif @@ -244,7 +246,7 @@ extension RigidArray where Element: ~Copyable { moving newElements: UnsafeMutableBufferPointer, ) -> Range { replaceSubrange(subrange, addingCount: newElements.count) { target in - target.withUnsafeMutableBufferPointer { buffer, count in + unsafe target.withUnsafeMutableBufferPointer { buffer, count in count = unsafe buffer._moveInitializePrefix(from: newElements) } } @@ -283,8 +285,8 @@ extension RigidArray where Element: ~Copyable { _ subrange: Range, moving items: inout InputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(last: count) count = 0 return unsafe self.replaceSubrange(subrange, moving: source) } @@ -323,8 +325,8 @@ extension RigidArray where Element: ~Copyable { _ subrange: Range, moving items: inout OutputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe self.replaceSubrange(subrange, moving: source) } @@ -366,7 +368,7 @@ extension RigidArray where Element: ~Copyable { ) -> Range { // FIXME: Remove this in favor of the generic algorithm over DrainableContainer unsafe newElements._unsafeEdit { buffer, count in - let source = buffer._extracting(first: count) + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe self.replaceSubrange(subrange, moving: source) } @@ -447,7 +449,7 @@ extension RigidArray { copying newElements: UnsafeBufferPointer ) -> Range { replaceSubrange(subrange, addingCount: newElements.count) { target in - target.withUnsafeMutableBufferPointer { buffer, count in + unsafe target.withUnsafeMutableBufferPointer { buffer, count in count = unsafe buffer._initializePrefix(copying: newElements) } } @@ -481,6 +483,7 @@ extension RigidArray { /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func replaceSubrange( _ subrange: Range, copying newElements: UnsafeMutableBufferPointer @@ -534,7 +537,7 @@ extension RigidArray { newCount: Int ) -> Range { self.replaceSubrange(subrange, addingCount: newCount) { target in - target.withUnsafeMutableBufferPointer { dst, dstCount in + unsafe target.withUnsafeMutableBufferPointer { dst, dstCount in let done: Void? = newElements.withContiguousStorageIfAvailable { src in let i = unsafe dst._initializePrefix(copying: src) precondition( diff --git a/Sources/BasicContainers/RigidArray/RigidArray.swift b/Sources/BasicContainers/RigidArray/RigidArray.swift index f3df6cd0..a8c4b233 100644 --- a/Sources/BasicContainers/RigidArray/RigidArray.swift +++ b/Sources/BasicContainers/RigidArray/RigidArray.swift @@ -21,6 +21,7 @@ import InternalCollectionsUtilities /// noncopyable elements. @frozen @available(*, unavailable, message: "RigidArray requires a Swift 6.2 toolchain") +@safe public struct RigidArray: ~Copyable { @usableFromInline internal var _ptr: UnsafeMutablePointer @@ -83,33 +84,37 @@ public struct RigidArray: ~Copyable { /// the use of ``UniqueArray`` rather than `RigidArray`. (For copyable elements, /// the standard `Array` is an even more convenient choice.) @available(SwiftStdlib 5.0, *) -@safe @frozen +@safe public struct RigidArray: ~Copyable { @usableFromInline + @unsafe internal var _ptr: UnsafeMutablePointer @usableFromInline + @unsafe // Setting this is unsafe internal var _capacity: Int @usableFromInline + @unsafe // Setting this is unsafe internal var _count: Int @_alwaysEmitIntoClient deinit { - if _capacity == 0 { + if capacity == 0 { return } - unsafe _ptr.deinitialize(count: _count) + unsafe _ptr.deinitialize(count: count) unsafe _ptr.deallocate() } @_alwaysEmitIntoClient + @unsafe package init(_storage: UnsafeMutableBufferPointer, count: Int) { unsafe self._ptr = _storage.baseAddress.unsafelyUnwrapped - self._capacity = _storage.count - self._count = count + unsafe self._capacity = _storage.count + unsafe self._count = count } } @@ -122,6 +127,7 @@ extension RigidArray: @unchecked Sendable where Element: Sendable & ~Copyable {} extension RigidArray where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent + @unsafe internal var _storage: UnsafeMutableBufferPointer { unsafe UnsafeMutableBufferPointer(start: _ptr, count: _capacity) } @@ -131,7 +137,7 @@ extension RigidArray where Element: ~Copyable { /// - Complexity: O(1) @inlinable @_transparent - public var capacity: Int { _assumeNonNegative(_capacity) } + public var capacity: Int { unsafe _assumeNonNegative(_capacity) } /// The number of additional elements that can be added to this array without /// exceeding its storage capacity. @@ -157,11 +163,13 @@ extension RigidArray where Element: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable + @unsafe internal var _items: UnsafeMutableBufferPointer { unsafe _storage.extracting(Range(uncheckedBounds: (0, _count))) } @inlinable + @unsafe internal var _freeSpace: UnsafeMutableBufferPointer { unsafe _storage.extracting(Range(uncheckedBounds: (_count, capacity))) } @@ -236,21 +244,21 @@ extension RigidArray where Element: ~Copyable { public mutating func edit( _ body: (inout OutputSpan) throws(E) -> R ) throws(E) -> R { - var span = OutputSpan(buffer: _storage, initializedCount: _count) + var span = unsafe OutputSpan(buffer: _storage, initializedCount: _count) defer { - _count = span.finalize(for: _storage) + unsafe _count = unsafe span.finalize(for: _storage) span = OutputSpan() } return try body(&span) } // FIXME: Stop using and remove this in favor of `edit` - @unsafe @inlinable + @unsafe internal mutating func _unsafeEdit( _ body: (UnsafeMutableBufferPointer, inout Int) throws(E) -> R ) throws(E) -> R { - defer { precondition(_count >= 0 && _count <= capacity) } + defer { precondition(count >= 0 && count <= capacity) } return unsafe try body(_storage, &_count) } } @@ -259,14 +267,14 @@ extension RigidArray where Element: ~Copyable { extension RigidArray where Element: ~Copyable { @inlinable internal func _contiguousSubrange(following index: inout Int) -> Range { - precondition(index >= 0 && index <= _count, "Index out of bounds") - defer { index = _count } - return unsafe Range(uncheckedBounds: (index, _count)) + precondition(index >= 0 && index <= count, "Index out of bounds") + defer { index = count } + return unsafe Range(uncheckedBounds: (index, count)) } @inlinable internal func _contiguousSubrange(preceding index: inout Int) -> Range { - precondition(index >= 0 && index <= _count, "Index out of bounds") + precondition(index >= 0 && index <= count, "Index out of bounds") defer { index = 0 } return unsafe Range(uncheckedBounds: (0, index)) } @@ -374,12 +382,12 @@ extension RigidArray where Element: ~Copyable { let i = unsafe newStorage.moveInitialize(fromContentsOf: self._items) assert(i == count) - if _capacity != 0 { + if capacity != 0 { unsafe _storage.deallocate() } unsafe _ptr = newStorage.baseAddress.unsafelyUnwrapped - _capacity = newStorage.count + unsafe self._capacity = newStorage.count } /// Ensure that the array has capacity to store the specified number of @@ -423,7 +431,7 @@ extension RigidArray { var result = RigidArray(capacity: capacity) let initialized = unsafe result._storage.initialize(fromContentsOf: _items) precondition(initialized == count) - result._count = count + unsafe result._count = count return result } } @@ -434,6 +442,7 @@ extension RigidArray { @available(SwiftStdlib 5.0, *) extension RigidArray where Element: ~Copyable { @inlinable + @unsafe internal mutating func _closeGap( at index: Int, count: Int ) { @@ -451,13 +460,13 @@ extension RigidArray where Element: ~Copyable { internal mutating func _openGap( at index: Int, count: Int ) -> UnsafeMutableBufferPointer { - assert(index >= 0 && index <= _count) + assert(index >= 0 && index <= self.count) assert(count <= freeCapacity) guard count > 0 else { return unsafe _storage.extracting(index ..< index) } let source = unsafe _storage.extracting( - Range(uncheckedBounds: (index, _count))) + Range(uncheckedBounds: (index, self.count))) let target = unsafe _storage.extracting( - Range(uncheckedBounds: (index + count, _count + count))) + Range(uncheckedBounds: (index + count, self.count + count))) let i = unsafe target.moveInitialize(fromContentsOf: source) assert(i == target.count) return unsafe _storage.extracting( @@ -475,16 +484,16 @@ extension RigidArray where Element: ~Copyable { internal mutating func _resizeGap( in subrange: Range, to newItemCount: Int ) -> UnsafeMutableBufferPointer { - assert(subrange.lowerBound >= 0 && subrange.upperBound <= _count) + assert(subrange.lowerBound >= 0 && subrange.upperBound <= self.count) assert(newItemCount >= 0 && newItemCount - subrange.count <= freeCapacity) if newItemCount > subrange.count { _ = unsafe _openGap( at: subrange.upperBound, count: newItemCount - subrange.count) } else if newItemCount < subrange.count { - _closeGap( + unsafe _closeGap( at: subrange.lowerBound + newItemCount, count: subrange.count - newItemCount) } - _count += newItemCount - subrange.count + unsafe self._count += newItemCount - subrange.count let gapRange = unsafe Range( uncheckedBounds: (subrange.lowerBound, subrange.lowerBound + newItemCount)) return unsafe _storage.extracting(gapRange) diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Consumption.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Consumption.swift index abee306a..fc0deb78 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Consumption.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Consumption.swift @@ -27,13 +27,13 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { inout InputSpan ) -> Void ) { - let keys = self._keys._memberBuf - let values = self._valueBuf - _keys._table.consumeAll { buckets in - let keyBuffer = keys._extracting(buckets) - let valueBuffer = values._extracting(buckets) - var keySpan = InputSpan(buffer: keyBuffer, initializedCount: keyBuffer.count) - var valueSpan = InputSpan(buffer: valueBuffer, initializedCount: valueBuffer.count) + let keys = unsafe self._keys._memberBuf + let values = unsafe self._valueBuf + unsafe _keys._table.consumeAll { buckets in + let keyBuffer = unsafe keys._extracting(buckets) + let valueBuffer = unsafe values._extracting(buckets) + var keySpan = unsafe InputSpan(buffer: keyBuffer, initializedCount: keyBuffer.count) + var valueSpan = unsafe InputSpan(buffer: valueBuffer, initializedCount: valueBuffer.count) consumer(&keySpan, &valueSpan) _ = consume keySpan _ = consume valueSpan @@ -42,16 +42,17 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { #endif @inlinable + @unsafe public mutating func _consumeAll( consumingWith consumer: ( UnsafeMutableBufferPointer, UnsafeMutableBufferPointer ) -> Void ) { - let keys = self._keys._memberBuf - let values = self._valueBuf - _keys._table.consumeAll { buckets in - consumer(keys._extracting(buckets), values._extracting(buckets)) + let keys = unsafe self._keys._memberBuf + let values = unsafe self._valueBuf + unsafe _keys._table.consumeAll { buckets in + unsafe consumer(keys._extracting(buckets), values._extracting(buckets)) } } } diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift index d0b89989..f05b57e9 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Equatable.swift @@ -22,7 +22,7 @@ import InternalCollectionsUtilities extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable public func isTriviallyIdentical(to other: borrowing Self) -> Bool { - self._keys.isTriviallyIdentical(to: other._keys) + unsafe self._keys.isTriviallyIdentical(to: other._keys) && self._values == other._values } } @@ -38,16 +38,16 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { guard self.count == other.count else { return false } - var it = self._keys._table.makeBucketIterator() + var it = unsafe self._keys._table.makeBucketIterator() while let next = it.nextOccupiedRegion() { var lb = next.lowerBound while lb < next.upperBound { - let res = other._find(self._keyPtr(at: lb).pointee) + let res = unsafe other._find(self._keyPtr(at: lb).pointee) guard let rb = res.bucket else { return false } - let lp = self._valuePtr(at: lb) - let rp = other._valuePtr(at: rb) - guard areEquivalent(lp.pointee, rp.pointee) else { return false } + let lp = unsafe self._valuePtr(at: lb) + let rp = unsafe other._valuePtr(at: rb) + guard unsafe areEquivalent(lp.pointee, rp.pointee) else { return false } lb._offset &+= 1 } } diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift index bd39ab9e..12045608 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Hashable.swift @@ -26,15 +26,15 @@ extension RigidDictionary where Value: Hashable & ~Copyable { @inlinable public func hash(into hasher: inout Hasher) { var commutativeHash = 0 - var it = self._keys._table.makeBucketIterator() + var it = unsafe self._keys._table.makeBucketIterator() while let next = it.nextOccupiedRegion() { var b = next.lowerBound while b < next.upperBound { // Note that we use a copy of our own hasher here. This makes hash values // dependent on its state, eliminating static collision patterns. var elementHasher = hasher - _keyPtr(at: b).pointee.hash(into: &elementHasher) - _valuePtr(at: b).pointee.hash(into: &elementHasher) + unsafe _keyPtr(at: b).pointee.hash(into: &elementHasher) + unsafe _valuePtr(at: b).pointee.hash(into: &elementHasher) commutativeHash ^= elementHasher.finalize() b._offset &+= 1 } diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Index.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Index.swift index 1737fec1..f92bcf06 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Index.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Index.swift @@ -57,35 +57,39 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @available(SwiftStdlib 5.0, *) extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @frozen + @safe public struct Element: ~Copyable, ~Escapable { // FIXME: See if using (the real) `struct Borrow` would make sense here. @_alwaysEmitIntoClient + @unsafe package var _key: UnsafePointer @_alwaysEmitIntoClient + @unsafe package var _value: UnsafePointer @_alwaysEmitIntoClient @_lifetime(borrow _base) + @safe package init( _base: borrowing RigidDictionary, bucket: _Bucket ) { assert(_base._isOccupied(bucket)) - self._key = .init(_base._keyPtr(at: bucket)) - self._value = .init(_base._valuePtr(at: bucket)) + unsafe self._key = .init(_base._keyPtr(at: bucket)) + unsafe self._value = .init(_base._valuePtr(at: bucket)) } @_alwaysEmitIntoClient public var key: Key { - // FIXME: This should be a borrow accessor - unsafeAddress { _key } + @_unsafeSelfDependentResult + borrow { unsafe _key.pointee } } @_alwaysEmitIntoClient public var value: Value { - // FIXME: This should be a borrow accessor - unsafeAddress { _value } + @_unsafeSelfDependentResult + borrow { unsafe _value.pointee } } } diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift index 98c3769a..f71fd117 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Indices.swift @@ -17,6 +17,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @available(SwiftStdlib 6.4, *) @frozen + @safe public struct Indices: ~Escapable { @_alwaysEmitIntoClient package let _base: Ref<_HTable> @@ -33,7 +34,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { public var indices: Indices { @_lifetime(borrow self) get { - Indices(_base: self._keys._table) + unsafe Indices(_base: self._keys._table) } } } @@ -71,7 +72,7 @@ where Key: ~Copyable, Value: ~Copyable public func makeBorrowingIterator() -> BorrowingIterator { let bit = self._base.value.makeBucketIterator() // FIXME: This override really should not be necessary. Check if the real `struct Borrow` fixes it. - let override = _overrideLifetime(bit, copying: self) + let override = unsafe _overrideLifetime(bit, copying: self) return BorrowingIterator(_it: override) } } diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Initializers.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Initializers.swift index 564fda6a..f9cc1ab8 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Initializers.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Initializers.swift @@ -26,14 +26,14 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable package init(_table: consuming _HTable) { - let keys = RigidSet(_table: _table) + let keys = unsafe RigidSet(_table: _table) let values: UnsafeMutablePointer if keys.capacity == 0 { - values = ._dangling() + unsafe values = ._dangling() } else { - values = .allocate(capacity: keys._storageCapacity) + unsafe values = .allocate(capacity: keys._storageCapacity) } - self.init(_keys: keys, values: values) + unsafe self.init(_keys: keys, values: values) } @inlinable diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Insertions.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Insertions.swift index 47886b4f..dd303327 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Insertions.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Insertions.swift @@ -18,48 +18,50 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable @inline(__always) @discardableResult + @unsafe package mutating func _insertNew( _ key: consuming Key, hashValue: Int, _ value: consuming Value ) -> _Bucket { precondition(!isFull, "RigidDictionary capacity overflow") - let keys = _keyBuf - let values = _valueBuf - if self._keys._table.isSmall { - let bucket = self._keys._table.insertNew_Small( + let keys = unsafe _keyBuf + let values = unsafe _valueBuf + if self._keys._isSmall { + let bucket = unsafe self._keys._table.insertNew_Small( swapper: { - swap(&key, &keys[$0]) - swap(&value, &values[$0]) + unsafe swap(&key, &keys[$0]) + unsafe swap(&value, &values[$0]) }) - keys._initializeElement(at: bucket, to: key) - values._initializeElement(at: bucket, to: value) + unsafe keys._initializeElement(at: bucket, to: key) + unsafe values._initializeElement(at: bucket, to: value) return bucket } - return _insertNew_Large(key, hashValue: hashValue, value) + return unsafe _insertNew_Large(key, hashValue: hashValue, value) } @_alwaysEmitIntoClient @inline(__always) + @unsafe package mutating func _insertNew_Large( _ key: consuming Key, hashValue: Int, _ value: consuming Value ) -> _Bucket { - let keys = _keyBuf - let values = _valueBuf + let keys = unsafe _keyBuf + let values = unsafe _valueBuf let seed = self._keys._seed - let bucket = self._keys._table.insertNew_Large( + let bucket = unsafe self._keys._table.insertNew_Large( hashValue: hashValue, hashGenerator: { - keys[$0]._rawHashValue(seed: seed) + unsafe keys[$0]._rawHashValue(seed: seed) }, swapper: { bucket in - swap(&key, &keys[bucket]) - swap(&value, &values[bucket]) + unsafe swap(&key, &keys[bucket]) + unsafe swap(&value, &values[bucket]) }) - keys.initializeElement(at: bucket.offset, to: key) - values.initializeElement(at: bucket.offset, to: value) + unsafe keys.initializeElement(at: bucket.offset, to: key) + unsafe values.initializeElement(at: bucket.offset, to: value) return bucket } @@ -74,7 +76,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { if r.bucket != nil { return value } - self._insertNew(key, hashValue: r.hashValue, value) + unsafe self._insertNew(key, hashValue: r.hashValue, value) return nil } @@ -86,9 +88,9 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { ) -> Value? { let r = _find(key) if let bucket = r.bucket { - return exchange(&_valuePtr(at: bucket).pointee, with: value) + return unsafe exchange(&_valuePtr(at: bucket).pointee, with: value) } - self._insertNew(key, hashValue: r.hashValue, value) + unsafe self._insertNew(key, hashValue: r.hashValue, value) return nil } @@ -106,7 +108,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { bucket = b } else { let value = try body(key) - bucket = self._insertNew(key, hashValue: r.hashValue, value) + bucket = unsafe self._insertNew(key, hashValue: r.hashValue, value) } return _borrowValue(at: bucket) } @@ -123,19 +125,19 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { let r = _keys._find(key) bucket = r.bucket if let bucket { - value = _valuePtr(at: bucket).move() + value = unsafe _valuePtr(at: bucket).move() } var key: Key? = key // To work around inability to consume key in deinit defer { if let bucket { if let value = value.take() { // Simple update - _valuePtr(at: bucket).initialize(to: value) + unsafe _valuePtr(at: bucket).initialize(to: value) } else { // Removal - self._keyPtr(at: bucket).deinitialize(count: 1) - _resolveHole(at: bucket) + unsafe self._keyPtr(at: bucket).deinitialize(count: 1) + unsafe _resolveHole(at: bucket) } } else if let value = value.take() { // Insertion - self._insertNew(key.take()!, hashValue: r.hashValue, value) + unsafe self._insertNew(key.take()!, hashValue: r.hashValue, value) } } return try updater(&value) diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Lookup.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Lookup.swift index 327e14b4..213bacc0 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Lookup.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Lookup.swift @@ -44,7 +44,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { forKey key: borrowing Key ) -> Ref? { guard let bucket = self._find(key).bucket else { return nil } - return Ref(unsafeAddress: _valuePtr(at: bucket), borrowing: self) + return unsafe Ref(unsafeAddress: _valuePtr(at: bucket), borrowing: self) } /// Checks if the given key is present in the `RigidDictionary`, and returns @@ -60,7 +60,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { forKey key: borrowing Key ) -> MutableRef? { guard let bucket = self._find(key).bucket else { return nil } - return MutableRef(unsafeAddress: _valuePtr(at: bucket), mutating: &self) + return unsafe MutableRef(unsafeAddress: _valuePtr(at: bucket), mutating: &self) } /// A stand-in for a `struct Ref`-returning lookup operation. @@ -73,23 +73,23 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { _ body: (borrowing Value) throws(E) -> R? ) throws(E) -> R? { guard let bucket = self._find(key).bucket else { return nil } - return try body(_valueBuf[bucket]) + return unsafe try body(_valueBuf[bucket]) } @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @_lifetime(borrow self) package func _borrowKey(at bucket: _Bucket) -> Ref { - assert(_keys._table.isOccupied(bucket)) - return Ref(unsafeAddress: _keyPtr(at: bucket), borrowing: self) + assert(unsafe _keys._table.isOccupied(bucket)) + return unsafe Ref(unsafeAddress: _keyPtr(at: bucket), borrowing: self) } @available(SwiftStdlib 6.4, *) @_alwaysEmitIntoClient @_lifetime(borrow self) package func _borrowValue(at bucket: _Bucket) -> Ref { - assert(_keys._table.isOccupied(bucket)) - return Ref(unsafeAddress: _valuePtr(at: bucket), borrowing: self) + assert(unsafe _keys._table.isOccupied(bucket)) + return unsafe Ref(unsafeAddress: _valuePtr(at: bucket), borrowing: self) } } diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Removals.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Removals.swift index 5426f8b3..3b012f57 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Removals.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Removals.swift @@ -24,10 +24,10 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable package mutating func _removeValue(at bucket: _Bucket) -> Value { - assert(self._keys._table.isOccupied(bucket)) - self._keyPtr(at: bucket).deinitialize(count: 1) - let oldValue = self._valuePtr(at: bucket).move() - _resolveHole(at: bucket) + assert(unsafe self._keys._table.isOccupied(bucket)) + unsafe self._keyPtr(at: bucket).deinitialize(count: 1) + let oldValue = unsafe self._valuePtr(at: bucket).move() + unsafe _resolveHole(at: bucket) return oldValue } @@ -35,19 +35,20 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { /// moved out (e.g., by `updateValue(forKey:with:)`). Handles key /// deinitialization and hole resolution without touching the value slot. @inlinable + @unsafe package mutating func _resolveHole(at bucket: _Bucket) { - assert(self._keys._table.isOccupied(bucket)) - self._keys._table.createHole(at: bucket) + assert(unsafe self._keys._table.isOccupied(bucket)) + unsafe self._keys._table.createHole(at: bucket) let seed = self._keys._seed - let keys = self._keys._members.unsafelyUnwrapped - self._keys._table.resolveHole( + let keys = unsafe self._keys._members.unsafelyUnwrapped + unsafe self._keys._table.resolveHole( at: bucket, hashGenerator: { - keys[$0.offset]._rawHashValue(seed: seed) + unsafe keys[$0.offset]._rawHashValue(seed: seed) }, mover: { - (keys + $1.offset).initialize(to: (keys + $0.offset).move()) - (_values + $1.offset).initialize(to: (_values + $0.offset).move()) + unsafe (keys + $1.offset).initialize(to: (keys + $0.offset).move()) + unsafe (_values + $1.offset).initialize(to: (_values + $0.offset).move()) }) } @@ -57,18 +58,19 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { /// /// This operation is intended to be used just before resizing the table. @inlinable + @unsafe package mutating func _punchHole(at bucket: _Bucket) -> Value { - assert(self._keys._table.isOccupied(bucket)) - self._keys._table.createHole(at: bucket) - self._keyPtr(at: bucket).deinitialize(count: 1) + assert(unsafe self._keys._table.isOccupied(bucket)) + unsafe self._keys._table.createHole(at: bucket) + unsafe self._keyPtr(at: bucket).deinitialize(count: 1) - let oldValue = self._valuePtr(at: bucket).move() - let keys = self._keys._members.unsafelyUnwrapped - self._keys._table.finalizeHole( + let oldValue = unsafe self._valuePtr(at: bucket).move() + let keys = unsafe self._keys._members.unsafelyUnwrapped + unsafe self._keys._table.finalizeHole( at: bucket, mover: { - (keys + $1.offset).initialize(to: (keys + $0.offset).move()) - (_values + $1.offset).initialize(to: (_values + $0.offset).move()) + unsafe (keys + $1.offset).initialize(to: (keys + $0.offset).move()) + unsafe (_values + $1.offset).initialize(to: (_values + $0.offset).move()) }) return oldValue } @@ -76,9 +78,9 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable public mutating func removeAll() { if isEmpty { return } - _deinitializeValues() - _keys._deinitializeMembers() - _keys._table.clear() + unsafe _deinitializeValues() + unsafe _keys._deinitializeMembers() + unsafe _keys._table.clear() } } diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Resizing.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Resizing.swift index 6a4a5862..90fe4a9a 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary+Resizing.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary+Resizing.swift @@ -34,14 +34,14 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { scale: UInt8, capacity: Int, ) { - assert(scale != self._keys._table.scale || capacity != self.capacity) + assert(unsafe scale != self._keys._table.scale || capacity != self.capacity) assert(self.count <= capacity) assert(capacity <= _HTable.maximumCapacity(forScale: scale)) assert(capacity >= _HTable.minimumCapacity(forScale: scale)) - if scale != 0, scale == self._keys._table.scale { + if scale != 0, unsafe scale == self._keys._table.scale { // Large result with matching scales. We don't need to rehash or // reallocate, we just need to update the logical capacity. - self._keys._table._capacity = capacity + unsafe self._keys._table._capacity = capacity return } @@ -51,36 +51,36 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { return } - let sourceKeys = old._keys._members.unsafelyUnwrapped - let sourceValues = old._values - let targetKeys = self._keys._members.unsafelyUnwrapped - let targetValues = self._values - if self._keys._table.isSmall { - self._keys._table.migrateItems_Small(from: &old._keys._table) { src, dst in - (targetKeys + dst.offset).initialize(to: (sourceKeys + src.offset).move()) - (targetValues + dst.offset).initialize(to: (sourceValues + src.offset).move()) + let sourceKeys = unsafe old._keys._members.unsafelyUnwrapped + let sourceValues = unsafe old._values + let targetKeys = unsafe self._keys._members.unsafelyUnwrapped + let targetValues = unsafe self._values + if self._keys._isSmall { + unsafe self._keys._table.migrateItems_Small(from: &old._keys._table) { src, dst in + unsafe (targetKeys + dst.offset).initialize(to: (sourceKeys + src.offset).move()) + unsafe (targetValues + dst.offset).initialize(to: (sourceValues + src.offset).move()) } } else { let seed = self._keys._seed - var srcKey = sourceKeys - var srcValue = sourceValues - self._keys._table.migrateItems_Large( + var srcKey = unsafe sourceKeys + var srcValue = unsafe sourceValues + unsafe self._keys._table.migrateItems_Large( from: &old._keys._table, selector: { - srcKey = sourceKeys + $0.offset - srcValue = sourceValues + $0.offset - return srcKey.pointee._rawHashValue(seed: seed) + unsafe srcKey = sourceKeys + $0.offset + unsafe srcValue = sourceValues + $0.offset + return unsafe srcKey.pointee._rawHashValue(seed: seed) }, hashGenerator: { - targetKeys[$0.offset]._rawHashValue(seed: seed) + unsafe targetKeys[$0.offset]._rawHashValue(seed: seed) }, swapper: { - swap(&srcKey.pointee, &targetKeys[$0.offset]) - swap(&srcValue.pointee, &targetValues[$0.offset]) + unsafe swap(&srcKey.pointee, &targetKeys[$0.offset]) + unsafe swap(&srcValue.pointee, &targetValues[$0.offset]) }, finalizer: { - (targetKeys + $0.offset).initialize(to: srcKey.move()) - (targetValues + $0.offset).initialize(to: srcValue.move()) + unsafe (targetKeys + $0.offset).initialize(to: srcKey.move()) + unsafe (targetValues + $0.offset).initialize(to: srcValue.move()) } ) } diff --git a/Sources/BasicContainers/RigidDictionary/RigidDictionary.swift b/Sources/BasicContainers/RigidDictionary/RigidDictionary.swift index 1cdabdd4..af44da5a 100644 --- a/Sources/BasicContainers/RigidDictionary/RigidDictionary.swift +++ b/Sources/BasicContainers/RigidDictionary/RigidDictionary.swift @@ -19,6 +19,7 @@ import InternalCollectionsUtilities #if compiler(<6.4) @available(*, unavailable, message: "RigidDictionary requires a Swift 6.4 toolchain") @frozen +@safe public struct RigidDictionary< Key: Hashable, Value: ~Copyable @@ -31,6 +32,7 @@ public struct RigidDictionary< @available(SwiftStdlib 5.0, *) @frozen @_addressableForDependencies +@safe public struct RigidDictionary< Key: Hashable & ~Copyable, Value: ~Copyable @@ -42,17 +44,19 @@ public struct RigidDictionary< package var _keys: RigidSet @_alwaysEmitIntoClient + @unsafe package var _values: UnsafeMutablePointer @_alwaysEmitIntoClient @_transparent + @unsafe package init( _keys: consuming RigidSet, values: UnsafeMutablePointer ) { - assert((values != ._dangling()) == (_keys._members != nil)) + assert(unsafe (values != ._dangling()) == (_keys._members != nil)) self._keys = _keys - self._values = values + unsafe self._values = values } @_alwaysEmitIntoClient @@ -61,17 +65,18 @@ public struct RigidDictionary< // and once in `_keys.deinit`. `self` not being mutable really hurts us // here. if !isEmpty { - _deinitializeValues() - _values.deallocate() + unsafe _deinitializeValues() + unsafe _values.deallocate() } } @_alwaysEmitIntoClient + @unsafe internal func _deinitializeValues() { - let values = _valueBuf - var it = _keys._table.makeBucketIterator() + let values = unsafe _valueBuf + var it = unsafe _keys._table.makeBucketIterator() while let range = it.nextOccupiedRegion() { - values.extracting(range._offsets).deinitialize() + unsafe values.extracting(range._offsets).deinitialize() } } } @@ -81,13 +86,13 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable @inline(__always) public var count: Int { - _assumeNonNegative(_keys._table.count) + _keys.count } @inlinable @inline(__always) public var capacity: Int { - _assumeNonNegative(_keys._table.capacity) + _keys.capacity } @inlinable @@ -105,7 +110,7 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable @inline(__always) public var freeCapacity: Int { - _assumeNonNegative(capacity &- count) + _keys.freeCapacity } @_alwaysEmitIntoClient @@ -113,37 +118,47 @@ extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { public var _scale: UInt8 { _keys._scale } + + @_alwaysEmitIntoClient + @_transparent + public var _isSmall: Bool { + _keys._isSmall + } } @available(SwiftStdlib 5.0, *) extension RigidDictionary where Key: ~Copyable, Value: ~Copyable { @_alwaysEmitIntoClient @_transparent + @unsafe internal var _keyBuf: UnsafeMutableBufferPointer { - _keys._memberBuf + unsafe _keys._memberBuf } @_alwaysEmitIntoClient @_transparent + @unsafe internal var _valueBuf: UnsafeMutableBufferPointer { - .init(start: _values, count: Int(bitPattern: _keys._table.bucketCount)) + unsafe .init(start: _values, count: Int(bitPattern: _keys._table.bucketCount)) } @_alwaysEmitIntoClient @_transparent + @unsafe internal func _valuePtr( at bucket: _HTable.Bucket ) -> UnsafeMutablePointer { - assert(_keys._table.isValid(bucket)) - return _values.advanced(by: bucket.offset) + assert(unsafe _keys._table.isValid(bucket)) + return unsafe _values.advanced(by: bucket.offset) } @_alwaysEmitIntoClient @_transparent + @unsafe internal func _keyPtr( at bucket: _HTable.Bucket ) -> UnsafeMutablePointer { - _keys._memberPtr(at: bucket) + unsafe _keys._memberPtr(at: bucket) } } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Consumption.swift b/Sources/BasicContainers/RigidSet/RigidSet+Consumption.swift index 71cf6697..9ef4b55d 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Consumption.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Consumption.swift @@ -24,10 +24,10 @@ extension RigidSet where Element: ~Copyable { public mutating func consumeAll( consumingWith consumer: (inout InputSpan) -> Void ) { - let storage = self._memberBuf - _table.consumeAll { buckets in - let buffer = storage._extracting(buckets) - var span = InputSpan(buffer: buffer, initializedCount: buffer.count) + let storage = unsafe self._memberBuf + unsafe _table.consumeAll { buckets in + let buffer = unsafe storage._extracting(buckets) + var span = unsafe InputSpan(buffer: buffer, initializedCount: buffer.count) consumer(&span) _ = consume span } @@ -38,9 +38,9 @@ extension RigidSet where Element: ~Copyable { public mutating func _consumeAll( consumingWith consumer: (UnsafeMutableBufferPointer) -> Void ) { - let storage = self._memberBuf - _table.consumeAll { buckets in - consumer(storage._extracting(buckets)) + let storage = unsafe self._memberBuf + unsafe _table.consumeAll { buckets in + unsafe consumer(storage._extracting(buckets)) } } } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift b/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift index a9362064..a231bcc7 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Debugging.swift @@ -24,21 +24,21 @@ extension RigidSet where Element: ~Copyable { chains: Bool = false, buckets: Bool = false, ) -> String { - var s = _table.describe(bitmap: bitmap) + var s = unsafe _table.describe(bitmap: bitmap) if chains { s += "\n" s += _chainDescription } - if buckets, !_table.isSmall, !_table.isEmpty { + if buckets, !_isSmall, !isEmpty { s += "\nBuckets:" - var it = _table.makeBucketIterator() + var it = unsafe _table.makeBucketIterator() var c = 0 while let next = it.nextOccupiedRegion() { var b = next.lowerBound while b != next.upperBound { if c.isMultiple(of: 8) { s += "\n " } let hashValue = _hashValue(at: b) - let idealBucket = _table.idealBucket(forHashValue: hashValue) + let idealBucket = unsafe _table.idealBucket(forHashValue: hashValue) let s1 = String(b.offset)._lpad(5) let s2 = String(idealBucket.offset)._rpad(5) s += "\(s1)→\(s2) " @@ -62,22 +62,22 @@ extension RigidSet where Element: ~Copyable { public func _probeLengthCounts() -> (successful: [Int], unsuccessful: [Int]) { var positiveLengths: [Int: Int] = [:] var negativeLengths: [Int: Int] = [:] - var it = self._table.makeBucketIterator() - var prev = self._table.startBucket + var it = unsafe self._table.makeBucketIterator() + var prev = unsafe self._table.startBucket while let next = it.nextOccupiedRegion() { negativeLengths[0, default: 0] += next.lowerBound.offset - prev.offset var b = next.lowerBound while b != next.upperBound { let hashValue = self._hashValue(at: b) - let pl = _table.probeLength(forHashValue: hashValue, in: b) + let pl = unsafe _table.probeLength(forHashValue: hashValue, in: b) positiveLengths[pl, default: 0] += 1 var nl = next.upperBound.offset - b.offset #if !COLLECTIONS_NO_ROBIN_HOOD_HASHING - nl = Swift.min(nl, _table._maxProbeLength) + nl = Swift.min(nl, unsafe _table._maxProbeLength) #endif negativeLengths[nl, default: 0] += 1 - _table.formBucket(after: &b) + unsafe _table.formBucket(after: &b) } prev = next.upperBound } @@ -118,8 +118,8 @@ extension RigidSet where Element: ~Copyable { histogram += "\n" sum += (length + 1) * count } - if _table.count > 0 { - let avg = Double((sum * 1000 + 500) / _table.count) / 1000.0 + if unsafe _table.count > 0 { + let avg = unsafe Double((sum * 1000 + 500) / _table.count) / 1000.0 str += " AVG: \(avg)\n" } str += histogram @@ -138,8 +138,8 @@ extension RigidSet where Element: ~Copyable { histogram += "\n" sum += length * count } - if _table.storageCapacity > 0 { - let avg = Double((sum * 1000 + 500) / _table.storageCapacity) / 1000.0 + if unsafe _table.storageCapacity > 0 { + let avg = unsafe Double((sum * 1000 + 500) / _table.storageCapacity) / 1000.0 str += " AVG: \(avg)\n" } str += histogram @@ -162,7 +162,7 @@ extension RigidSet where Element: ~Copyable { public func _checkInvariants( failureHandler: (String) -> Void ) { - _table.checkInvariants( + unsafe _table.checkInvariants( failureHandler: failureHandler, hashGenerator: { _hashValue(at: $0) }) } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift b/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift index 584fa44d..03f70649 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Equatable.swift @@ -21,7 +21,7 @@ import InternalCollectionsUtilities extension RigidSet where Element: ~Copyable { @inlinable public func isTriviallyIdentical(to other: borrowing Self) -> Bool { - self._members == other._members + unsafe self._members == other._members && self._table.isTriviallyIdentical(to: other._table) } } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift b/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift index 7dede4f7..d35016b3 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Hashable.swift @@ -40,7 +40,7 @@ extension RigidSet where Element: ~Copyable { let next = it.nextSpan() var i = 0 while i < next.count { - hash ^= next[unchecked: i]._rawHashValue(seed: seed) + hash ^= unsafe next[unchecked: i]._rawHashValue(seed: seed) i &+= 1 } } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Index.swift b/Sources/BasicContainers/RigidSet/RigidSet+Index.swift index 575fa5d6..6b062431 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Index.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Index.swift @@ -74,22 +74,22 @@ extension RigidSet where Element: ~Copyable { @inlinable public var startIndex: Index { - if _table.isSmall { return Index(_bucket: _Bucket(offset: 0)) } - guard let b = _table.bitmap.firstOccupiedBucket(from: _Bucket(offset: 0)) + if _isSmall { return Index(_bucket: _Bucket(offset: 0)) } + guard let b = unsafe _table.bitmap.firstOccupiedBucket(from: _Bucket(offset: 0)) else { return endIndex } return Index(_bucket: b) } @inlinable public var endIndex: Index { - if _table.isSmall { return Index(_offset: count) } - return Index(_bucket: _table.endBucket) + if _isSmall { return Index(_offset: count) } + return unsafe Index(_bucket: _table.endBucket) } @_alwaysEmitIntoClient @_transparent package func _isOccupied(_ bucket: _Bucket) -> Bool { - _table.isValid(bucket) && _table.isOccupied(bucket) + unsafe _table.isValid(bucket) && _table.isOccupied(bucket) } @_alwaysEmitIntoClient @@ -115,13 +115,13 @@ extension RigidSet where Element: ~Copyable { @inlinable public func index(after index: Index) -> Index { _checkItemIndex(index) - if _table.isSmall { + if _isSmall { return Index(_bucket: _Bucket(offset: index._bucket._offset &+ 1)) } var start = index._bucket start._offset &+= 1 - guard start < _table.endBucket else { return Index(_bucket: start) } - guard let b = _table.bitmap.firstOccupiedBucket(from: start) + guard unsafe start < _table.endBucket else { return Index(_bucket: start) } + guard let b = unsafe _table.bitmap.firstOccupiedBucket(from: start) else { return endIndex } return Index(_bucket: b) } @@ -131,7 +131,7 @@ extension RigidSet where Element: ~Copyable { @_unsafeSelfDependentResult borrow { _checkItemIndex(index) - return _memberPtr(at: index._bucket).pointee + return unsafe _memberPtr(at: index._bucket).pointee } } @@ -142,20 +142,20 @@ extension RigidSet where Element: ~Copyable { ) -> Span { _checkValidIndex(index) if index == endIndex { return .init() } - if _table.isSmall { + if _isSmall { let start = Int(index._offset) - let end = _table.count - let items = _memberBuf.extracting(start ..< end) + let end = self.count + let items = unsafe _memberBuf.extracting(start ..< end) index = Index(_offset: end) - let span = Span(_unsafeElements: items) - return _overrideLifetime(span, borrowing: self) + let span = unsafe Span(_unsafeElements: items) + return unsafe _overrideLifetime(span, borrowing: self) } - let buckets = _table.bitmap.nextOccupiedRegion( + let buckets = unsafe _table.bitmap.nextOccupiedRegion( from: &index._bucket, maxCount: .max, limit: _table.endBucket) - let span = Span( + let span = unsafe Span( _unsafeStart: _memberPtr(at: buckets.lowerBound), count: buckets._offsets.count) - return _overrideLifetime(span, borrowing: self) + return unsafe _overrideLifetime(span, borrowing: self) } @inlinable @@ -168,22 +168,22 @@ extension RigidSet where Element: ~Copyable { precondition(maxCount > 0, "maxCount must be positive") if index == endIndex { return .init() } let limit = limit._offset < index._offset ? endIndex : limit - if _table.isSmall { + if _isSmall { let start = Int(index._offset) - var c = Swift.min(maxCount, _table.count - start) + var c = unsafe Swift.min(maxCount, _table.count - start) var end = start end._advance(by: &c, limitedBy: Int(limit._offset)) - let items = _memberBuf.extracting(start ..< end) + let items = unsafe _memberBuf.extracting(start ..< end) index = Index(_offset: end) - let span = Span(_unsafeElements: items) - return _overrideLifetime(span, borrowing: self) + let span = unsafe Span(_unsafeElements: items) + return unsafe _overrideLifetime(span, borrowing: self) } - let buckets = _table.bitmap.nextOccupiedRegion( + let buckets = unsafe _table.bitmap.nextOccupiedRegion( from: &index._bucket, maxCount: maxCount, limit: limit._bucket) - let span = Span( + let span = unsafe Span( _unsafeStart: _memberPtr(at: buckets.lowerBound), count: buckets._offsets.count) - return _overrideLifetime(span, borrowing: self) + return unsafe _overrideLifetime(span, borrowing: self) } } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift b/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift index 8f082694..239f95fa 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Initializers.swift @@ -24,7 +24,7 @@ extension RigidSet where Element: ~Copyable { @inlinable public init(capacity: Int) { precondition(capacity >= 0, "Capacity must be nonnegative") - self.init(_table: _HTable(capacity: capacity)) + unsafe self.init(_table: _HTable(capacity: capacity)) } @inlinable diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift index 7e7f0a8a..3fd45557 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Insertions.swift @@ -49,13 +49,13 @@ extension RigidSet where Element: ~Copyable { hashValue: Int ) -> _Bucket { precondition(!isFull, "RigidSet capacity overflow") - let storage = _memberBuf - if _table.isSmall { - let bucket = _table.insertNew_Small( + let storage = unsafe _memberBuf + if _isSmall { + let bucket = unsafe _table.insertNew_Small( swapper: { - swap(&item, &storage[$0]) + unsafe swap(&item, &storage[$0]) }) - storage._initializeElement(at: bucket, to: item) + unsafe storage._initializeElement(at: bucket, to: item) return bucket } return _insertNew_Large(item, hashValue: hashValue) @@ -67,17 +67,17 @@ extension RigidSet where Element: ~Copyable { _ item: consuming Element, hashValue: Int ) -> _Bucket { - let storage = _memberBuf + let storage = unsafe _memberBuf let seed = self._seed - let bucket = _table.insertNew_Large( + let bucket = unsafe _table.insertNew_Large( hashValue: hashValue, hashGenerator: { - storage[$0]._rawHashValue(seed: seed) + unsafe storage[$0]._rawHashValue(seed: seed) }, swapper: { - swap(&item, &storage[$0]) + unsafe swap(&item, &storage[$0]) }) - storage.initializeElement(at: bucket.offset, to: item) + unsafe storage.initializeElement(at: bucket.offset, to: item) return bucket } @@ -94,7 +94,7 @@ extension RigidSet where Element: ~Copyable { ) -> Element? { let r = _find(item) if let bucket = r.bucket { - return exchange(&_memberPtr(at: bucket).pointee, with: item) + return unsafe exchange(&_memberPtr(at: bucket).pointee, with: item) } _insertNew(item, hashValue: r.hashValue) return nil @@ -176,7 +176,7 @@ extension RigidSet /* where Element: Copyable */ { ) { var i = 0 while i < items.count { - self.insert(items[unchecked: i]) + unsafe self.insert(items[unchecked: i]) i &+= 1 } } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Iterable.swift b/Sources/BasicContainers/RigidSet/RigidSet+Iterable.swift index 8231f874..0b86feda 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Iterable.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Iterable.swift @@ -35,56 +35,61 @@ extension RigidSet: Iterable where Element: ~Copyable { package borrowing func _validateIterator( _ iterator: borrowing BorrowingIterator ) -> Bool { - iterator._baseAddress == UnsafePointer(self._members) + unsafe iterator._baseAddress == UnsafePointer(self._members) && iterator._bucketIterator._words == UnsafePointer(self._table._bitmap) } @frozen + @safe public struct BorrowingIterator: BorrowingIteratorProtocol, ~Copyable, ~Escapable { @_alwaysEmitIntoClient + @unsafe package var _baseAddress: UnsafePointer? @_alwaysEmitIntoClient package var _bucketIterator: _HTable.BucketIterator @_alwaysEmitIntoClient - package var _endBucket: _Bucket + package let _endBucket: _Bucket @_alwaysEmitIntoClient @_lifetime(borrow _set) + @safe package init( _set: borrowing RigidSet ) { - self._baseAddress = .init(_set._members) - self._bucketIterator = _set._table.makeBucketIterator() + unsafe self._baseAddress = .init(_set._members) + self._bucketIterator = unsafe _set._table.makeBucketIterator() self._endBucket = self._bucketIterator._endBucket _bucketIterator.advanceToOccupied() } @_alwaysEmitIntoClient @_lifetime(borrow _set) + @unsafe package init( _set: borrowing RigidSet, from start: Index, to end: Index ) { - self._baseAddress = .init(_set._members) - self._bucketIterator = _set._table.makeBucketIterator(from: start._bucket) + unsafe self._baseAddress = .init(_set._members) + self._bucketIterator = unsafe _set._table.makeBucketIterator(from: start._bucket) self._endBucket = end._bucket _bucketIterator.advanceToOccupied() } @_alwaysEmitIntoClient @_lifetime(copy self) + @unsafe internal func _span(from start: _Bucket, to end: _Bucket) -> Span { - let items = UnsafeBufferPointer( + let items = unsafe UnsafeBufferPointer( start: _baseAddress.unsafelyUnwrapped + start.offset, count: end.offset - start.offset) - return _overrideLifetime(Span(_unsafeElements: items), copying: self) + return unsafe _overrideLifetime(Span(_unsafeElements: items), copying: self) } @_alwaysEmitIntoClient @@ -103,7 +108,7 @@ extension RigidSet: Iterable where Element: ~Copyable { end = _endBucket _bucketIterator.advanceToEnd() } - return _span(from: start, to: end) + return unsafe _span(from: start, to: end) } } } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Lookup.swift b/Sources/BasicContainers/RigidSet/RigidSet+Lookup.swift index f4122eab..3bc794f8 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Lookup.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Lookup.swift @@ -19,15 +19,15 @@ extension RigidSet where Element: ~Copyable { package borrowing func _find( _ item: borrowing Element ) -> (bucket: _Bucket?, hashValue: Int) { - let storage = _memberBuf - if _table.isSmall { - let bucket = _table.find_Small(tester: { storage[$0] == item }) + let storage = unsafe _memberBuf + if _isSmall { + let bucket = unsafe _table.find_Small { unsafe storage[$0] == item } return (bucket, 0) } let hashValue = _hashValue(for: item) - let bucket = _table.find_Large( + let bucket = unsafe _table.find_Large( hashValue: hashValue, - tester: { storage[$0] == item }) + tester: { unsafe storage[$0] == item }) return (bucket, hashValue) } @@ -40,8 +40,8 @@ extension RigidSet where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow self) package func _borrowValue(at bucket: _Bucket) -> Ref { - assert(self._table.isOccupied(bucket)) - return Ref(unsafeAddress: self._memberPtr(at: bucket), borrowing: self) + assert(unsafe self._table.isOccupied(bucket)) + return unsafe Ref(unsafeAddress: self._memberPtr(at: bucket), borrowing: self) } } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Removals.swift b/Sources/BasicContainers/RigidSet/RigidSet+Removals.swift index 8d5b3dbd..c64aab85 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Removals.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Removals.swift @@ -19,7 +19,7 @@ extension RigidSet where Element: ~Copyable { public mutating func remove(_ member: borrowing Element) -> Element? { let r = _find(member) guard let bucket = r.bucket else { return nil } - return _remove(at: bucket) + return unsafe _remove(at: bucket) } /// Remove the member currently at the specified occupied bucket, @@ -28,33 +28,35 @@ extension RigidSet where Element: ~Copyable { /// /// This operation is intended to be used just before resizing the table. @inlinable + @unsafe package mutating func _punchHole(at bucket: _Bucket) -> Element { - assert(_table.isOccupied(bucket)) - _table.createHole(at: bucket) - let result = _memberPtr(at: bucket).move() - let members = _members.unsafelyUnwrapped - _table.finalizeHole( + assert(unsafe _table.isOccupied(bucket)) + unsafe _table.createHole(at: bucket) + let result = unsafe _memberPtr(at: bucket).move() + let members = unsafe _members.unsafelyUnwrapped + unsafe _table.finalizeHole( at: bucket, mover: { - (members + $1.offset).initialize(to: (members + $0.offset).move()) + unsafe (members + $1.offset).initialize(to: (members + $0.offset).move()) }) return result } @inlinable + @unsafe package mutating func _remove(at bucket: _Bucket) -> Element { - assert(_table.isOccupied(bucket)) - _table.createHole(at: bucket) - let result = _memberPtr(at: bucket).move() + assert(unsafe _table.isOccupied(bucket)) + unsafe _table.createHole(at: bucket) + let result = unsafe _memberPtr(at: bucket).move() let seed = self._seed - let members = _members.unsafelyUnwrapped - _table.resolveHole( + let members = unsafe _members.unsafelyUnwrapped + unsafe _table.resolveHole( at: bucket, hashGenerator: { - members[$0.offset]._rawHashValue(seed: seed) + unsafe members[$0.offset]._rawHashValue(seed: seed) }, mover: { - (members + $1.offset).initialize(to: (members + $0.offset).move()) + unsafe (members + $1.offset).initialize(to: (members + $0.offset).move()) }) return result } @@ -62,8 +64,8 @@ extension RigidSet where Element: ~Copyable { @inlinable public mutating func removeAll() { if isEmpty { return } - _deinitializeMembers() - _table.clear() + unsafe _deinitializeMembers() + unsafe _table.clear() } } diff --git a/Sources/BasicContainers/RigidSet/RigidSet+Resizing.swift b/Sources/BasicContainers/RigidSet/RigidSet+Resizing.swift index 91d4e0a4..a17a82a4 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet+Resizing.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet+Resizing.swift @@ -34,48 +34,48 @@ extension RigidSet where Element: ~Copyable { scale: UInt8, capacity: Int, ) { - assert(scale != self._table.scale || capacity != self.capacity) + assert(unsafe scale != self._table.scale || capacity != self.capacity) assert(self.count <= capacity) assert(capacity <= _HTable.maximumCapacity(forScale: scale)) assert(capacity >= _HTable.minimumCapacity(forScale: scale)) - if scale != 0, scale == self._table.scale { + if scale != 0, unsafe scale == self._table.scale { // Large result with matching scales. We don't need to rehash or // reallocate, we just need to update the logical capacity. - self._table._capacity = capacity + unsafe self._table._capacity = capacity return } let newTable = _HTable(_capacity: capacity, scale: scale) - var old = exchange(&self, with: Self(_table: newTable)) + var old = unsafe exchange(&self, with: Self(_table: newTable)) guard old.count > 0 else { return } - let source = old._members.unsafelyUnwrapped - let target = self._members.unsafelyUnwrapped - if self._table.isSmall { - self._table.migrateItems_Small(from: &old._table) { src, dst in - (target + dst.offset).initialize(to: (source + src.offset).move()) + let source = unsafe old._members.unsafelyUnwrapped + let target = unsafe self._members.unsafelyUnwrapped + if _isSmall { + unsafe self._table.migrateItems_Small(from: &old._table) { src, dst in + unsafe (target + dst.offset).initialize(to: (source + src.offset).move()) } return } let seed = self._seed - var src = source - self._table.migrateItems_Large( + var src = unsafe source + unsafe self._table.migrateItems_Large( from: &old._table, selector: { - src = source + $0.offset - return src.pointee._rawHashValue(seed: seed) + unsafe src = source + $0.offset + return unsafe src.pointee._rawHashValue(seed: seed) }, hashGenerator: { - target[$0.offset]._rawHashValue(seed: seed) + unsafe target[$0.offset]._rawHashValue(seed: seed) }, swapper: { - swap(&src.pointee, &target[$0.offset]) + unsafe swap(&src.pointee, &target[$0.offset]) }, finalizer: { - (target + $0.offset).initialize(to: src.move()) + unsafe (target + $0.offset).initialize(to: src.move()) } ) } diff --git a/Sources/BasicContainers/RigidSet/RigidSet.swift b/Sources/BasicContainers/RigidSet/RigidSet.swift index 75526e92..9b94dd00 100644 --- a/Sources/BasicContainers/RigidSet/RigidSet.swift +++ b/Sources/BasicContainers/RigidSet/RigidSet.swift @@ -30,44 +30,50 @@ public struct RigidSet: ~Copyable { /// elements. @available(SwiftStdlib 5.0, *) @frozen +@safe public struct RigidSet: ~Copyable { @usableFromInline package typealias _Bucket = _HTable.Bucket @_alwaysEmitIntoClient + @unsafe package var _members: UnsafeMutablePointer? @_alwaysEmitIntoClient + @unsafe // FIXME: Only mutations are unsafe package var _table: _HTable @inlinable @_transparent + @unsafe package init( _table: consuming _HTable ) { assert(_table.isEmpty) if _table.capacity == 0 { - self._members = nil + unsafe self._members = nil } else { - self._members = .allocate(capacity: _table.storageCapacity) + unsafe self._members = .allocate(capacity: _table.storageCapacity) } - self._table = _table + unsafe self._table = _table } @_alwaysEmitIntoClient deinit { if !isEmpty { - _deinitializeMembers() + unsafe _deinitializeMembers() } - _members?.deallocate() + unsafe _members?.deallocate() } @_alwaysEmitIntoClient + @unsafe internal func _deinitializeMembers() { - let storage = _memberBuf - var it = _table.makeBucketIterator() + // FIXME: This should be declared mutating and update stored properties. + let storage = unsafe _memberBuf + var it = unsafe _table.makeBucketIterator() while let range = it.nextOccupiedRegion() { - storage._extracting(unchecked: range._offsets).deinitialize() + unsafe storage._extracting(unchecked: range._offsets).deinitialize() } } } @@ -77,13 +83,13 @@ extension RigidSet where Element: ~Copyable { @inlinable @inline(__always) public var count: Int { - _assumeNonNegative(_table.count) + unsafe _assumeNonNegative(_table.count) } @inlinable @inline(__always) public var capacity: Int { - _assumeNonNegative(_table.capacity) + unsafe _assumeNonNegative(_table.capacity) } @inlinable @@ -107,13 +113,19 @@ extension RigidSet where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent public var _scale: UInt8 { - _table.scale + unsafe _table.scale } @_alwaysEmitIntoClient @_transparent public var _storageCapacity: Int { - _table.storageCapacity + unsafe _table.storageCapacity + } + + @_alwaysEmitIntoClient + @_transparent + public var _isSmall: Bool { + unsafe _table.isSmall } } @@ -121,17 +133,19 @@ extension RigidSet where Element: ~Copyable { extension RigidSet where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent + @unsafe internal var _memberBuf: UnsafeMutableBufferPointer { - .init(start: _members, count: Int(bitPattern: _table.bucketCount)) + unsafe .init(start: _members, count: Int(bitPattern: _table.bucketCount)) } @_alwaysEmitIntoClient @_transparent + @unsafe internal func _memberPtr( at bucket: _Bucket ) -> UnsafeMutablePointer { - assert(_table.isValid(bucket)) - return _members.unsafelyUnwrapped.advanced(by: bucket.offset) + assert(unsafe _table.isValid(bucket)) + return unsafe _members.unsafelyUnwrapped.advanced(by: bucket.offset) } } @@ -140,9 +154,9 @@ extension RigidSet where Element: ~Copyable { @_alwaysEmitIntoClient internal var _seed: Int { #if COLLECTIONS_DETERMINISTIC_HASHING - Int(_table.scale) + unsafe Int(_table.scale) #else - Int(bitPattern: _members) + unsafe Int(bitPattern: _members) #endif } @@ -151,8 +165,8 @@ extension RigidSet where Element: ~Copyable { internal borrowing func _hashValue( at bucket: _Bucket ) -> Int { - assert(bucket.offset >= 0 && bucket.offset < _table.storageCapacity) - return _hashValue(for: _members.unsafelyUnwrapped[bucket.offset]) + assert(unsafe bucket.offset >= 0 && bucket.offset < _table.storageCapacity) + return unsafe _hashValue(for: _members.unsafelyUnwrapped[bucket.offset]) } @_alwaysEmitIntoClient diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift index 9d073e85..c38babf1 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Append.swift @@ -89,7 +89,7 @@ extension UniqueArray where Element: ~Copyable { moving items: UnsafeMutableBufferPointer ) -> Range { _ensureFreeCapacity(items.count) - return _storage._appendUnchecked(moving: items) + return unsafe _storage._appendUnchecked(moving: items) } #if UnstableContainersPreview @@ -131,8 +131,8 @@ extension UniqueArray where Element: ~Copyable { moving items: inout OutputSpan ) -> Range { _ensureFreeCapacity(items.count) - return items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + return unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe _storage._appendUnchecked(moving: source) } @@ -159,9 +159,9 @@ extension UniqueArray where Element: ~Copyable { // FIXME: Remove in favor of the generic RRC algorithm _ensureFreeCapacity(items.count) return items.edit { source in - source.withUnsafeMutableBufferPointer { buffer, count in + unsafe source.withUnsafeMutableBufferPointer { buffer, count in count = 0 - return _storage.append(moving: buffer._extracting(first: count)) + return unsafe _storage.append(moving: buffer._extracting(first: count)) } } } diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift index 2c3cd53b..1dbedc4d 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Deprecated.swift @@ -184,7 +184,7 @@ extension UniqueArray where Element: ~Copyable { removing subrange: Range, moving newElements: UnsafeMutableBufferPointer, ) { - replaceSubrange(subrange, moving: newElements) + unsafe replaceSubrange(subrange, moving: newElements) } #if UnstableContainersPreview @@ -258,7 +258,7 @@ extension UniqueArray { removing subrange: Range, copying newElements: UnsafeBufferPointer ) { - replaceSubrange(subrange, copying: newElements) + unsafe replaceSubrange(subrange, copying: newElements) } @available(*, deprecated, renamed: "replace(_:copying:)") @@ -267,7 +267,7 @@ extension UniqueArray { removing subrange: Range, copying newElements: UnsafeMutableBufferPointer ) { - self.replaceSubrange(subrange, copying: newElements) + unsafe self.replaceSubrange(subrange, copying: newElements) } @available(*, deprecated, renamed: "replace(_:copying:)") diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift index 149efddc..bc00937b 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Insertions.swift @@ -113,13 +113,14 @@ extension UniqueArray where Element: ~Copyable { /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func insert( moving items: UnsafeMutableBufferPointer, at index: Int ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(items.count) - return _storage.insert(moving: items, at: index) + return unsafe _storage.insert(moving: items, at: index) } #if UnstableContainersPreview @@ -231,6 +232,7 @@ extension UniqueArray { /// - Complexity: O(`self.count` + `newElements.count`) @inlinable @discardableResult + @unsafe public mutating func insert( copying newElements: UnsafeBufferPointer, at index: Int ) -> Range { @@ -262,6 +264,7 @@ extension UniqueArray { /// - Complexity: O(`self.count` + `newElements.count`) @inlinable @discardableResult + @unsafe public mutating func insert( copying newElements: UnsafeMutableBufferPointer, at index: Int diff --git a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift index 00009dfd..a173a3bb 100644 --- a/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift +++ b/Sources/BasicContainers/UniqueArray/UniqueArray+Replacements.swift @@ -70,7 +70,7 @@ extension UniqueArray where Element: ~Copyable { precondition(newItemCount >= 0, "Cannot add a negative number of items") // FIXME: Avoid moving the subsequent elements twice on resize. _ensureFreeCapacity(newItemCount - subrange.count) - return try _storage._uncheckedReplaceSubrange( + return unsafe try _storage._uncheckedReplaceSubrange( subrange, addingCount: newItemCount, initializingWith: initializer) @@ -139,7 +139,7 @@ extension UniqueArray where Element: ~Copyable { _storage._checkValidBounds(subrange) precondition(newItemCount >= 0, "Cannot add a negative number of items") _ensureFreeCapacity(newItemCount - subrange.count) - return try _storage._uncheckedReplaceSubrange( + return unsafe try _storage._uncheckedReplaceSubrange( subrange, consumingWith: consumer, addingCount: newItemCount, @@ -181,13 +181,14 @@ extension UniqueArray where Element: ~Copyable { /// - Complexity: O(`self.count` + `newElements.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func replaceSubrange( _ subrange: Range, moving newElements: UnsafeMutableBufferPointer, ) -> Range { // FIXME: Avoid moving the subsequent elements twice. _ensureFreeCapacity(newElements.count - subrange.count) - return _storage.replaceSubrange(subrange, moving: newElements) + return unsafe _storage.replaceSubrange(subrange, moving: newElements) } #if UnstableContainersPreview @@ -381,6 +382,7 @@ extension UniqueArray { @_alwaysEmitIntoClient @inline(__always) @discardableResult + @unsafe public mutating func replaceSubrange( _ subrange: Range, copying newElements: UnsafeBufferPointer diff --git a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Consumption.swift b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Consumption.swift index 517ef057..959b98dc 100644 --- a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Consumption.swift +++ b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Consumption.swift @@ -32,13 +32,14 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable { #endif @inlinable + @unsafe public mutating func _consumeAll( consumingWith consumer: ( UnsafeMutableBufferPointer, UnsafeMutableBufferPointer ) -> Void ) { - _storage._consumeAll(consumingWith: consumer) + unsafe _storage._consumeAll(consumingWith: consumer) } } diff --git a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Insertions.swift b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Insertions.swift index ce46f09a..5defa8de 100644 --- a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Insertions.swift +++ b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Insertions.swift @@ -25,10 +25,10 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable { if bucket != nil { return value } - if _ensureFreeCapacity(1), !_storage._keys._table.isSmall { + if _ensureFreeCapacity(1), !_storage._isSmall { hashValue = _storage._keys._hashValue(for: key) } - _storage._insertNew(key, hashValue: hashValue, value) + unsafe _storage._insertNew(key, hashValue: hashValue, value) return nil } @@ -40,12 +40,12 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable { ) -> Value? { var (bucket, hashValue) = _storage._find(key) if let bucket { - return exchange(&_storage._valuePtr(at: bucket).pointee, with: value) + return unsafe exchange(&_storage._valuePtr(at: bucket).pointee, with: value) } - if _ensureFreeCapacity(1), !_storage._keys._table.isSmall { + if _ensureFreeCapacity(1), !_storage._isSmall { hashValue = _storage._keys._hashValue(for: key) } - _storage._insertNew(key, hashValue: hashValue, value) + unsafe _storage._insertNew(key, hashValue: hashValue, value) return nil } @@ -64,10 +64,10 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable { } else { let value = try body(key) var hashValue = r.hashValue - if _ensureFreeCapacity(1), !_storage._keys._table.isSmall { + if _ensureFreeCapacity(1), !_storage._isSmall { hashValue = _storage._keys._hashValue(for: key) } - bucket = _storage._insertNew(key, hashValue: hashValue, value) + bucket = unsafe _storage._insertNew(key, hashValue: hashValue, value) } return _storage._borrowValue(at: bucket) } @@ -84,25 +84,25 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable { let r = _storage._find(key) bucket = r.bucket if let bucket { - value = _storage._valuePtr(at: bucket).move() + value = unsafe _storage._valuePtr(at: bucket).move() } var key: Key? = key // To work around inability to consume key in deinit defer { if let bucket { if let value = value.take() { // Simple update - _storage._valuePtr(at: bucket).initialize(to: value) + unsafe _storage._valuePtr(at: bucket).initialize(to: value) } else { // Removal - _ = _removeValue(at: bucket) + _ = unsafe _removeValue(at: bucket) } } else if let value = value.take() { // Insertion. let key = key.take()! var hashValue = r.hashValue - if _ensureFreeCapacity(1), !_storage._keys._table.isSmall { + if _ensureFreeCapacity(1), !_storage._isSmall { hashValue = _storage._keys._hashValue(for: key) } - _storage._insertNew(key, hashValue: hashValue, value) + unsafe _storage._insertNew(key, hashValue: hashValue, value) } } diff --git a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Lookup.swift b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Lookup.swift index e0746344..b4f02d4e 100644 --- a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Lookup.swift +++ b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Lookup.swift @@ -36,7 +36,7 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable { forKey key: borrowing Key ) -> Ref? { // FIXME: Why is this override necessary? Is it sound? It was triggered by RigidDictionary becoming `@_addressableForDependencies`. - _overrideLifetime(_storage.value(forKey: key), borrowing: self) + unsafe _overrideLifetime(_storage.value(forKey: key), borrowing: self) } /// Checks if the given key is present in the `RigidDictionary`, and returns diff --git a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Removals.swift b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Removals.swift index 0fa97c1b..113398c9 100644 --- a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Removals.swift +++ b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary+Removals.swift @@ -19,17 +19,18 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable { public mutating func removeValue(forKey key: borrowing Key) -> Value? { let r = _storage._keys._find(key) guard let bucket = r.bucket else { return nil } - return _removeValue(at: bucket) + return unsafe _removeValue(at: bucket) } @inlinable + @unsafe package mutating func _removeValue(at bucket: _Bucket) -> Value { guard self.count <= _HTable.minimumCapacity(forScale: self._scale) else { return _storage._removeValue(at: bucket) } // Shrink storage. - let result = _storage._punchHole(at: bucket) + let result = unsafe _storage._punchHole(at: bucket) _resize(minimumCapacity: self.count) return result } diff --git a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary.swift b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary.swift index 264ccea4..6bdc3f36 100644 --- a/Sources/BasicContainers/UniqueDictionary/UniqueDictionary.swift +++ b/Sources/BasicContainers/UniqueDictionary/UniqueDictionary.swift @@ -47,13 +47,13 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable @inline(__always) public var count: Int { - _assumeNonNegative(_storage._keys._table._count) + _storage.count } @inlinable @inline(__always) public var capacity: Int { - _assumeNonNegative(_storage._keys._table._capacity) + _storage.capacity } @inlinable @@ -71,7 +71,7 @@ extension UniqueDictionary where Key: ~Copyable, Value: ~Copyable { @inlinable @inline(__always) public var freeCapacity: Int { - _assumeNonNegative(capacity &- count) + _storage.freeCapacity } @_alwaysEmitIntoClient diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Consumption.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Consumption.swift index 633abba1..848ca6f7 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Consumption.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Consumption.swift @@ -23,18 +23,15 @@ extension UniqueSet where Element: ~Copyable { public mutating func consumeAll( consumingWith consumer: (inout InputSpan) -> Void ) { - self._consumeAll { buffer in - var span = InputSpan(buffer: buffer, initializedCount: buffer.count) - consumer(&span) - _ = consume span - } + _storage.consumeAll(consumingWith: consumer) } @inlinable + @unsafe public mutating func _consumeAll( consumingWith consumer: (UnsafeMutableBufferPointer) -> Void ) { - _storage._consumeAll(consumingWith: consumer) + unsafe _storage._consumeAll(consumingWith: consumer) } } diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift index 2e4b4e00..25fea4aa 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Initializers.swift @@ -24,7 +24,7 @@ extension UniqueSet where Element: ~Copyable { public init(minimumCapacity: Int) { precondition(minimumCapacity >= 0, "Capacity must be nonnegative") let table = _HTable(minimumCapacity: minimumCapacity) - self.init(_storage: RigidSet(_table: table)) + unsafe self.init(_storage: RigidSet(_table: table)) } @inlinable diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift index 12030cbb..1611df94 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Insertions.swift @@ -24,7 +24,7 @@ extension UniqueSet where Element: ~Copyable { return .init(bucket: bucket, remnant: item) } var hashValue = r.hashValue - if _ensureFreeCapacity(1), !_storage._table.isSmall { + if _ensureFreeCapacity(1), !_isSmall { hashValue = _storage._hashValue(for: item) } let bucket = _storage._insertNew(item, hashValue: hashValue) @@ -44,7 +44,7 @@ extension UniqueSet where Element: ~Copyable { ) -> Element? { var r = self._insert(item) guard let remnant = r.remnant.take() else { return nil } - return exchange( + return unsafe exchange( &_storage._memberPtr(at: r.bucket).pointee, with: remnant) } diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet+Removals.swift b/Sources/BasicContainers/UniqueSet/UniqueSet+Removals.swift index 92ef7df9..91707d70 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet+Removals.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet+Removals.swift @@ -16,12 +16,13 @@ @available(SwiftStdlib 5.0, *) extension UniqueSet where Element: ~Copyable { @inlinable + @unsafe package mutating func _remove(at bucket: _Bucket) -> Element { guard self.count <= _HTable.minimumCapacity(forScale: self._scale) else { - return _storage._remove(at: bucket) + return unsafe _storage._remove(at: bucket) } // Shrink storage. - let result = _storage._punchHole(at: bucket) + let result = unsafe _storage._punchHole(at: bucket) _resize(minimumCapacity: self.count) return result } @@ -30,7 +31,7 @@ extension UniqueSet where Element: ~Copyable { public mutating func remove(_ member: borrowing Element) -> Element? { let r = _storage._find(member) guard let bucket = r.bucket else { return nil } - return _remove(at: bucket) + return unsafe _remove(at: bucket) } @inlinable diff --git a/Sources/BasicContainers/UniqueSet/UniqueSet.swift b/Sources/BasicContainers/UniqueSet/UniqueSet.swift index 1f460d07..71e12f2c 100644 --- a/Sources/BasicContainers/UniqueSet/UniqueSet.swift +++ b/Sources/BasicContainers/UniqueSet/UniqueSet.swift @@ -69,7 +69,13 @@ extension UniqueSet where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent public var _scale: UInt8 { - _storage._table.scale + unsafe _storage._table.scale + } + + @_alwaysEmitIntoClient + @_transparent + public var _isSmall: Bool { + _storage._isSmall } } #endif diff --git a/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift index 6ab3a1ab..e9d32e1d 100644 --- a/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift +++ b/Sources/BitCollections/BitArray/BitArray+BitwiseOperations.swift @@ -157,14 +157,14 @@ extension BitArray { extension BitArray { public mutating func toggleAll() { - _update { handle in - let w = handle._mutableWords - for i in 0 ..< handle._words.count { - w[i].formComplement() + unsafe _update { handle in + let w = unsafe handle._mutableWords + for i in unsafe 0 ..< handle._words.count { + unsafe w[i].formComplement() } let p = handle.end if p.bit > 0 { - w[p.word].subtract(_Word(upTo: p.bit).complement()) + unsafe w[p.word].subtract(_Word(upTo: p.bit).complement()) } } _checkInvariants() @@ -173,22 +173,22 @@ extension BitArray { public mutating func toggleAll(in range: Range) { precondition(range.upperBound <= count, "Range out of bounds") guard !range.isEmpty else { return } - _update { handle in - let words = handle._mutableWords + unsafe _update { handle in + let words = unsafe handle._mutableWords let start = _BitPosition(range.lowerBound) let end = _BitPosition(range.upperBound) if start.word == end.word { let bits = _Word(from: start.bit, to: end.bit) - words[start.word].formSymmetricDifference(bits) + unsafe words[start.word].formSymmetricDifference(bits) return } - words[start.word].formSymmetricDifference( + unsafe words[start.word].formSymmetricDifference( _Word(upTo: start.bit).complement()) for i in stride(from: start.word + 1, to: end.word, by: 1) { - words[i].formComplement() + unsafe words[i].formComplement() } if end.bit > 0 { - words[end.word].formSymmetricDifference(_Word(upTo: end.bit)) + unsafe words[end.word].formSymmetricDifference(_Word(upTo: end.bit)) } } } diff --git a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift index 715bb5ab..7a789343 100644 --- a/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift +++ b/Sources/BitCollections/BitArray/BitArray+ChunkedBitsIterators.swift @@ -15,11 +15,14 @@ import InternalCollectionsUtilities #endif +@unsafe internal struct _ChunkedBitsForwardIterator { internal typealias _BitPosition = _UnsafeBitSet.Index internal let words: UnsafeBufferPointer<_Word> + @safe internal let end: _BitPosition + @safe internal var position: _BitPosition internal init( @@ -28,7 +31,7 @@ internal struct _ChunkedBitsForwardIterator { ) { assert(range.lowerBound >= 0) assert(range.upperBound <= words.count * _Word.capacity) - self.words = words + unsafe self.words = words self.end = _BitPosition(range.upperBound) self.position = _BitPosition(range.lowerBound) } @@ -38,7 +41,7 @@ internal struct _ChunkedBitsForwardIterator { let (w, b) = position.split if w == end.word { position = end - return ( + return unsafe ( bits: words[w] .intersection(_Word(upTo: end.bit)) .shiftedDown(by: b), @@ -46,15 +49,18 @@ internal struct _ChunkedBitsForwardIterator { } let c = _Word._capacity - b position.value += c - return (bits: words[w].shiftedDown(by: b), count: c) + return unsafe (bits: words[w].shiftedDown(by: b), count: c) } } +@unsafe internal struct _ChunkedBitsBackwardIterator { internal typealias _BitPosition = _UnsafeBitSet.Index internal let words: UnsafeBufferPointer<_Word> + @safe internal let start: _BitPosition + @safe internal var position: _BitPosition internal init( @@ -63,7 +69,7 @@ internal struct _ChunkedBitsBackwardIterator { ) { assert(range.lowerBound >= 0) assert(range.upperBound <= words.count * _Word.capacity) - self.words = words + unsafe self.words = words self.start = _BitPosition(range.lowerBound) self.position = _BitPosition(range.upperBound) } @@ -73,7 +79,7 @@ internal struct _ChunkedBitsBackwardIterator { let (w, b) = position.endSplit if w == start.word { position = start - return ( + return unsafe ( bits: words[w] .intersection(_Word(upTo: b)) .shiftedDown(by: start.bit), @@ -81,7 +87,7 @@ internal struct _ChunkedBitsBackwardIterator { } let c = b position.value -= c - return (bits: words[w].intersection(_Word(upTo: b)), count: c) + return unsafe (bits: words[w].intersection(_Word(upTo: b)), count: c) } } diff --git a/Sources/BitCollections/BitArray/BitArray+Collection.swift b/Sources/BitCollections/BitArray/BitArray+Collection.swift index 98bfa817..efc79501 100644 --- a/Sources/BitCollections/BitArray/BitArray+Collection.swift +++ b/Sources/BitCollections/BitArray/BitArray+Collection.swift @@ -176,14 +176,14 @@ extension BitArray: RandomAccessCollection, MutableCollection { public subscript(position: Int) -> Bool { get { precondition(position >= 0 && position < _count, "Index out of bounds") - return _read { handle in - handle[position] + return unsafe _read { handle in + unsafe handle[position] } } set { precondition(position >= 0 && position < _count, "Index out of bounds") - return _update { handle in - handle[position] = newValue + return unsafe _update { handle in + unsafe handle[position] = newValue } } } diff --git a/Sources/BitCollections/BitArray/BitArray+Copy.swift b/Sources/BitCollections/BitArray/BitArray+Copy.swift index f40faecb..2fbf72ed 100644 --- a/Sources/BitCollections/BitArray/BitArray+Copy.swift +++ b/Sources/BitCollections/BitArray/BitArray+Copy.swift @@ -20,8 +20,8 @@ extension BitArray { from range: Range, to target: Int ) { - _update { handle in - handle.copy(from: range, to: target) + unsafe _update { handle in + unsafe handle.copy(from: range, to: target) } } @@ -30,8 +30,8 @@ extension BitArray { in source: UnsafeBufferPointer<_Word>, to target: Int ) { - _update { handle in - handle.copy(from: range, in: source, to: target) + unsafe _update { handle in + unsafe handle.copy(from: range, in: source, to: target) } } @@ -48,7 +48,7 @@ extension BitArray { ) { let range = source._bounds source.base._storage.withUnsafeBufferPointer { words in - self._copy(from: range, in: words, to: target) + unsafe self._copy(from: range, in: words, to: target) } } @@ -56,7 +56,7 @@ extension BitArray { from source: S, to range: Range ) where S.Element == Bool { - _update { $0.copy(from: source, to: range) } + unsafe _update { unsafe $0.copy(from: source, to: range) } } } @@ -66,21 +66,21 @@ extension BitArray._UnsafeHandle { ) { assert(count <= _Word.capacity) assert(count == _Word.capacity || bits.shiftedDown(by: count).isEmpty) - assert(target.value + count <= _count) + assert(target.value + count <= self.count) let start = target.split let end = _BitPosition(target.value + count).endSplit - let words = _mutableWords + let words = unsafe _mutableWords if start.word == end.word { let mask = _Word(from: start.bit, to: end.bit) - words[start.word].formIntersection(mask.complement()) - words[start.word].formUnion(bits.shiftedUp(by: start.bit)) + unsafe words[start.word].formIntersection(mask.complement()) + unsafe words[start.word].formUnion(bits.shiftedUp(by: start.bit)) return } assert(start.word + 1 == end.word) - words[start.word].formIntersection(_Word(upTo: start.bit)) - words[start.word].formUnion(bits.shiftedUp(by: start.bit)) - words[end.word].formIntersection(_Word(upTo: end.bit).complement()) - words[end.word].formUnion( + unsafe words[start.word].formIntersection(_Word(upTo: start.bit)) + unsafe words[start.word].formUnion(bits.shiftedUp(by: start.bit)) + unsafe words[end.word].formIntersection(_Word(upTo: end.bit).complement()) + unsafe words[end.word].formUnion( bits.shiftedDown(by: _Word._capacity &- start.bit)) } @@ -91,7 +91,7 @@ extension BitArray._UnsafeHandle { assert( range.lowerBound >= 0 && range.upperBound <= self.count, "Source range out of bounds") - copy(from: range, in: _words, to: target) + unsafe copy(from: range, in: _words, to: target) } internal mutating func copy( @@ -114,17 +114,17 @@ extension BitArray._UnsafeHandle { let upperSource = _BitPosition(range.upperBound).endSplit - let targetPtr = _words._ptr(at: target.word) - let lowerSourcePtr = source._ptr(at: lowerSource.word) - let upperSourcePtr = source._ptr(at: upperSource.word) + let targetPtr = unsafe _words._ptr(at: target.word) + let lowerSourcePtr = unsafe source._ptr(at: lowerSource.word) + let upperSourcePtr = unsafe source._ptr(at: upperSource.word) - if targetPtr < lowerSourcePtr || targetPtr > upperSourcePtr { + if unsafe targetPtr < lowerSourcePtr || targetPtr > upperSourcePtr { return true } - if targetPtr == lowerSourcePtr, target.bit < lowerSource.bit { + if unsafe targetPtr == lowerSourcePtr, target.bit < lowerSource.bit { return true } - if targetPtr == upperSourcePtr, target.bit >= upperSource.bit { + if unsafe targetPtr == upperSourcePtr, target.bit >= upperSource.bit { return true } return false @@ -132,20 +132,20 @@ extension BitArray._UnsafeHandle { if goForward() { // Copy forward from a disjoint or following overlapping range. - var src = _ChunkedBitsForwardIterator(words: source, range: range) + var src = unsafe _ChunkedBitsForwardIterator(words: source, range: range) var dst = _BitPosition(target) - while let (bits, count) = src.next() { - _copy(bits: bits, count: count, to: dst) + while let (bits, count) = unsafe src.next() { + unsafe _copy(bits: bits, count: count, to: dst) dst.value += count } assert(dst.value == target + range.count) } else { // Copy backward from a non-following overlapping range. - var src = _ChunkedBitsBackwardIterator(words: source, range: range) + var src = unsafe _ChunkedBitsBackwardIterator(words: source, range: range) var dst = _BitPosition(target + range.count) - while let (bits, count) = src.next() { + while let (bits, count) = unsafe src.next() { dst.value -= count - _copy(bits: bits, count: count, to: dst) + unsafe _copy(bits: bits, count: count, to: dst) } assert(dst.value == target) } @@ -163,14 +163,14 @@ extension BitArray._UnsafeHandle { if pos.bit > 0 { let (bits, count) = it._nextChunk( maxCount: _Word._capacity - pos.bit) - _copy(bits: bits, count: count, to: pos) + unsafe _copy(bits: bits, count: count, to: pos) pos.value += count } while true { let (bits, count) = it._nextChunk() guard count > 0 else { break } assert(pos.bit == 0) - _copy(bits: bits, count: count, to: pos) + unsafe _copy(bits: bits, count: count, to: pos) pos.value += count } precondition(pos.value == range.upperBound) diff --git a/Sources/BitCollections/BitArray/BitArray+Descriptions.swift b/Sources/BitCollections/BitArray/BitArray+Descriptions.swift index ecb9eb37..09848f3e 100644 --- a/Sources/BitCollections/BitArray/BitArray+Descriptions.swift +++ b/Sources/BitCollections/BitArray/BitArray+Descriptions.swift @@ -66,14 +66,14 @@ extension BitArray { var result: String if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) { result = String(unsafeUninitializedCapacity: self.count + 2) { target in - target.initializeElement(at: count + 1, to: ._asciiGT) + unsafe target.initializeElement(at: count + 1, to: ._asciiGT) var i = count for v in self { - target.initializeElement(at: i, to: v ? ._ascii1 : ._ascii0) + unsafe target.initializeElement(at: i, to: v ? ._ascii1 : ._ascii0) i &-= 1 } assert(i == 0) - target.initializeElement(at: 0, to: ._asciiLT) + unsafe target.initializeElement(at: 0, to: ._asciiLT) return count + 2 } } else { diff --git a/Sources/BitCollections/BitArray/BitArray+Fill.swift b/Sources/BitCollections/BitArray/BitArray+Fill.swift index 38eaa8b2..a150c0ac 100644 --- a/Sources/BitCollections/BitArray/BitArray+Fill.swift +++ b/Sources/BitCollections/BitArray/BitArray+Fill.swift @@ -16,7 +16,7 @@ extension BitArray { /// /// - Parameter value: The Boolean value to which to set the array's elements. public mutating func fill(with value: Bool = true) { - fill(in: Range(uncheckedBounds: (0, count)), with: value) + fill(in: unsafe Range(uncheckedBounds: (0, count)), with: value) } /// Set every bit of this array within the specified range to `value` @@ -25,11 +25,11 @@ extension BitArray { /// - Parameter range: The range whose elements to overwrite. /// - Parameter value: The Boolean value to which to set the array's elements. public mutating func fill(in range: Range, with value: Bool = true) { - _update { handle in + unsafe _update { handle in if value { - handle.fill(in: range) + unsafe handle.fill(in: range) } else { - handle.clear(in: range) + unsafe handle.clear(in: range) } } } diff --git a/Sources/BitCollections/BitArray/BitArray+Initializers.swift b/Sources/BitCollections/BitArray/BitArray+Initializers.swift index bd7958d7..1204766f 100644 --- a/Sources/BitCollections/BitArray/BitArray+Initializers.swift +++ b/Sources/BitCollections/BitArray/BitArray+Initializers.swift @@ -75,13 +75,13 @@ extension BitArray { isSigned: Bool, body: (Int, UInt) -> Bool ) -> Bool { - self._read { - guard $0._words.count > 0 else { return false } + unsafe self._read { + guard unsafe $0._words.count > 0 else { return false } var isNegative = false let end = $0.end.endSplit assert(end.bit > 0) - let last = $0._words[end.word] + let last = unsafe $0._words[end.word] if isSigned, last.contains(end.bit - 1) { // Sign extend last word isNegative = true @@ -92,7 +92,7 @@ extension BitArray { return isNegative } for i in stride(from: end.word - 1, through: 0, by: -1) { - if !body(i, $0._words[i].value) { return isNegative } + if unsafe !body(i, $0._words[i].value) { return isNegative } } return isNegative } diff --git a/Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift b/Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift index c9317330..5234cdd7 100644 --- a/Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift +++ b/Sources/BitCollections/BitArray/BitArray+LosslessStringConvertible.swift @@ -38,8 +38,8 @@ extension BitArray: LosslessStringConvertible { if digits.utf8.first == ._asciiLT, digits.utf8.last == ._asciiGT { digits = digits.dropFirst().dropLast() } - let bits: BitArray? = digits.utf8.withContiguousStorageIfAvailable { buffer in - Self(_utf8Digits: buffer) + let bits: BitArray? = unsafe digits.utf8.withContiguousStorageIfAvailable { buffer in + unsafe Self(_utf8Digits: buffer) } ?? Self(_utf8Digits: description.utf8) guard let bits = bits else { return nil @@ -51,10 +51,10 @@ extension BitArray: LosslessStringConvertible { let c = utf8.count self.init(repeating: false, count: c) var i = c &- 1 - let success = _update { handle in + let success = unsafe _update { handle in for byte in utf8 { if byte == ._ascii1 { - handle.set(at: i) + unsafe handle.set(at: i) } else { guard byte == ._ascii0 else { return false } } diff --git a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift index 7cf20ac8..f9374719 100644 --- a/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift +++ b/Sources/BitCollections/BitArray/BitArray+RangeReplaceableCollection.swift @@ -251,8 +251,8 @@ extension BitArray { } _count += 1 if newElement { - _update { handle in - handle._mutableWords[word].value |= 1 &<< bit + unsafe _update { handle in + unsafe handle._mutableWords[word].value |= 1 &<< bit } } _checkInvariants() @@ -288,7 +288,7 @@ extension BitArray { maxCount: _Word._capacity - pos.bit) guard count > 0 else { return } _count += count - _update { $0._copy(bits: bits, count: count, to: pos) } + unsafe _update { unsafe $0._copy(bits: bits, count: count, to: pos) } pos.value += count } while true { @@ -297,7 +297,7 @@ extension BitArray { assert(pos.bit == 0) _storage.append(.empty) _count += count - _update { $0._copy(bits: bits, count: count, to: pos) } + unsafe _update { unsafe $0._copy(bits: bits, count: count, to: pos) } pos.value += count } _checkInvariants() @@ -363,9 +363,9 @@ extension BitArray { } let c = count _count += 1 - _update { handle in - handle.copy(from: i ..< c, to: i + 1) - handle[i] = newElement + unsafe _update { handle in + unsafe handle.copy(from: i ..< c, to: i + 1) + unsafe handle[i] = newElement } _checkInvariants() } @@ -484,7 +484,7 @@ extension BitArray { range.lowerBound >= 0 && range.upperBound <= count, "Bounds out of range") _copy( - from: Range(uncheckedBounds: (range.upperBound, count)), + from: unsafe Range(uncheckedBounds: (range.upperBound, count)), to: range.lowerBound) _removeLast(range.count) _checkInvariants() diff --git a/Sources/BitCollections/BitArray/BitArray+Shifts.swift b/Sources/BitCollections/BitArray/BitArray+Shifts.swift index 9ff20c00..0693d17b 100644 --- a/Sources/BitCollections/BitArray/BitArray+Shifts.swift +++ b/Sources/BitCollections/BitArray/BitArray+Shifts.swift @@ -74,7 +74,7 @@ extension BitArray { self = .init() return } - self._copy(from: Range(uncheckedBounds: (amount, count)), to: 0) + self._copy(from: unsafe Range(uncheckedBounds: (amount, count)), to: 0) self._removeLast(count &- amount) } } @@ -102,11 +102,11 @@ extension BitArray { /// // bits is now 0000000 public mutating func maskingShiftLeft(by amount: Int) { guard amount != 0 else { return } - _update { + unsafe _update { if amount > 0 { - $0._maskingShiftLeft(by: amount) + unsafe $0._maskingShiftLeft(by: amount) } else { - $0._maskingShiftRight(by: -amount) + unsafe $0._maskingShiftRight(by: -amount) } } } @@ -131,11 +131,11 @@ extension BitArray { /// // bits is now 0000000 public mutating func maskingShiftRight(by amount: Int) { guard amount != 0 else { return } - _update { + unsafe _update { if amount > 0 { - $0._maskingShiftRight(by: amount) + unsafe $0._maskingShiftRight(by: amount) } else { - $0._maskingShiftLeft(by: -amount) + unsafe $0._maskingShiftLeft(by: -amount) } } } @@ -146,19 +146,19 @@ extension BitArray._UnsafeHandle { assert(amount > 0) let d = Swift.min(amount, self.count) if d == amount { - let range = Range(uncheckedBounds: (0, self.count &- d)) - self.copy(from: range, to: d) + let range = unsafe Range(uncheckedBounds: (0, self.count &- d)) + unsafe self.copy(from: range, to: d) } - self.clear(in: Range(uncheckedBounds: (0, d))) + unsafe self.clear(in: Range(uncheckedBounds: (0, d))) } internal mutating func _maskingShiftRight(by amount: Int) { assert(amount > 0) let d = Swift.min(amount, self.count) if d == amount { - let range = Range(uncheckedBounds: (d, self.count)) - self.copy(from: range, to: 0) + let range = unsafe Range(uncheckedBounds: (d, self.count)) + unsafe self.copy(from: range, to: 0) } - self.clear(in: Range(uncheckedBounds: (self.count &- d, self.count))) + unsafe self.clear(in: Range(uncheckedBounds: (self.count &- d, self.count))) } } diff --git a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift index 0e441831..a08f01ae 100644 --- a/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift +++ b/Sources/BitCollections/BitArray/BitArray._UnsafeHandle.swift @@ -20,24 +20,29 @@ extension BitArray { /// primitives. @usableFromInline @frozen + @unsafe internal struct _UnsafeHandle { @usableFromInline internal typealias _BitPosition = _UnsafeBitSet.Index @usableFromInline + @unsafe internal let _words: UnsafeBufferPointer<_Word> @usableFromInline + @unsafe // Setter internal var _count: UInt #if DEBUG /// True when this handle does not support table mutations. /// (This is only checked in debug builds.) @usableFromInline + @safe internal let _mutable: Bool #endif @inline(__always) + @safe internal func ensureMutable() { #if DEBUG assert(_mutable) @@ -46,7 +51,7 @@ extension BitArray { internal var _mutableWords: UnsafeMutableBufferPointer<_Word> { ensureMutable() - return UnsafeMutableBufferPointer(mutating: _words) + return unsafe UnsafeMutableBufferPointer(mutating: _words) } @inlinable @@ -58,8 +63,8 @@ extension BitArray { ) { assert(count <= words.count * _Word.capacity) assert(count > (words.count - 1) * _Word.capacity) - self._words = words - self._count = count + unsafe self._words = words + unsafe self._count = count #if DEBUG self._mutable = mutable #endif @@ -72,7 +77,7 @@ extension BitArray { count: UInt, mutable: Bool ) { - self.init( + unsafe self.init( words: UnsafeBufferPointer(words), count: count, mutable: mutable) @@ -81,42 +86,45 @@ extension BitArray { } extension BitArray._UnsafeHandle { + @safe + @_transparent internal var count: Int { - Int(_count) + unsafe Int(_count) } + @safe internal var end: _BitPosition { - _BitPosition(_count) + unsafe _BitPosition(_count) } internal func set(at position: Int) { ensureMutable() - assert(position >= 0 && position < _count) + assert(position >= 0 && position < count) let (word, bit) = _BitPosition(UInt(position)).split - _mutableWords[word].insert(bit) + unsafe _mutableWords[word].insert(bit) } internal func clear(at position: Int) { ensureMutable() - assert(position >= 0 && position < _count) + assert(position >= 0 && position < count) let (word, bit) = _BitPosition(UInt(position)).split - _mutableWords[word].remove(bit) + unsafe _mutableWords[word].remove(bit) } internal subscript(position: Int) -> Bool { get { - assert(position >= 0 && position < _count) + assert(position >= 0 && position < count) let (word, bit) = _BitPosition(UInt(position)).split - return _words[word].contains(bit) + return unsafe _words[word].contains(bit) } set { ensureMutable() - assert(position >= 0 && position < _count) + assert(position >= 0 && position < count) let (word, bit) = _BitPosition(UInt(position)).split if newValue { - _mutableWords[word].insert(bit) + unsafe _mutableWords[word].insert(bit) } else { - _mutableWords[word].remove(bit) + unsafe _mutableWords[word].remove(bit) } } } @@ -131,16 +139,16 @@ extension BitArray._UnsafeHandle { guard range.count > 0 else { return } let (lw, lb) = _BitPosition(range.lowerBound).split let (uw, ub) = _BitPosition(range.upperBound).endSplit - let words = _mutableWords + let words = unsafe _mutableWords guard lw != uw else { - words[lw].formUnion(_Word(from: lb, to: ub)) + unsafe words[lw].formUnion(_Word(from: lb, to: ub)) return } - words[lw].formUnion(_Word(upTo: lb).complement()) + unsafe words[lw].formUnion(_Word(upTo: lb).complement()) for w in lw + 1 ..< uw { - words[w] = _Word.allBits + unsafe words[w] = _Word.allBits } - words[uw].formUnion(_Word(upTo: ub)) + unsafe words[uw].formUnion(_Word(upTo: ub)) } internal mutating func clear(in range: Range) { @@ -151,15 +159,15 @@ extension BitArray._UnsafeHandle { guard range.count > 0 else { return } let (lw, lb) = _BitPosition(range.lowerBound).split let (uw, ub) = _BitPosition(range.upperBound).endSplit - let words = _mutableWords + let words = unsafe _mutableWords guard lw != uw else { - words[lw].subtract(_Word(from: lb, to: ub)) + unsafe words[lw].subtract(_Word(from: lb, to: ub)) return } - words[lw].subtract(_Word(upTo: lb).complement()) + unsafe words[lw].subtract(_Word(upTo: lb).complement()) for w in lw + 1 ..< uw { - words[w] = _Word.empty + unsafe words[w] = _Word.empty } - words[uw].subtract(_Word(upTo: ub)) + unsafe words[uw].subtract(_Word(upTo: ub)) } } diff --git a/Sources/BitCollections/BitArray/BitArray.swift b/Sources/BitCollections/BitArray/BitArray.swift index bc9583d5..f417f7f6 100644 --- a/Sources/BitCollections/BitArray/BitArray.swift +++ b/Sources/BitCollections/BitArray/BitArray.swift @@ -24,6 +24,7 @@ import InternalCollectionsUtilities /// See `BitSet` for an alternative form of the same underlying data /// structure, treating it as a set of nonnegative integers corresponding to /// `true` bits. +@safe public struct BitArray { @usableFromInline internal typealias _BitPosition = _UnsafeBitSet.Index @@ -58,9 +59,9 @@ extension BitArray { _ body: (_UnsafeHandle) throws -> R ) rethrows -> R { try _storage.withUnsafeBufferPointer { words in - let handle = _UnsafeHandle( + let handle = unsafe _UnsafeHandle( words: words, count: _count, mutable: false) - return try body(handle) + return unsafe try body(handle) } } @@ -72,8 +73,8 @@ extension BitArray { _checkInvariants() } return try _storage.withUnsafeMutableBufferPointer { words in - var handle = _UnsafeHandle(words: words, count: _count, mutable: true) - return try body(&handle) + var handle = unsafe _UnsafeHandle(words: words, count: _count, mutable: true) + return unsafe try body(&handle) } } diff --git a/Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift b/Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift index 144793cf..bcec2800 100644 --- a/Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift +++ b/Sources/BitCollections/BitSet/BitSet+BidirectionalCollection.swift @@ -66,9 +66,9 @@ extension BitSet: Sequence { internal init(_ bitset: BitSet) { self.bitset = bitset self.index = 0 - self.word = bitset._read { handle in + self.word = unsafe bitset._read { handle in guard handle.wordCount > 0 else { return .empty } - return handle._words[0] + return unsafe handle._words[0] } } @@ -77,10 +77,10 @@ extension BitSet: Sequence { self.bitset = _bitset let (word, bit) = start._position.split self.index = word - self.word = bitset._read { handle in + self.word = unsafe bitset._read { handle in precondition(word <= handle.wordCount, "Invalid index") guard word < handle.wordCount else { return .empty } - var w = handle._words[word] + var w = unsafe handle._words[word] w.removeAll(upTo: bit) return w } @@ -103,10 +103,10 @@ extension BitSet: Sequence { let i = _UnsafeHandle.Index(word: index, bit: bit) return Int(truncatingIfNeeded: i.value) } - return bitset._read { handle in + return unsafe bitset._read { handle in while (index + 1) < handle.wordCount { index += 1 - word = handle._words[index] + word = unsafe handle._words[index] if let bit = word.next() { let i = _UnsafeHandle.Index(word: index, bit: bit) return Int(truncatingIfNeeded: i.value) @@ -135,7 +135,7 @@ extension BitSet: Collection, BidirectionalCollection { /// - Note: `BitSet.Counted` is a variant of this type that keeps a running /// total of its element count, for use cases that require an O(1) count. public var count: Int { - return _read { $0.count } + return unsafe _read { unsafe $0.count } } /// The position of the first element in a nonempty set, or `endIndex` @@ -143,7 +143,7 @@ extension BitSet: Collection, BidirectionalCollection { /// /// - Complexity: O(*min*) where *min* is the value of the first element. public var startIndex: Index { - Index(_position: _read { $0.startIndex }) + Index(_position: unsafe _read { unsafe $0.startIndex }) } /// The collection's "past the end" position--that is, the position one step @@ -185,9 +185,9 @@ extension BitSet: Collection, BidirectionalCollection { /// (Each call needs to search for the next `true` bit in the underlying /// storage.) public func index(after index: Index) -> Index { - _read { handle in - assert(handle._isReachable(index._position), "Invalid index") - let pos = handle.index(after: index._position) + unsafe _read { handle in + assert(unsafe handle._isReachable(index._position), "Invalid index") + let pos = unsafe handle.index(after: index._position) return Index(_position: pos) } } @@ -205,9 +205,9 @@ extension BitSet: Collection, BidirectionalCollection { /// (Each call needs to search for the next `true` bit in the underlying /// storage.) public func index(before index: Index) -> Index { - _read { handle in - assert(handle._isReachable(index._position), "Invalid index") - let pos = handle.index(before: index._position) + unsafe _read { handle in + assert(unsafe handle._isReachable(index._position), "Invalid index") + let pos = unsafe handle.index(before: index._position) return Index(_position: pos) } } @@ -223,10 +223,10 @@ extension BitSet: Collection, BidirectionalCollection { /// - Complexity: O(*d*), where *d* is the difference of the values /// addressed by the two input indices. public func distance(from start: Index, to end: Index) -> Int { - _read { handle in - assert(handle._isReachable(start._position), "Invalid start index") - assert(handle._isReachable(end._position), "Invalid end index") - return handle.distance(from: start._position, to: end._position) + unsafe _read { handle in + assert(unsafe handle._isReachable(start._position), "Invalid start index") + assert(unsafe handle._isReachable(end._position), "Invalid end index") + return unsafe handle.distance(from: start._position, to: end._position) } } @@ -247,9 +247,9 @@ extension BitSet: Collection, BidirectionalCollection { /// - Complexity: O(*d*), where *d* is the difference of the values /// addressed by `index` and the returned result. public func index(_ index: Index, offsetBy distance: Int) -> Index { - _read { handle in - assert(handle._isReachable(index._position), "Invalid index") - let pos = handle.index(index._position, offsetBy: distance) + unsafe _read { handle in + assert(unsafe handle._isReachable(index._position), "Invalid index") + let pos = unsafe handle.index(index._position, offsetBy: distance) return Index(_position: pos) } } @@ -277,10 +277,10 @@ extension BitSet: Collection, BidirectionalCollection { public func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { - _read { handle in - assert(handle._isReachable(i._position), "Invalid index") - assert(handle._isReachable(limit._position), "Invalid limit index") - return handle.index( + unsafe _read { handle in + assert(unsafe handle._isReachable(i._position), "Invalid index") + assert(unsafe handle._isReachable(limit._position), "Invalid limit index") + return unsafe handle.index( i._position, offsetBy: distance, limitedBy: limit._position ).map { Index(_position: $0) } } diff --git a/Sources/BitCollections/BitSet/BitSet+Extras.swift b/Sources/BitCollections/BitSet/BitSet+Extras.swift index 28d2b777..629afdba 100644 --- a/Sources/BitCollections/BitSet/BitSet+Extras.swift +++ b/Sources/BitCollections/BitSet/BitSet+Extras.swift @@ -76,8 +76,8 @@ extension BitSet { } else if member >= _capacity { return } - _updateThenShrink { handle, shrink in - shrink = handle.update(member, to: newValue) + unsafe _updateThenShrink { handle, shrink in + shrink = unsafe handle.update(member, to: newValue) } } } @@ -98,27 +98,27 @@ extension BitSet { /// /// - Complexity: Equivalent to two invocations of `index(after:)`. public subscript(members bounds: Range) -> Slice { - let bounds: Range = _read { handle in + let bounds: Range = unsafe _read { handle in let bounds = bounds._clampedToUInt() var lower = _UnsafeBitSet.Index(bounds.lowerBound) if lower >= handle.endIndex { lower = handle.endIndex - } else if !handle.contains(lower.value) { - lower = handle.index(after: lower) + } else if unsafe !handle.contains(lower.value) { + lower = unsafe handle.index(after: lower) } - assert(lower == handle.endIndex || handle.contains(lower.value)) + assert(unsafe lower == handle.endIndex || handle.contains(lower.value)) var upper = _UnsafeBitSet.Index(bounds.upperBound) if upper <= lower { upper = lower } else if upper >= handle.endIndex { upper = handle.endIndex - } else if !handle.contains(upper.value) { - upper = handle.index(after: upper) + } else if unsafe !handle.contains(upper.value) { + upper = unsafe handle.index(after: upper) } - assert(upper == handle.endIndex || handle.contains(upper.value)) + assert(unsafe upper == handle.endIndex || handle.contains(upper.value)) assert(lower <= upper) - return Range( + return unsafe Range( uncheckedBounds: (Index(_position: lower), Index(_position: upper))) } return Slice(base: self, bounds: bounds) @@ -187,10 +187,10 @@ extension BitSet { ) rethrows -> Self { var words = [_Word](repeating: .empty, count: _storage.count) try words.withUnsafeMutableBufferPointer { buffer in - var target = _UnsafeHandle(words: buffer, mutable: true) + var target = unsafe _UnsafeHandle(words: buffer, mutable: true) for i in self { guard try isIncluded(i) else { continue } - target.insert(UInt(i)) + unsafe target.insert(UInt(i)) } } return BitSet(_words: words) diff --git a/Sources/BitCollections/BitSet/BitSet+Initializers.swift b/Sources/BitCollections/BitSet/BitSet+Initializers.swift index 871c5b54..ca74ff5b 100644 --- a/Sources/BitCollections/BitSet/BitSet+Initializers.swift +++ b/Sources/BitCollections/BitSet/BitSet+Initializers.swift @@ -186,31 +186,31 @@ extension BitSet { includingTail: Bool, using function: (_Word, _Word) -> _Word ) { - let w1 = handles.0._words - let w2 = handles.1._words + let w1 = unsafe handles.0._words + let w2 = unsafe handles.1._words let capacity = ( includingTail ? Swift.max(w1.count, w2.count) : Swift.min(w1.count, w2.count)) - _storage = Array(unsafeUninitializedCapacity: capacity) { buffer, count in + _storage = unsafe Array(unsafeUninitializedCapacity: capacity) { buffer, count in let sharedCount = Swift.min(w1.count, w2.count) for w in 0 ..< sharedCount { - buffer.initializeElement(at: w, to: function(w1[w], w2[w])) + unsafe buffer.initializeElement(at: w, to: function(w1[w], w2[w])) } if includingTail { if w1.count < w2.count { for w in w1.count ..< w2.count { - buffer.initializeElement(at: w, to: function(_Word.empty, w2[w])) + unsafe buffer.initializeElement(at: w, to: function(_Word.empty, w2[w])) } } else { for w in w2.count ..< w1.count { - buffer.initializeElement(at: w, to: function(w1[w], _Word.empty)) + unsafe buffer.initializeElement(at: w, to: function(w1[w], _Word.empty)) } } } // Adjust the word count based on results. count = capacity - while count > 0, buffer[count - 1].isEmpty { + while count > 0, unsafe buffer[count - 1].isEmpty { count -= 1 } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift index cf072058..921e7cbc 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra basics.swift @@ -26,7 +26,7 @@ extension BitSet { /// - Complexity: O(1) @usableFromInline internal func _contains(_ member: UInt) -> Bool { - _read { $0.contains(member) } + unsafe _read { unsafe $0.contains(member) } } /// Returns a Boolean value that indicates whether the given element exists @@ -64,7 +64,7 @@ extension BitSet { @usableFromInline internal mutating func _insert(_ newMember: UInt) -> Bool { _ensureCapacity(forValue: newMember) - return _update { $0.insert(newMember) } + return unsafe _update { unsafe $0.insert(newMember) } } /// Inserts the given element in the set if it is not already present. @@ -114,8 +114,8 @@ extension BitSet { @discardableResult @usableFromInline internal mutating func _remove(_ member: UInt) -> Bool { - _updateThenShrink { handle, shrink in - shrink = handle.remove(member) + unsafe _updateThenShrink { handle, shrink in + shrink = unsafe handle.remove(member) return shrink } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift index 4598cf17..be798cae 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formIntersection.swift @@ -27,12 +27,12 @@ extension BitSet { /// /// - Complexity: O(*max*), where *max* is the largest item in either set. public mutating func formIntersection(_ other: BitSet) { - other._read { source in + unsafe other._read { source in if source.wordCount < _storage.count { self._storage.removeLast(_storage.count - source.wordCount) } - _updateThenShrink { target, shrink in - target.combineSharedPrefix( + unsafe _updateThenShrink { target, shrink in + unsafe target.combineSharedPrefix( with: source, using: { $0.formIntersection($1) }) } } @@ -71,8 +71,8 @@ extension BitSet { if _storage.count - lastWord - 1 > 0 { _storage.removeLast(_storage.count - lastWord - 1) } - _updateThenShrink { handle, shrink in - handle.formIntersection(other) + unsafe _updateThenShrink { handle, shrink in + unsafe handle.formIntersection(other) } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift index ee0aad9a..3e79b42c 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formSymmetricDifference.swift @@ -29,9 +29,9 @@ extension BitSet { /// - Complexity: O(*max*), where *max* is the largest item in either set. public mutating func formSymmetricDifference(_ other: BitSet) { _ensureCapacity(limit: other._capacity) - _updateThenShrink { target, shrink in - other._read { source in - target.combineSharedPrefix( + unsafe _updateThenShrink { target, shrink in + unsafe other._read { source in + unsafe target.combineSharedPrefix( with: source, using: { $0.formSymmetricDifference($1) }) } } @@ -68,8 +68,8 @@ extension BitSet { } guard !other.isEmpty else { return } _ensureCapacity(limit: other.upperBound) - _updateThenShrink { handle, shrink in - handle.formSymmetricDifference(other) + unsafe _updateThenShrink { handle, shrink in + unsafe handle.formSymmetricDifference(other) } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift index 0d7c6d2c..311529b4 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra formUnion.swift @@ -28,9 +28,9 @@ extension BitSet { /// - Complexity: O(*max*), where *max* is the largest item in either input. public mutating func formUnion(_ other: BitSet) { _ensureCapacity(limit: other._capacity) - _update { target in - other._read { source in - target.combineSharedPrefix(with: source) { $0.formUnion($1) } + unsafe _update { target in + unsafe other._read { source in + unsafe target.combineSharedPrefix(with: source) { $0.formUnion($1) } } } } @@ -64,8 +64,8 @@ extension BitSet { } guard !other.isEmpty else { return } _ensureCapacity(limit: other.upperBound) - _update { handle in - handle.formUnion(other) + unsafe _update { handle in + unsafe handle.formUnion(other) } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift index 49c1f46e..9e278b4f 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra intersection.swift @@ -28,9 +28,9 @@ extension BitSet { /// /// - Complexity: O(*max*), where *max* is the largest item in either set. public func intersection(_ other: BitSet) -> BitSet { - self._read { first in - other._read { second in - Self( + unsafe self._read { first in + unsafe other._read { second in + unsafe Self( _combining: (first, second), includingTail: false, using: { $0.intersection($1) }) diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift index a980ad2b..9913c1b7 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isDisjoint.swift @@ -30,12 +30,12 @@ extension BitSet { /// /// - Complexity: O(*max*), where *max* is the largest item in either input. public func isDisjoint(with other: BitSet) -> Bool { - self._read { first in - other._read { second in - let w1 = first._words - let w2 = second._words + unsafe self._read { first in + unsafe other._read { second in + let w1 = unsafe first._words + let w2 = unsafe second._words for i in 0 ..< Swift.min(w1.count, w2.count) { - if !w1[i].intersection(w2[i]).isEmpty { return false } + if unsafe !w1[i].intersection(w2[i]).isEmpty { return false } } return true } @@ -72,7 +72,7 @@ extension BitSet { /// /// - Complexity: O(*max*), where *max* is the largest item in `self`. public func isDisjoint(with other: Range) -> Bool { - _read { $0.isDisjoint(with: other._clampedToUInt()) } + unsafe _read { unsafe $0.isDisjoint(with: other._clampedToUInt()) } } /// Returns a Boolean value that indicates whether the set has no members in diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift index ea65622b..a14b3aba 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isEqualSet.swift @@ -43,7 +43,7 @@ extension BitSet { public func isEqualSet(to other: Range) -> Bool { if other.isEmpty { return isEmpty } guard let other = other._toUInt() else { return false } - return _read { $0.isEqualSet(to: other) } + return unsafe _read { unsafe $0.isEqualSet(to: other) } } /// Returns a Boolean value indicating whether this bit set contains the same diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift index 6af9fa56..cfe77c6d 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSubset.swift @@ -37,19 +37,19 @@ extension BitSet { /// /// - Complexity: O(*max*), where *max* is the largest item in `self`. public func isStrictSubset(of other: BitSet) -> Bool { - self._read { first in - other._read { second in - let w1 = first._words - let w2 = second._words + unsafe self._read { first in + unsafe other._read { second in + let w1 = unsafe first._words + let w2 = unsafe second._words if w1.count > w2.count { return false } var strict = w1.count < w2.count for i in 0 ..< w1.count { - if !w1[i].subtracting(w2[i]).isEmpty { + if unsafe !w1[i].subtracting(w2[i]).isEmpty { return false } - strict = strict || w1[i] != w2[i] + strict = unsafe strict || w1[i] != w2[i] } return strict } @@ -133,7 +133,7 @@ extension BitSet { } let selfCount = self.count - return _UnsafeHandle.withTemporaryBitSet( + return unsafe _UnsafeHandle.withTemporaryBitSet( wordCount: _storage.count ) { seen in var strict = false @@ -144,7 +144,7 @@ extension BitSet { strict = true continue } - if seen.insert(UInt(i)) { + if unsafe seen.insert(UInt(i)) { c &+= 1 if c == selfCount { while !strict, let i = it.next() { diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift index e2acac2a..2651906c 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isStrictSuperset.swift @@ -82,7 +82,7 @@ extension BitSet { return false } guard let r = other._toUInt() else { return false } - return _read { $0.isSuperset(of: r) } + return unsafe _read { unsafe $0.isSuperset(of: r) } } /// Returns a Boolean value that indicates whether this set is a strict @@ -118,14 +118,14 @@ extension BitSet { if let other = _specialize(other, for: Range.self) { return isStrictSuperset(of: other) } - return _UnsafeHandle.withTemporaryBitSet( + return unsafe _UnsafeHandle.withTemporaryBitSet( wordCount: _storage.count ) { seen in for i in other { guard contains(i) else { return false } - seen.insert(UInt(i)) + unsafe seen.insert(UInt(i)) } - return !_storage.elementsEqual(seen._words) + return unsafe !_storage.elementsEqual(seen._words) } } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSubset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSubset.swift index 98dd619d..5cacb26b 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSubset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSubset.swift @@ -35,15 +35,15 @@ extension BitSet { /// /// - Complexity: O(*max*), where *max* is the largest item in `self`. public func isSubset(of other: BitSet) -> Bool { - self._read { first in - other._read { second in - let w1 = first._words - let w2 = second._words + unsafe self._read { first in + unsafe other._read { second in + let w1 = unsafe first._words + let w2 = unsafe second._words if w1.count > w2.count { return false } for i in 0 ..< w1.count { - if !w1[i].subtracting(w2[i]).isEmpty { + if unsafe !w1[i].subtracting(w2[i]).isEmpty { return false } } @@ -84,7 +84,7 @@ extension BitSet { /// /// - Complexity: O(*max*), where *max* is the largest item in `self`. public func isSubset(of other: Range) -> Bool { - _read { $0.isSubset(of: other._clampedToUInt()) } + unsafe _read { unsafe $0.isSubset(of: other._clampedToUInt()) } } /// Returns a Boolean value that indicates whether this set is a subset of diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift index db6aede5..817ee53f 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra isSuperset.swift @@ -71,7 +71,7 @@ extension BitSet { public func isSuperset(of other: Range) -> Bool { if other.isEmpty { return true } guard let r = other._toUInt() else { return false } - return _read { $0.isSuperset(of: r) } + return unsafe _read { unsafe $0.isSuperset(of: r) } } /// Returns a Boolean value that indicates whether this set is a superset of diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift index fc8d0e49..edfea898 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtract.swift @@ -27,9 +27,9 @@ extension BitSet { /// /// - Complexity: O(*max*), where *max* is the largest item in either input. public mutating func subtract(_ other: BitSet) { - _updateThenShrink { target, shrink in - other._read { source in - target.combineSharedPrefix( + unsafe _updateThenShrink { target, shrink in + unsafe other._read { source in + unsafe target.combineSharedPrefix( with: source, using: { $0.subtract($1) } ) @@ -67,8 +67,8 @@ extension BitSet { @usableFromInline internal mutating func _subtract(_ other: Range) { guard !other.isEmpty else { return } - _updateThenShrink { handle, shrink in - handle.subtract(other) + unsafe _updateThenShrink { handle, shrink in + unsafe handle.subtract(other) } } @@ -110,9 +110,9 @@ extension BitSet { @usableFromInline internal mutating func _subtract(_ next: () -> UInt?) { - _updateThenShrink { handle, shrink in + unsafe _updateThenShrink { handle, shrink in while let value = next() { - handle.remove(value) + unsafe handle.remove(value) } } } diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift index ef1f81df..8a07a186 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra subtracting.swift @@ -29,9 +29,9 @@ extension BitSet { /// /// - Complexity: O(*max*), where *max* is the largest item in either input. public func subtracting(_ other: BitSet) -> BitSet { - self._read { first in - other._read { second in - Self( + unsafe self._read { first in + unsafe other._read { second in + unsafe Self( _combining: (first, second), includingTail: true, using: { $0.subtracting($1) }) diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift index f47ca296..b5472eb8 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra symmetricDifference.swift @@ -29,9 +29,9 @@ extension BitSet { /// /// - Complexity: O(*max*), where *max* is the largest item in either set. public func symmetricDifference(_ other: BitSet) -> BitSet { - self._read { first in - other._read { second in - Self( + unsafe self._read { first in + unsafe other._read { second in + unsafe Self( _combining: (first, second), includingTail: true, using: { $0.symmetricDifference($1) }) diff --git a/Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift b/Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift index affcccc0..fbb65a70 100644 --- a/Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift +++ b/Sources/BitCollections/BitSet/BitSet+SetAlgebra union.swift @@ -26,9 +26,9 @@ extension BitSet { /// /// - Complexity: O(*max*), where *max* is the largest item in either input. public func union(_ other: BitSet) -> BitSet { - self._read { first in - other._read { second in - Self( + unsafe self._read { first in + unsafe other._read { second in + unsafe Self( _combining: (first, second), includingTail: true, using: { $0.union($1) }) diff --git a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift index 2680cffb..5b873d8c 100644 --- a/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift +++ b/Sources/BitCollections/BitSet/BitSet._UnsafeHandle.swift @@ -23,14 +23,14 @@ extension BitSet { extension _UnsafeBitSet { @inline(__always) internal func _isReachable(_ index: Index) -> Bool { - index == endIndex || contains(index.value) + unsafe index == endIndex || contains(index.value) } } extension _UnsafeBitSet { internal func _emptySuffix() -> Int { var i = wordCount - 1 - while i >= 0, _words[i].isEmpty { + while i >= 0, unsafe _words[i].isEmpty { i -= 1 } return wordCount - 1 - i @@ -46,7 +46,7 @@ extension _UnsafeBitSet { ensureMutable() let c = Swift.min(self.wordCount, other.wordCount) for w in 0 ..< c { - function(&self._mutableWords[w], other._words[w]) + unsafe function(&self._mutableWords[w], other._words[w]) } } } @@ -62,15 +62,15 @@ extension _UnsafeBitSet { if l.word == u.word { guard l.word < wordCount else { return } let w = _Word(from: l.bit, to: u.bit) - _mutableWords[l.word].formUnion(w) + unsafe _mutableWords[l.word].formUnion(w) return } - _mutableWords[l.word].formUnion(_Word(upTo: l.bit).complement()) + unsafe _mutableWords[l.word].formUnion(_Word(upTo: l.bit).complement()) for w in l.word + 1 ..< u.word { - _mutableWords[w] = .allBits + unsafe _mutableWords[w] = .allBits } if u.word < wordCount { - _mutableWords[u.word].formUnion(_Word(upTo: u.bit)) + unsafe _mutableWords[u.word].formUnion(_Word(upTo: u.bit)) } } @@ -81,21 +81,21 @@ extension _UnsafeBitSet { let u = Index(Swift.min(range.upperBound, capacity)) for w in 0 ..< l.word { - _mutableWords[w] = .empty + unsafe _mutableWords[w] = .empty } if l.word == u.word { guard l.word < wordCount else { return } let w = _Word(from: l.bit, to: u.bit) - _mutableWords[l.word].formIntersection(w) + unsafe _mutableWords[l.word].formIntersection(w) return } - _mutableWords[l.word].formIntersection(_Word(upTo: l.bit).complement()) + unsafe _mutableWords[l.word].formIntersection(_Word(upTo: l.bit).complement()) if u.word < wordCount { - _mutableWords[u.word].formIntersection(_Word(upTo: u.bit)) - _mutableWords[(u.word + 1)...].update(repeating: .empty) + unsafe _mutableWords[u.word].formIntersection(_Word(upTo: u.bit)) + unsafe _mutableWords[(u.word + 1)...].update(repeating: .empty) } } @@ -109,16 +109,16 @@ extension _UnsafeBitSet { if l.word == u.word { guard l.word < wordCount else { return } let w = _Word(from: l.bit, to: u.bit) - _mutableWords[l.word].formSymmetricDifference(w) + unsafe _mutableWords[l.word].formSymmetricDifference(w) return } - _mutableWords[l.word] + unsafe _mutableWords[l.word] .formSymmetricDifference(_Word(upTo: l.bit).complement()) for w in l.word + 1 ..< u.word { - _mutableWords[w].formComplement() + unsafe _mutableWords[w].formComplement() } if u.word < wordCount { - _mutableWords[u.word].formSymmetricDifference(_Word(upTo: u.bit)) + unsafe _mutableWords[u.word].formSymmetricDifference(_Word(upTo: u.bit)) } } @@ -131,20 +131,20 @@ extension _UnsafeBitSet { if l.word == u.word { guard l.word < wordCount else { return } let w = _Word(from: l.bit, to: u.bit) - _mutableWords[l.word].subtract(w) + unsafe _mutableWords[l.word].subtract(w) return } - _mutableWords[l.word].subtract(_Word(upTo: l.bit).complement()) - _mutableWords[(l.word + 1) ..< u.word].update(repeating: .empty) + unsafe _mutableWords[l.word].subtract(_Word(upTo: l.bit).complement()) + unsafe _mutableWords[(l.word + 1) ..< u.word].update(repeating: .empty) if u.word < wordCount { - _mutableWords[u.word].subtract(_Word(upTo: u.bit)) + unsafe _mutableWords[u.word].subtract(_Word(upTo: u.bit)) } } @_effects(releasenone) internal func isDisjoint(with range: Range) -> Bool { - if self.isEmpty { return true } + if unsafe self.isEmpty { return true } let lower = Index(Swift.min(range.lowerBound, capacity)) let upper = Index(Swift.min(range.upperBound, capacity)) if lower == upper { return true } @@ -152,47 +152,47 @@ extension _UnsafeBitSet { if lower.word == upper.word { guard lower.word < wordCount else { return true } let w = _Word(from: lower.bit, to: upper.bit) - return _words[lower.word].intersection(w).isEmpty + return unsafe _words[lower.word].intersection(w).isEmpty } let lw = _Word(upTo: lower.bit).complement() - guard _words[lower.word].intersection(lw).isEmpty else { return false } + guard unsafe _words[lower.word].intersection(lw).isEmpty else { return false } for i in lower.word + 1 ..< upper.word { - guard _words[i].isEmpty else { return false } + guard unsafe _words[i].isEmpty else { return false } } if upper.word < wordCount { let uw = _Word(upTo: upper.bit) - guard _words[upper.word].intersection(uw).isEmpty else { return false } + guard unsafe _words[upper.word].intersection(uw).isEmpty else { return false } } return true } @_effects(releasenone) internal func isSubset(of range: Range) -> Bool { - guard !range.isEmpty else { return isEmpty } - guard !_words.isEmpty else { return true } + guard !range.isEmpty else { return unsafe isEmpty } + guard unsafe !_words.isEmpty else { return true } let r = range.clamped(to: 0 ..< UInt(capacity)) let lower = Index(r.lowerBound) let upper = Index(r.upperBound) for w in 0 ..< lower.word { - guard _words[w].isEmpty else { return false } + guard unsafe _words[w].isEmpty else { return false } } guard lower.word < wordCount else { return true } let lw = _Word(upTo: lower.bit) - guard _words[lower.word].intersection(lw).isEmpty else { return false } + guard unsafe _words[lower.word].intersection(lw).isEmpty else { return false } guard upper.word < wordCount else { return true } let hw = _Word(upTo: upper.bit).complement() - guard _words[upper.word].intersection(hw).isEmpty else { return false } + guard unsafe _words[upper.word].intersection(hw).isEmpty else { return false } for w in upper.word + 1 ..< wordCount { - guard _words[w].isEmpty else { return false } + guard unsafe _words[w].isEmpty else { return false } } return true } @@ -208,23 +208,23 @@ extension _UnsafeBitSet { if lower.word == upper.word { let w = _Word(from: lower.bit, to: upper.bit) - return _words[lower.word].intersection(w) == w + return unsafe _words[lower.word].intersection(w) == w } let lw = _Word(upTo: lower.bit).complement() - guard _words[lower.word].intersection(lw) == lw else { return false } + guard unsafe _words[lower.word].intersection(lw) == lw else { return false } for w in lower.word + 1 ..< upper.word { - guard _words[w].isFull else { return false } + guard unsafe _words[w].isFull else { return false } } guard upper.word < wordCount else { return true } let uw = _Word(upTo: upper.bit) - return _words[upper.word].intersection(uw) == uw + return unsafe _words[upper.word].intersection(uw) == uw } @_effects(releasenone) internal func isEqualSet(to range: Range) -> Bool { - if range.isEmpty { return self.isEmpty } + if range.isEmpty { return unsafe self.isEmpty } let r = range.clamped(to: 0 ..< UInt(capacity)) guard r == range else { return false } @@ -234,22 +234,22 @@ extension _UnsafeBitSet { guard upper.word == wordCount &- 1 else { return false } for w in 0 ..< lower.word { - guard _words[w].isEmpty else { return false } + guard unsafe _words[w].isEmpty else { return false } } if lower.word == upper.word { let w = _Word(from: lower.bit, to: upper.bit) - return _words[lower.word] == w + return unsafe _words[lower.word] == w } let lw = _Word(upTo: lower.bit).complement() - guard _words[lower.word] == lw else { return false } + guard unsafe _words[lower.word] == lw else { return false } for w in lower.word + 1 ..< upper.word { - guard _words[w].isFull else { return false } + guard unsafe _words[w].isFull else { return false } } let uw = _Word(upTo: upper.bit) - return _words[upper.word] == uw + return unsafe _words[upper.word] == uw } } diff --git a/Sources/BitCollections/BitSet/BitSet.swift b/Sources/BitCollections/BitSet/BitSet.swift index c7b8ac60..c162825f 100644 --- a/Sources/BitCollections/BitSet/BitSet.swift +++ b/Sources/BitCollections/BitSet/BitSet.swift @@ -24,6 +24,7 @@ import InternalCollectionsUtilities /// See `BitArray` for an alternative form of the same underlying data /// structure, treating it as a mutable random-access collection of `Bool` /// values. +@safe public struct BitSet { @usableFromInline internal var _storage: [_Word] @@ -43,8 +44,8 @@ extension BitSet { _ body: (_UnsafeHandle) throws -> R ) rethrows -> R { try _storage.withUnsafeBufferPointer { words in - let handle = _UnsafeHandle(words: words, mutable: false) - return try body(handle) + let handle = unsafe _UnsafeHandle(words: words, mutable: false) + return unsafe try body(handle) } } @@ -69,7 +70,7 @@ extension BitSet { } internal mutating func _shrink() { - let suffix = _read { $0._emptySuffix() } + let suffix = unsafe _read { unsafe $0._emptySuffix() } if suffix > 0 { _storage.removeLast(suffix) } } @@ -81,8 +82,8 @@ extension BitSet { _checkInvariants() } return try _storage.withUnsafeMutableBufferPointer { words in - var handle = _UnsafeHandle(words: words, mutable: true) - return try body(&handle) + var handle = unsafe _UnsafeHandle(words: words, mutable: true) + return unsafe try body(&handle) } } @@ -96,8 +97,8 @@ extension BitSet { _checkInvariants() } return try _storage.withUnsafeMutableBufferPointer { words in - var handle = _UnsafeHandle(words: words, mutable: true) - return try body(&handle, &shrink) + var handle = unsafe _UnsafeHandle(words: words, mutable: true) + return unsafe try body(&handle, &shrink) } } } diff --git a/Sources/BitCollections/Shared/Range+Utilities.swift b/Sources/BitCollections/Shared/Range+Utilities.swift index bd12da26..1598089a 100644 --- a/Sources/BitCollections/Shared/Range+Utilities.swift +++ b/Sources/BitCollections/Shared/Range+Utilities.swift @@ -15,14 +15,14 @@ extension Range where Bound: FixedWidthInteger { @inlinable internal func _clampedToUInt() -> Range { if upperBound <= 0 { - return Range(uncheckedBounds: (0, 0)) + return unsafe Range(uncheckedBounds: (0, 0)) } if lowerBound >= UInt.max { - return Range(uncheckedBounds: (UInt.max, UInt.max)) + return unsafe Range(uncheckedBounds: (UInt.max, UInt.max)) } let lower = lowerBound < 0 ? 0 : UInt(lowerBound) let upper = upperBound > UInt.max ? UInt.max : UInt(upperBound) - return Range(uncheckedBounds: (lower, upper)) + return unsafe Range(uncheckedBounds: (lower, upper)) } @inlinable @@ -33,6 +33,6 @@ extension Range where Bound: FixedWidthInteger { else { return nil } - return Range(uncheckedBounds: (lower: lower, upper: upper)) + return unsafe Range(uncheckedBounds: (lower: lower, upper: upper)) } } diff --git a/Sources/BitCollections/Shared/Slice+Utilities.swift b/Sources/BitCollections/Shared/Slice+Utilities.swift index 2b63dd77..e71996be 100644 --- a/Sources/BitCollections/Shared/Slice+Utilities.swift +++ b/Sources/BitCollections/Shared/Slice+Utilities.swift @@ -13,6 +13,6 @@ extension Slice { internal var _bounds: Range { - Range(uncheckedBounds: (startIndex, endIndex)) + unsafe Range(uncheckedBounds: (startIndex, endIndex)) } } diff --git a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift index 185bade6..cdf4a6c4 100644 --- a/Sources/ContainersPreview/Conformances/InputSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/InputSpan+Container.swift @@ -32,7 +32,7 @@ where Element: ~Copyable let span = self.span let it = span.makeBorrowingIterator(from: start, to: end) // FIXME: `it` is borrowing `span`, not self - return _overrideLifetime(it, borrowing: self) + return unsafe _overrideLifetime(it, borrowing: self) } @_alwaysEmitIntoClient diff --git a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift index c1d8e60b..883a3b7f 100644 --- a/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift +++ b/Sources/ContainersPreview/Conformances/MutableSpan+Container.swift @@ -98,7 +98,7 @@ extension MutableSpan where Element: ~Copyable { ) -> MutableSpan { precondition(index >= 0 && index <= count, "Index out of bounds") let end = self.count - let r = self._consumingExtracting(unchecked: Range(uncheckedBounds: (index, end))) + let r = unsafe self._consumingExtracting(unchecked: Range(uncheckedBounds: (index, end))) index = end return r } @@ -110,7 +110,7 @@ extension MutableSpan where Element: ~Copyable { ) -> MutableSpan { precondition(index >= 0 && index <= count, "Index out of bounds") let end = self.count - let r = self._mutatingExtracting( + let r = unsafe self._mutatingExtracting( unchecked: Range(uncheckedBounds: (index, end))) index = end return r @@ -128,7 +128,7 @@ extension MutableSpan where Element: ~Copyable { if limit >= index, limit < end { end = limit } - let r = self._consumingExtracting( + let r = unsafe self._consumingExtracting( unchecked: Range(uncheckedBounds: (index, end))) index = end return r @@ -146,7 +146,7 @@ extension MutableSpan where Element: ~Copyable { if limit >= index, limit < end { end = limit } - let r = self._mutatingExtracting( + let r = unsafe self._mutatingExtracting( unchecked: Range(uncheckedBounds: (index, end))) index = end return r diff --git a/Sources/ContainersPreview/Conformances/RigidSet+Container.swift b/Sources/ContainersPreview/Conformances/RigidSet+Container.swift index 384038e8..ed1d92f2 100644 --- a/Sources/ContainersPreview/Conformances/RigidSet+Container.swift +++ b/Sources/ContainersPreview/Conformances/RigidSet+Container.swift @@ -37,7 +37,7 @@ extension RigidSet: Container where Element: ~Copyable { ) -> BorrowingIterator { _checkValidIndex(start) _checkValidIndex(end) - return BorrowingIterator(_set: self, from: start, to: end) + return unsafe BorrowingIterator(_set: self, from: start, to: end) } } diff --git a/Sources/ContainersPreview/Conformances/Span+Container.swift b/Sources/ContainersPreview/Conformances/Span+Container.swift index ee432555..b7cec83f 100644 --- a/Sources/ContainersPreview/Conformances/Span+Container.swift +++ b/Sources/ContainersPreview/Conformances/Span+Container.swift @@ -36,12 +36,12 @@ extension Span: RandomAccessContainer where Element: ~Copyable { return iterator._start #else return self.withUnsafeBufferPointer { ourBuffer in - iterator._withShamIterator { sham in + unsafe iterator._withShamIterator { sham in precondition( - sham._basePointer == UnsafeRawPointer(ourBuffer.baseAddress) + unsafe sham._basePointer == UnsafeRawPointer(ourBuffer.baseAddress) && sham._baseCount <= ourBuffer.count, "Iterator does not belong to this container") - return sham._start + return unsafe sham._start } } #endif diff --git a/Sources/ContainersPreview/Conformances/UniqueDeque+Container.swift b/Sources/ContainersPreview/Conformances/UniqueDeque+Container.swift index 8d6d9b7a..c71af159 100644 --- a/Sources/ContainersPreview/Conformances/UniqueDeque+Container.swift +++ b/Sources/ContainersPreview/Conformances/UniqueDeque+Container.swift @@ -93,7 +93,7 @@ extension UniqueDeque where Element: ~Copyable { where P.Element: ~Copyable { _ensureFreeCapacity(newItemCount) - return try _storage._handle.uncheckedPrepend( + return unsafe try _storage._handle.uncheckedPrepend( addingCount: newItemCount ) { target throws(E) in try producer.generate(into: &target) @@ -127,7 +127,7 @@ extension UniqueDeque where Element: ~Copyable { while !done { let c = Swift.max(producer.underestimatedCount, 1) _ensureFreeCapacity(c) - _ = try _storage._handle.uncheckedPrepend( + _ = unsafe try _storage._handle.uncheckedPrepend( addingCount: freeCapacity ) { target throws(E) in let origCount = target.count @@ -139,7 +139,7 @@ extension UniqueDeque where Element: ~Copyable { done = try producer.generate(into: &target) == 0 } } - return Range(uncheckedBounds: (0, added)) + return unsafe Range(uncheckedBounds: (0, added)) } } diff --git a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift index 19dbaced..ece21d4e 100644 --- a/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Container/Container+Filter.swift @@ -97,14 +97,14 @@ extension ContainerFilter: BorrowingIteratorProtocol where Element: ~Copyable { while true { // Drop filtered out items from prefix of _remainder var i = 0 - while i < _remainder.count, !_isIncluded(_remainder[unchecked: i]) { + while i < _remainder.count, unsafe !_isIncluded(_remainder[unchecked: i]) { i &+= 1 } _remainder = _remainder.extracting(droppingFirst: i) if !_remainder.isEmpty { let c = Swift.min(_remainder.count, maxCount) i = 1 - while i < c, _isIncluded(_remainder[unchecked: i]) { + while i < c, unsafe _isIncluded(_remainder[unchecked: i]) { i &+= 1 } return _remainder._trim(first: i) diff --git a/Sources/ContainersPreview/Protocols/Container/DrainableContainer.swift b/Sources/ContainersPreview/Protocols/Container/DrainableContainer.swift index 0cb75f5e..2f804dac 100644 --- a/Sources/ContainersPreview/Protocols/Container/DrainableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/DrainableContainer.swift @@ -81,7 +81,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable { @_alwaysEmitIntoClient public mutating func remove(at index: inout Index) -> Element { - let range = Range(uncheckedBounds: (index, self.index(after: index))) + let range = unsafe Range(uncheckedBounds: (index, self.index(after: index))) var result: Element? index = self.consumeSubrange(range) { result = $0.removeFirst() diff --git a/Sources/ContainersPreview/Protocols/Container/MutableContainer+UpdateSubrange.swift b/Sources/ContainersPreview/Protocols/Container/MutableContainer+UpdateSubrange.swift index 436a2016..cd2ae1d8 100644 --- a/Sources/ContainersPreview/Protocols/Container/MutableContainer+UpdateSubrange.swift +++ b/Sources/ContainersPreview/Protocols/Container/MutableContainer+UpdateSubrange.swift @@ -74,7 +74,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable // We need to update all items that were successfully generated, // whether or not we've run into failure/eof. let j = offset &+ scratch.count - dst._updateSubrange( + unsafe dst._updateSubrange( Range(uncheckedBounds: (offset, j)), moving: &scratch) offset = j @@ -161,7 +161,7 @@ where Self: ~Copyable & ~Escapable, Element: ~Copyable !src.isEmpty, "updateSubrange source length does not match target range") let k = j &+ src.count - dst._updateSubrange(Range(uncheckedBounds: (j, k)), moving: &src) + unsafe dst._updateSubrange(Range(uncheckedBounds: (j, k)), moving: &src) j = k } } @@ -196,7 +196,7 @@ where Self: ~Copyable & ~Escapable, Element: Copyable while offset < dst.count { let src = try source.nextSpan(maxCount: dst.count &- offset) if src.isEmpty { break outer } - let range = Range(uncheckedBounds: (offset, offset &+ src.count)) + let range = unsafe Range(uncheckedBounds: (offset, offset &+ src.count)) dst._updateSubrange(range, copying: src) offset = range.upperBound } @@ -220,7 +220,7 @@ where Self: ~Copyable & ~Escapable, Element: Copyable let src = it.nextSpan(maxCount: dst.count &- offset) precondition(!src.isEmpty, "updateSubrange source length does not match target range") let end = offset + src.count - dst._updateSubrange(Range(uncheckedBounds: (offset, end)), copying: src) + unsafe dst._updateSubrange(Range(uncheckedBounds: (offset, end)), copying: src) offset = end } } diff --git a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift index 43b7eb0d..f4e4a340 100644 --- a/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift +++ b/Sources/ContainersPreview/Protocols/Container/RangeReplaceableContainer.swift @@ -655,9 +655,9 @@ where let res: Range? = items.withContiguousStorageIfAvailable { buffer in precondition(buffer.count == c, "Broken Collection: mismatching count") - var buffer = buffer + var buffer = unsafe buffer let res = self.replaceSubrange(subrange, addingCount: c) { target in - target._append(copying: buffer._trim(first: target.freeCapacity)) + unsafe target._append(copying: buffer._trim(first: target.freeCapacity)) } precondition(buffer.count == 0, "Invalid RangeReplaceableContainer") return res @@ -719,7 +719,7 @@ where let res: Range? = items.withContiguousStorageIfAvailable { buffer in precondition(buffer.count == newCount, "Broken Collection: mismatching count") return self.insert(addingCount: buffer.count, at: index) { target in - target._append(copying: buffer) + unsafe target._append(copying: buffer) } } if let res { return res } diff --git a/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Filter.swift b/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Filter.swift index 25fdfe08..3e1069d5 100644 --- a/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Filter.swift +++ b/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Filter.swift @@ -65,7 +65,7 @@ where Base: ~Copyable & ~Escapable, Base.Element: ~Copyable { let span = try _base.nextSpan(maxCount: 1) if span.isEmpty { return span } precondition(span.count == 1, "Invalid BorrowingIterator") - if try _isIncluded(span[unchecked: 0]) { return span } + if unsafe try _isIncluded(span[unchecked: 0]) { return span } } } } diff --git a/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Map.swift b/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Map.swift index ee83d845..a3e4ea8c 100644 --- a/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Map.swift +++ b/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Map.swift @@ -93,7 +93,7 @@ where public mutating func next() throws(Failure) -> Element? { let span = try _it.nextSpan(maxCount: 1) guard !span.isEmpty else { return nil } - return try _transform(span[unchecked: 0]) + return unsafe try _transform(span[unchecked: 0]) } @inlinable @@ -110,7 +110,7 @@ where c += span.count var i = 0 while i < span.count { - target.append(try _transform(span[unchecked: i])) + unsafe target.append(try _transform(span[unchecked: i])) i &+= 1 } } diff --git a/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Reduce.swift b/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Reduce.swift index 62b07169..fc47d98a 100644 --- a/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Reduce.swift +++ b/Sources/ContainersPreview/Protocols/Iterable/BorrowingIteratorProtocol+Reduce.swift @@ -30,7 +30,7 @@ where guard !span.isEmpty else { break } var i = 0 while i < span.count { - result = try nextPartialResult(result, span[unchecked: i]) + result = unsafe try nextPartialResult(result, span[unchecked: i]) i &+= 1 } } @@ -48,7 +48,7 @@ where guard !span.isEmpty else { break } var i = 0 while i < span.count { - try updateAccumulatingResult(&result, span[unchecked: i]) + unsafe try updateAccumulatingResult(&result, span[unchecked: i]) i &+= 1 } } diff --git a/Sources/ContainersPreview/Types/UniqueBox.swift b/Sources/ContainersPreview/Types/UniqueBox.swift index 6bf2ff4e..3efb431c 100644 --- a/Sources/ContainersPreview/Types/UniqueBox.swift +++ b/Sources/ContainersPreview/Types/UniqueBox.swift @@ -84,13 +84,13 @@ extension UniqueBox where Value: ~Copyable { @_transparent @_unsafeSelfDependentResult borrow { - _pointer.pointee + unsafe _pointer.pointee } @_transparent @_unsafeSelfDependentResult mutate { - &_pointer.pointee + unsafe &_pointer.pointee } } #else @@ -98,12 +98,12 @@ extension UniqueBox where Value: ~Copyable { public var value: Value { @_transparent unsafeAddress { - UnsafePointer(_pointer) + unsafe UnsafePointer(_pointer) } @_transparent unsafeMutableAddress { - _pointer + unsafe _pointer } } #endif @@ -187,7 +187,7 @@ extension UniqueBox where Value: ~Copyable { @_lifetime(immortal) @_unsafeNonescapableResult // FIXME: This should not be necessary public consuming func leak() -> MutableRef { - let p = _pointer + let p = unsafe _pointer discard self // FIXME: _unsafeImmortalize does not work here, and MutableRef has no immortal initializer return unsafe MutableRef(&p.pointee) diff --git a/Sources/DequeModule/Deque/Deque+Collection.swift b/Sources/DequeModule/Deque/Deque+Collection.swift index 1a252557..0b7d25ef 100644 --- a/Sources/DequeModule/Deque/Deque+Collection.swift +++ b/Sources/DequeModule/Deque/Deque+Collection.swift @@ -23,6 +23,7 @@ extension Deque: Sequence { /// An iterator over the members of a deque. @frozen + @safe public struct Iterator: IteratorProtocol { @usableFromInline internal var _storage: Deque._Storage @@ -42,23 +43,23 @@ extension Deque: Sequence { @inlinable internal init(_base: Deque) { - self = _base._storage.read { handle in - let start = handle.startSlot - let end = Swift.min(start.advanced(by: handle.count), handle.limSlot) + self = unsafe _base._storage.read { handle in + let start = unsafe handle.startSlot + let end = unsafe Swift.min(start.advanced(by: handle.count), handle.limSlot) return Self(_storage: _base._storage, start: start, end: end) } } @inlinable internal init(_base: Deque, from index: Int) { - self = _base._storage.read { handle in - assert(index >= 0 && index <= handle.count) - let start = handle.slot(forOffset: index) - if index == handle.count { + self = unsafe _base._storage.read { handle in + assert(unsafe index >= 0 && index <= handle.count) + let start = unsafe handle.slot(forOffset: index) + if unsafe index == handle.count { return Self(_storage: _base._storage, start: start, end: start) } - var end = handle.endSlot - if start >= end { end = handle.limSlot } + var end = unsafe handle.endSlot + if start >= end { end = unsafe handle.limSlot } return Self(_storage: _base._storage, start: start, end: end) } } @@ -67,8 +68,8 @@ extension Deque: Sequence { @inline(never) internal mutating func _swapSegment() -> Bool { assert(_nextSlot == _endSlot) - return _storage.read { handle in - let end = handle.endSlot + return unsafe _storage.read { handle in + let end = unsafe handle.endSlot if end == .zero || end == _nextSlot { return false } @@ -90,8 +91,8 @@ extension Deque: Sequence { assert(_nextSlot < _endSlot) let slot = _nextSlot _nextSlot = _nextSlot.advanced(by: 1) - return _storage.read { handle in - return handle.ptr(at: slot).pointee + return unsafe _storage.read { handle in + return unsafe handle.ptr(at: slot).pointee } } } @@ -106,17 +107,17 @@ extension Deque: Sequence { @inlinable public __consuming func _copyToContiguousArray() -> ContiguousArray { - ContiguousArray(unsafeUninitializedCapacity: _storage.count) { target, count in - _storage.read { source in - let segments = source.segments() - let c = segments.first.count - target[.. ) -> (Iterator, UnsafeMutableBufferPointer.Index) { - _storage.read { source in - let segments = source.segments() - let c1 = Swift.min(segments.first.count, target.count) - target[.. c1, let second = segments.second else { + unsafe _storage.read { source in + let segments = unsafe source.segments() + let c1 = unsafe Swift.min(segments.first.count, target.count) + unsafe target[.. c1, let second = unsafe segments.second else { return (Iterator(_base: self, from: c1), c1) } let c2 = Swift.min(second.count, target.count - c1) - target[c1 ..< c1 + c2].initializeAll(fromContentsOf: second.prefix(c2)) + unsafe target[c1 ..< c1 + c2].initializeAll(fromContentsOf: second.prefix(c2)) return (Iterator(_base: self, from: c1 + c2), c1 + c2) } } @@ -158,10 +159,10 @@ extension Deque: Sequence { public func withContiguousStorageIfAvailable( _ body: (UnsafeBufferPointer) throws -> R ) rethrows -> R? { - return try _storage.read { handle in - let endSlot = handle.startSlot.advanced(by: handle.count) - guard endSlot.position <= handle.capacity else { return nil } - return try body(handle.buffer(for: handle.startSlot ..< endSlot)) + return unsafe try _storage.read { handle in + let endSlot = unsafe handle.startSlot.advanced(by: handle.count) + guard unsafe endSlot.position <= handle.capacity else { return nil } + return unsafe try body(handle.buffer(for: handle.startSlot ..< endSlot)) } } } @@ -357,14 +358,16 @@ extension Deque: RandomAccessCollection { public subscript(index: Int) -> Element { get { precondition(index >= 0 && index < count, "Index out of bounds") - return _storage.read { $0.ptr(at: $0.slot(forOffset: index)).pointee } + return unsafe _storage.read { + unsafe $0.ptr(at: $0.slot(forOffset: index)).pointee + } } set { precondition(index >= 0 && index < count, "Index out of bounds") _storage.ensureUnique() - _storage.update { handle in - let slot = handle.slot(forOffset: index) - handle.ptr(at: slot).pointee = newValue + unsafe _storage.update { handle in + let slot = unsafe handle.slot(forOffset: index) + unsafe handle.ptr(at: slot).pointee = newValue } } @inline(__always) // https://github.com/apple/swift-collections/issues/164 @@ -384,16 +387,16 @@ extension Deque: RandomAccessCollection { // We technically aren't supposed to escape storage pointers out of a // managed buffer, so we escape a `(slot, value)` pair instead, leaving // the corresponding slot temporarily uninitialized. - return _storage.update { handle in - let slot = handle.slot(forOffset: index) - return (slot, handle.ptr(at: slot).move()) + return unsafe _storage.update { handle in + let slot = unsafe handle.slot(forOffset: index) + return (slot, unsafe handle.ptr(at: slot).move()) } } @inlinable internal mutating func _finalizeModify(_ slot: _Slot, _ value: Element) { - _storage.update { handle in - handle.ptr(at: slot).initialize(to: value) + unsafe _storage.update { handle in + unsafe handle.ptr(at: slot).initialize(to: value) } } @@ -437,10 +440,10 @@ extension Deque: MutableCollection { precondition(i >= 0 && i < count, "Index out of bounds") precondition(j >= 0 && j < count, "Index out of bounds") _storage.ensureUnique() - _storage.update { handle in - let slot1 = handle.slot(forOffset: i) - let slot2 = handle.slot(forOffset: j) - handle.mutableBuffer.swapAt(slot1.position, slot2.position) + unsafe _storage.update { handle in + let slot1 = unsafe handle.slot(forOffset: i) + let slot2 = unsafe handle.slot(forOffset: j) + unsafe handle.mutableBuffer.swapAt(slot1.position, slot2.position) } } @@ -469,19 +472,21 @@ extension Deque: MutableCollection { _ body: (inout UnsafeMutableBufferPointer) throws -> R ) rethrows -> R? { _storage.ensureUnique() - return try _storage.update { handle in - let endSlot = handle.startSlot.advanced(by: handle.count) - guard endSlot.position <= handle.capacity else { + return unsafe try _storage.update { handle in + let endSlot = unsafe handle.startSlot.advanced(by: handle.count) + guard unsafe endSlot.position <= handle.capacity else { // FIXME: Rotate storage such that it becomes contiguous. return nil } - let original = handle.mutableBuffer(for: handle.startSlot ..< endSlot) - var extract = original + let original = unsafe handle.mutableBuffer(for: handle.startSlot ..< endSlot) + var extract = unsafe original defer { - precondition(extract.baseAddress == original.baseAddress && extract.count == original.count, - "Closure must not replace the provided buffer") + precondition( + unsafe extract.baseAddress == original.baseAddress + && extract.count == original.count, + "Closure must not replace the provided buffer") } - return try body(&extract) + return unsafe try body(&extract) } } @@ -489,7 +494,7 @@ extension Deque: MutableCollection { public mutating func _withUnsafeMutableBufferPointerIfSupported( _ body: (inout UnsafeMutableBufferPointer) throws -> R ) rethrows -> R? { - return try withContiguousMutableStorageIfAvailable(body) + return unsafe try withContiguousMutableStorageIfAvailable(body) } } @@ -560,16 +565,16 @@ extension Deque: RangeReplaceableCollection { let targetCut = subrange.lowerBound + replacementCount let sourceCut = newElements.index(newElements.startIndex, offsetBy: replacementCount) - _storage.update { target in - target.uncheckedReplaceInPlace( + unsafe _storage.update { target in + unsafe target.uncheckedReplaceInPlace( inOffsets: subrange.lowerBound ..< targetCut, with: newElements[.. 0 { - target.uncheckedInsert( + unsafe target.uncheckedInsert( contentsOf: newElements[sourceCut...], count: deltaCount, atOffset: targetCut) @@ -590,12 +595,12 @@ extension Deque: RangeReplaceableCollection { public init(repeating repeatedValue: Element, count: Int) { precondition(count >= 0) self.init(minimumCapacity: count) - _storage.update { handle in - assert(handle.startSlot == .zero) + unsafe _storage.update { handle in + assert(unsafe handle.startSlot == .zero) if count > 0 { - handle.ptr(at: .zero).initialize(repeating: repeatedValue, count: count) + unsafe handle.ptr(at: .zero).initialize(repeating: repeatedValue, count: count) } - handle.count = count + unsafe handle.count = count } } @@ -622,16 +627,16 @@ extension Deque: RangeReplaceableCollection { let c = elements.count guard c > 0 else { _storage = _Storage(); return } self._storage = _Storage(minimumCapacity: c) - _storage.update { handle in - assert(handle.startSlot == .zero) - let target = handle.mutableBuffer(for: .zero ..< _Slot(at: c)) + unsafe _storage.update { handle in + assert(unsafe handle.startSlot == .zero) + let target = unsafe handle.mutableBuffer(for: .zero ..< _Slot(at: c)) let done: Void? = elements.withContiguousStorageIfAvailable { source in - target.initializeAll(fromContentsOf: source) + unsafe target.initializeAll(fromContentsOf: source) } if done == nil { - target.initializeAll(fromContentsOf: elements) + unsafe target.initializeAll(fromContentsOf: elements) } - handle.count = c + unsafe handle.count = c } } @@ -661,8 +666,8 @@ extension Deque: RangeReplaceableCollection { @inlinable public mutating func append(_ newElement: Element) { _storage.ensureUnique(minimumCapacity: count + 1) - _storage.update { - $0.uncheckedAppend(newElement) + unsafe _storage.update { + unsafe $0.uncheckedAppend(newElement) } } @@ -684,7 +689,7 @@ extension Deque: RangeReplaceableCollection { public mutating func append(contentsOf newElements: some Sequence) { let done: Void? = newElements.withContiguousStorageIfAvailable { source in _storage.ensureUnique(minimumCapacity: count + source.count) - _storage.update { $0.uncheckedAppend(contentsOf: source) } + unsafe _storage.update { unsafe $0.uncheckedAppend(contentsOf: source) } } if done != nil { return @@ -692,18 +697,18 @@ extension Deque: RangeReplaceableCollection { let underestimatedCount = newElements.underestimatedCount _storage.ensureUnique(minimumCapacity: count + underestimatedCount) - var it = _storage.update { target in - let gaps = target.availableSegments() - let (it, copied) = gaps.initialize(fromSequencePrefix: newElements) - target.count += copied + var it = unsafe _storage.update { target in + let gaps = unsafe target.availableSegments() + let (it, copied) = unsafe gaps.initialize(fromSequencePrefix: newElements) + unsafe target.count += copied return it } while let next = it.next() { _storage.ensureUnique(minimumCapacity: count + 1) - _storage.update { target in - target.uncheckedAppend(next) - let gaps = target.availableSegments() - target.count += gaps.initialize(copyingPrefixOf: &it) + unsafe _storage.update { target in + unsafe target.uncheckedAppend(next) + let gaps = unsafe target.availableSegments() + unsafe target.count += gaps.initialize(copyingPrefixOf: &it) } } } @@ -728,17 +733,17 @@ extension Deque: RangeReplaceableCollection { ) { let done: Void? = newElements.withContiguousStorageIfAvailable { source in _storage.ensureUnique(minimumCapacity: count + source.count) - _storage.update { $0.uncheckedAppend(contentsOf: source) } + unsafe _storage.update { unsafe $0.uncheckedAppend(contentsOf: source) } } guard done == nil else { return } let c = newElements.count guard c > 0 else { return } _storage.ensureUnique(minimumCapacity: count + c) - _storage.update { target in - let gaps = target.availableSegments().prefix(c) - gaps.initialize(copying: newElements) - target.count += c + unsafe _storage.update { target in + let gaps = unsafe target.availableSegments().prefix(c) + unsafe gaps.initialize(copying: newElements) + unsafe target.count += c } } @@ -761,18 +766,18 @@ extension Deque: RangeReplaceableCollection { public mutating func insert(_ newElement: Element, at index: Int) { precondition(index >= 0 && index <= count, "Index out of bounds") _storage.ensureUnique(minimumCapacity: count + 1) - _storage.update { target in + unsafe _storage.update { target in if index == 0 { - target.uncheckedPrepend(newElement) + unsafe target.uncheckedPrepend(newElement) return } if index == count { - target.uncheckedAppend(newElement) + unsafe target.uncheckedAppend(newElement) return } - let gap = target.openGap(ofSize: 1, atOffset: index) - assert(gap.first.count == 1) - gap.first.baseAddress!.initialize(to: newElement) + let gap = unsafe target.openGap(ofSize: 1, atOffset: index) + assert(unsafe gap.first.count == 1) + unsafe gap.first.baseAddress!.initialize(to: newElement) } } @@ -801,8 +806,8 @@ extension Deque: RangeReplaceableCollection { precondition(index >= 0 && index <= count, "Index out of bounds") let newCount = newElements.count _storage.ensureUnique(minimumCapacity: count + newCount) - _storage.update { target in - target.uncheckedInsert(contentsOf: newElements, count: newCount, atOffset: index) + unsafe _storage.update { target in + unsafe target.uncheckedInsert(contentsOf: newElements, count: newCount, atOffset: index) } } @@ -827,10 +832,10 @@ extension Deque: RangeReplaceableCollection { precondition(index >= 0 && index < self.count, "Index out of bounds") // FIXME: Implement storage shrinking _storage.ensureUnique() - return _storage.update { target in + return unsafe _storage.update { target in // FIXME: Add direct implementation & see if it makes a difference let result = self[index] - target.uncheckedRemove(offsets: index ..< index + 1) + unsafe target.uncheckedRemove(offsets: index ..< index + 1) return result } } @@ -853,14 +858,14 @@ extension Deque: RangeReplaceableCollection { precondition(bounds.lowerBound >= 0 && bounds.upperBound <= self.count, "Index range out of bounds") _storage.ensureUnique() - _storage.update { $0.uncheckedRemove(offsets: bounds) } + unsafe _storage.update { unsafe $0.uncheckedRemove(offsets: bounds) } } @inlinable public mutating func _customRemoveLast() -> Element? { precondition(!isEmpty, "Cannot remove last element of an empty Deque") _storage.ensureUnique() - return _storage.update { $0.uncheckedRemoveLast() } + return unsafe _storage.update { unsafe $0.uncheckedRemoveLast() } } @inlinable @@ -868,7 +873,7 @@ extension Deque: RangeReplaceableCollection { precondition(n >= 0, "Cannot remove a negative number of elements") precondition(n <= count, "Cannot remove more elements than there are in the Collection") _storage.ensureUnique() - _storage.update { $0.uncheckedRemoveLast(n) } + unsafe _storage.update { unsafe $0.uncheckedRemoveLast(n) } return true } @@ -885,7 +890,7 @@ extension Deque: RangeReplaceableCollection { public mutating func removeFirst() -> Element { precondition(!isEmpty, "Cannot remove first element of an empty Deque") _storage.ensureUnique() - return _storage.update { $0.uncheckedRemoveFirst() } + return unsafe _storage.update { unsafe $0.uncheckedRemoveFirst() } } /// Removes the specified number of elements from the beginning of the deque. @@ -901,7 +906,7 @@ extension Deque: RangeReplaceableCollection { precondition(n >= 0, "Cannot remove a negative number of elements") precondition(n <= count, "Cannot remove more elements than there are in the Collection") _storage.ensureUnique() - return _storage.update { $0.uncheckedRemoveFirst(n) } + return unsafe _storage.update { unsafe $0.uncheckedRemoveFirst(n) } } /// Removes all elements from the deque. @@ -914,7 +919,7 @@ extension Deque: RangeReplaceableCollection { public mutating func removeAll(keepingCapacity keepCapacity: Bool = false) { if keepCapacity { _storage.ensureUnique() - _storage.update { $0.uncheckedRemoveAll() } + unsafe _storage.update { unsafe $0.uncheckedRemoveAll() } } else { self = Deque() } diff --git a/Sources/DequeModule/Deque/Deque+Extras.swift b/Sources/DequeModule/Deque/Deque+Extras.swift index b33bef36..2d103481 100644 --- a/Sources/DequeModule/Deque/Deque+Extras.swift +++ b/Sources/DequeModule/Deque/Deque+Extras.swift @@ -48,19 +48,20 @@ extension Deque { (inout UnsafeMutableBufferPointer, inout Int) throws -> Void ) rethrows { self._storage = .init(minimumCapacity: capacity) - try _storage.update { handle in - handle.startSlot = .zero + unsafe try _storage.update { handle in + unsafe handle.startSlot = .zero var count = 0 - var buffer = handle.mutableBuffer(for: .zero ..< _Slot(at: capacity)) + var buffer = unsafe handle.mutableBuffer(for: .zero ..< _Slot(at: capacity)) defer { precondition(count <= capacity, "Initialized count set to greater than specified capacity") - let b = handle.mutableBuffer(for: .zero ..< _Slot(at: capacity)) - precondition(buffer.baseAddress == b.baseAddress && buffer.count == b.count, + let b = unsafe handle.mutableBuffer(for: .zero ..< _Slot(at: capacity)) + precondition( + unsafe buffer.baseAddress == b.baseAddress && buffer.count == b.count, "Initializer relocated Deque storage") - handle.count = count + unsafe handle.count = count } - try initializer(&buffer, &count) + unsafe try initializer(&buffer, &count) } } } @@ -79,8 +80,8 @@ extension Deque { // where Self == Self.SubSequence guard count > 0 else { return nil } _storage.ensureUnique() - return _storage.update { - $0.uncheckedRemoveFirst() + return unsafe _storage.update { + unsafe $0.uncheckedRemoveFirst() } } @@ -114,8 +115,8 @@ extension Deque { @inlinable public mutating func prepend(_ newElement: Element) { _storage.ensureUnique(minimumCapacity: count + 1) - return _storage.update { - $0.uncheckedPrepend(newElement) + return unsafe _storage.update { + unsafe $0.uncheckedPrepend(newElement) } } @@ -141,18 +142,18 @@ extension Deque { ) { let done: Void? = newElements.withContiguousStorageIfAvailable { source in _storage.ensureUnique(minimumCapacity: count + source.count) - _storage.update { $0.uncheckedPrepend(contentsOf: source) } + unsafe _storage.update { unsafe $0.uncheckedPrepend(contentsOf: source) } } guard done == nil else { return } let c = newElements.count guard c > 0 else { return } _storage.ensureUnique(minimumCapacity: count + c) - _storage.update { target in - let gaps = target.availableSegments().suffix(c) - gaps.initialize(copying: newElements) - target.count += c - target.startSlot = target.slot(target.startSlot, offsetBy: -c) + unsafe _storage.update { target in + let gaps = unsafe target.availableSegments().suffix(c) + unsafe gaps.initialize(copying: newElements) + unsafe target.count += c + unsafe target.startSlot = target.slot(target.startSlot, offsetBy: -c) } } @@ -176,7 +177,7 @@ extension Deque { public mutating func prepend(contentsOf newElements: some Sequence) { let done: Void? = newElements.withContiguousStorageIfAvailable { source in _storage.ensureUnique(minimumCapacity: count + source.count) - _storage.update { $0.uncheckedPrepend(contentsOf: source) } + unsafe _storage.update { unsafe $0.uncheckedPrepend(contentsOf: source) } } guard done == nil else { return } @@ -184,11 +185,11 @@ extension Deque { self.append(contentsOf: newElements) let newCount = self.count let c = newCount - originalCount - _storage.update { target in - target.startSlot = target.slot(forOffset: originalCount) - target.count = target.capacity - target.closeGap(offsets: c ..< c + (target.capacity - newCount)) - assert(target.count == newCount) + unsafe _storage.update { target in + unsafe target.startSlot = target.slot(forOffset: originalCount) + unsafe target.count = target.capacity + unsafe target.closeGap(offsets: c ..< c + (target.capacity - newCount)) + assert(unsafe target.count == newCount) } } } diff --git a/Sources/DequeModule/Deque/Deque+Testing.swift b/Sources/DequeModule/Deque/Deque+Testing.swift index 373f9d55..e2a02499 100644 --- a/Sources/DequeModule/Deque/Deque+Testing.swift +++ b/Sources/DequeModule/Deque/Deque+Testing.swift @@ -71,15 +71,15 @@ extension Deque { let buffer = _DequeBuffer.create(minimumCapacity: capacity) { _ in _DequeBufferHeader(capacity: capacity, count: contents.count, startSlot: startSlot) } - let storage = Deque._Storage(unsafeDowncast(buffer, to: _DequeBuffer.self)) + let storage = unsafe Deque._Storage(unsafeDowncast(buffer, to: _DequeBuffer.self)) if contents.count > 0 { contents.withUnsafeBufferPointer { source in - storage.update { target in - let segments = target.mutableSegments() - let c = segments.first.count - segments.first.initializeAll(fromContentsOf: source.prefix(c)) - if let second = segments.second { - second.initializeAll(fromContentsOf: source.dropFirst(c)) + unsafe storage.update { target in + let segments = unsafe target.mutableSegments() + let c = unsafe segments.first.count + unsafe segments.first.initializeAll(fromContentsOf: source.prefix(c)) + if let second = unsafe segments.second { + unsafe second.initializeAll(fromContentsOf: source.dropFirst(c)) } } } diff --git a/Sources/DequeModule/Deque/Deque._Storage.swift b/Sources/DequeModule/Deque/Deque._Storage.swift index 1f11b33d..e93f2ab0 100644 --- a/Sources/DequeModule/Deque/Deque._Storage.swift +++ b/Sources/DequeModule/Deque/Deque._Storage.swift @@ -23,6 +23,7 @@ extension Deque { @inlinable @inline(__always) + @unsafe internal init(_buffer: _Buffer) { self._buffer = _buffer } @@ -39,12 +40,12 @@ extension Deque._Storage: CustomStringConvertible { extension Deque._Storage { @inlinable internal init() { - self.init(_buffer: _Buffer(unsafeBufferObject: _emptyDequeStorage)) + unsafe self.init(_buffer: _Buffer(unsafeBufferObject: _emptyDequeStorage)) } @inlinable internal init(_ object: _DequeBuffer) { - self.init(_buffer: _Buffer(unsafeBufferObject: object)) + unsafe self.init(_buffer: _Buffer(unsafeBufferObject: object)) } @inlinable @@ -57,7 +58,7 @@ extension Deque._Storage { count: 0, startSlot: .zero) }) - self.init(_buffer: _Buffer(unsafeBufferObject: object)) + unsafe self.init(_buffer: _Buffer(unsafeBufferObject: object)) } } @@ -82,19 +83,20 @@ extension Deque._Storage { @inlinable @inline(__always) internal var capacity: Int { - _buffer.withUnsafeMutablePointerToHeader { $0.pointee.capacity } + unsafe _buffer.withUnsafeMutablePointerToHeader { unsafe $0.pointee.capacity } } @inlinable @inline(__always) internal var count: Int { - _buffer.withUnsafeMutablePointerToHeader { $0.pointee.count } + unsafe _buffer.withUnsafeMutablePointerToHeader { unsafe $0.pointee.count } } @inlinable @inline(__always) internal var startSlot: _DequeSlot { - _buffer.withUnsafeMutablePointerToHeader { $0.pointee.startSlot + unsafe _buffer.withUnsafeMutablePointerToHeader { + unsafe $0.pointee.startSlot } } } @@ -108,23 +110,27 @@ extension Deque._Storage { @inlinable @inline(__always) + @unsafe internal func read(_ body: (_UnsafeHandle) throws -> R) rethrows -> R { - try _buffer.withUnsafeMutablePointers { header, elements in - let handle = _UnsafeHandle(header: header, - elements: elements, - isMutable: false) - return try body(handle) + unsafe try _buffer.withUnsafeMutablePointers { header, elements in + let handle = unsafe _UnsafeHandle( + header: header, + elements: elements, + isMutable: false) + return unsafe try body(handle) } } @inlinable @inline(__always) + @unsafe internal func update(_ body: (_UnsafeHandle) throws -> R) rethrows -> R { - try _buffer.withUnsafeMutablePointers { header, elements in - let handle = _UnsafeHandle(header: header, - elements: elements, - isMutable: true) - return try body(handle) + unsafe try _buffer.withUnsafeMutablePointers { header, elements in + let handle = unsafe _UnsafeHandle( + header: header, + elements: elements, + isMutable: true) + return unsafe try body(handle) } } } @@ -151,7 +157,7 @@ extension Deque._Storage { @inlinable @inline(never) internal mutating func _makeUniqueCopy() { - self = self.read { $0.copyElements() } + self = unsafe self.read { unsafe $0.copyElements() } } @usableFromInline @@ -194,18 +200,18 @@ extension Deque._Storage { ) { if capacity >= minimumCapacity { assert(!isUnique) - self = self.read { $0.copyElements() } + self = unsafe self.read { unsafe $0.copyElements() } return } let minimumCapacity = _growCapacity(to: minimumCapacity, linearly: linearGrowth) if isUnique { - self = self.update { source in - source.moveElements(minimumCapacity: minimumCapacity) + self = unsafe self.update { source in + unsafe source.moveElements(minimumCapacity: minimumCapacity) } } else { - self = self.read { source in - source.copyElements(minimumCapacity: minimumCapacity) + self = unsafe self.read { source in + unsafe source.copyElements(minimumCapacity: minimumCapacity) } } } diff --git a/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift b/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift index d0d36d5f..bd6114ea 100644 --- a/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift +++ b/Sources/DequeModule/Deque/Deque._UnsafeHandle.swift @@ -14,25 +14,30 @@ extension Deque { @frozen @usableFromInline + @unsafe internal struct _UnsafeHandle { @usableFromInline + @unsafe let _header: UnsafeMutablePointer<_DequeBufferHeader> @usableFromInline + @unsafe let _elements: UnsafeMutablePointer #if DEBUG @usableFromInline + @safe let _isMutable: Bool #endif @inlinable @inline(__always) + @unsafe init( header: UnsafeMutablePointer<_DequeBufferHeader>, elements: UnsafeMutablePointer, isMutable: Bool ) { - self._header = header - self._elements = elements + unsafe self._header = header + unsafe self._elements = elements #if DEBUG self._isMutable = isMutable #endif @@ -43,6 +48,7 @@ extension Deque { extension Deque._UnsafeHandle { @inlinable @inline(__always) + @safe func assertMutable() { #if DEBUG assert(_isMutable) @@ -57,34 +63,35 @@ extension Deque._UnsafeHandle { @inlinable @inline(__always) var header: _DequeBufferHeader { - _header.pointee + unsafe _header.pointee } @inlinable @inline(__always) var capacity: Int { - _header.pointee.capacity + unsafe _header.pointee.capacity } @inlinable @inline(__always) var count: Int { - get { _header.pointee.count } - nonmutating set { _header.pointee.count = newValue } + get { unsafe _header.pointee.count } + nonmutating set { unsafe _header.pointee.count = newValue } } @inlinable @inline(__always) var startSlot: Slot { - get { _header.pointee.startSlot } - nonmutating set { _header.pointee.startSlot = newValue } + get { unsafe _header.pointee.startSlot } + nonmutating set { unsafe _header.pointee.startSlot = newValue } } @inlinable @inline(__always) + @unsafe func ptr(at slot: Slot) -> UnsafeMutablePointer { - assert(slot.position >= 0 && slot.position <= capacity) - return _elements + slot.position + assert(unsafe slot.position >= 0 && slot.position <= capacity) + return unsafe _elements + slot.position } } @@ -93,20 +100,20 @@ extension Deque._UnsafeHandle { @inline(__always) var mutableBuffer: UnsafeMutableBufferPointer { assertMutable() - return .init(start: _elements, count: _header.pointee.capacity) + return unsafe .init(start: _elements, count: _header.pointee.capacity) } @inlinable internal func buffer(for range: Range) -> UnsafeBufferPointer { - assert(range.upperBound.position <= capacity) - return .init(start: _elements + range.lowerBound.position, count: range._count) + assert(unsafe range.upperBound.position <= capacity) + return unsafe .init(start: _elements + range.lowerBound.position, count: range._count) } @inlinable @inline(__always) internal func mutableBuffer(for range: Range) -> UnsafeMutableBufferPointer { assertMutable() - return .init(mutating: buffer(for: range)) + return unsafe .init(mutating: buffer(for: range)) } } @@ -117,14 +124,14 @@ extension Deque._UnsafeHandle { @inlinable @inline(__always) internal var limSlot: Slot { - Slot(at: capacity) + unsafe Slot(at: capacity) } @inlinable internal func slot(after slot: Slot) -> Slot { - assert(slot.position < capacity) + assert(unsafe slot.position < capacity) let position = slot.position + 1 - if position >= capacity { + if unsafe position >= capacity { return Slot(at: 0) } return Slot(at: position) @@ -132,6 +139,7 @@ extension Deque._UnsafeHandle { @inlinable internal func slot(before slot: Slot) -> Slot { + let capacity = unsafe self.capacity assert(slot.position < capacity) if slot.position == 0 { return Slot(at: capacity - 1) } return Slot(at: slot.position - 1) @@ -139,6 +147,7 @@ extension Deque._UnsafeHandle { @inlinable internal func slot(_ slot: Slot, offsetBy delta: Int) -> Slot { + let capacity = unsafe self.capacity assert(slot.position <= capacity) let position = slot.position + delta if delta >= 0 { @@ -152,13 +161,14 @@ extension Deque._UnsafeHandle { @inlinable @inline(__always) internal var endSlot: Slot { - slot(startSlot, offsetBy: count) + unsafe slot(startSlot, offsetBy: count) } /// Return the storage slot corresponding to the specified offset, which may /// or may not address an existing element. @inlinable internal func slot(forOffset offset: Int) -> Slot { + let capacity = unsafe self.capacity assert(offset >= 0) assert(offset <= capacity) // Not `count`! @@ -166,7 +176,7 @@ extension Deque._UnsafeHandle { // fact that `offset` is guaranteed to fall in the range `0 ..< capacity`. // Eliminating the overflow checks leads to a measurable speedup for // random-access subscript operations. (Up to 2x on some microbenchmarks.) - let position = startSlot.position &+ offset + let position = unsafe startSlot.position &+ offset guard position < capacity else { return Slot(at: position &- capacity) } return Slot(at: position) } @@ -174,98 +184,112 @@ extension Deque._UnsafeHandle { extension Deque._UnsafeHandle { @inlinable + @unsafe internal func segments() -> _UnsafeDequeSegments { - let wrap = capacity - startSlot.position - if count <= wrap { - return .init(start: ptr(at: startSlot), count: count) + let wrap = unsafe capacity - startSlot.position + if unsafe count <= wrap { + return unsafe .init(start: ptr(at: startSlot), count: count) } - return .init(first: ptr(at: startSlot), count: wrap, + return unsafe .init(first: ptr(at: startSlot), count: wrap, second: ptr(at: .zero), count: count - wrap) } @inlinable + @unsafe internal func segments( forOffsets offsets: Range ) -> _UnsafeDequeSegments { - assert(offsets.lowerBound >= 0 && offsets.upperBound <= count) - let lower = slot(forOffset: offsets.lowerBound) - let upper = slot(forOffset: offsets.upperBound) + assert(unsafe offsets.lowerBound >= 0 && offsets.upperBound <= count) + let lower = unsafe slot(forOffset: offsets.lowerBound) + let upper = unsafe slot(forOffset: offsets.upperBound) if offsets.count == 0 || lower < upper { - return .init(start: ptr(at: lower), count: offsets.count) + return unsafe .init(start: ptr(at: lower), count: offsets.count) } - return .init(first: ptr(at: lower), count: capacity - lower.position, - second: ptr(at: .zero), count: upper.position) + return unsafe .init( + first: ptr(at: lower), count: capacity - lower.position, + second: ptr(at: .zero), count: upper.position) } @inlinable @inline(__always) + @unsafe internal func mutableSegments() -> _UnsafeMutableDequeSegments { assertMutable() - return .init(mutating: segments()) + return unsafe .init(mutating: segments()) } @inlinable @inline(__always) + @unsafe internal func mutableSegments( forOffsets range: Range ) -> _UnsafeMutableDequeSegments { assertMutable() - return .init(mutating: segments(forOffsets: range)) + return unsafe .init(mutating: segments(forOffsets: range)) } } extension Deque._UnsafeHandle { @inlinable + @unsafe internal func availableSegments() -> _UnsafeMutableDequeSegments { assertMutable() - let endSlot = self.endSlot - guard count < capacity else { return .init(start: ptr(at: endSlot), count: 0) } - if endSlot < startSlot { return .init(mutableBuffer(for: endSlot ..< startSlot)) } - return .init(mutableBuffer(for: endSlot ..< limSlot), - mutableBuffer(for: .zero ..< startSlot)) + let endSlot = unsafe self.endSlot + guard unsafe count < capacity else { + return unsafe .init(start: ptr(at: endSlot), count: 0) + } + if unsafe endSlot < startSlot { + return unsafe .init(mutableBuffer(for: endSlot ..< startSlot)) + } + return unsafe .init( + mutableBuffer(for: endSlot ..< limSlot), + mutableBuffer(for: .zero ..< startSlot)) } } extension Deque._UnsafeHandle { @inlinable @discardableResult + @unsafe func initialize( at start: Slot, from source: UnsafeBufferPointer ) -> Slot { - assert(start.position + source.count <= capacity) + assert(unsafe start.position + source.count <= capacity) guard source.count > 0 else { return start } - ptr(at: start).initialize(from: source.baseAddress!, count: source.count) + unsafe ptr(at: start).initialize(from: source.baseAddress!, count: source.count) return Slot(at: start.position + source.count) } @inlinable @inline(__always) @discardableResult + @unsafe func moveInitialize( at start: Slot, from source: UnsafeMutableBufferPointer ) -> Slot { - assert(start.position + source.count <= capacity) + assert(unsafe start.position + source.count <= capacity) guard source.count > 0 else { return start } - ptr(at: start).moveInitialize(from: source.baseAddress!, count: source.count) + unsafe ptr(at: start).moveInitialize(from: source.baseAddress!, count: source.count) return Slot(at: start.position + source.count) } @inlinable @inline(__always) @discardableResult + @unsafe public func move( from source: Slot, to target: Slot, count: Int ) -> (source: Slot, target: Slot) { assert(count >= 0) - assert(source.position + count <= self.capacity) - assert(target.position + count <= self.capacity) + assert(unsafe source.position + count <= self.capacity) + assert(unsafe target.position + count <= self.capacity) guard count > 0 else { return (source, target) } - ptr(at: target).moveInitialize(from: ptr(at: source), count: count) - return (slot(source, offsetBy: count), slot(target, offsetBy: count)) + unsafe ptr(at: target).moveInitialize(from: ptr(at: source), count: count) + return unsafe (slot(source, offsetBy: count), slot(target, offsetBy: count)) } } @@ -273,17 +297,18 @@ extension Deque._UnsafeHandle { /// Copy elements into a new storage instance without changing capacity or /// layout. @inlinable + @unsafe internal func copyElements() -> Deque._Storage { - let object = _DequeBuffer.create( + let object = unsafe _DequeBuffer.create( minimumCapacity: capacity, - makingHeaderWith: { _ in header }) - let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object)) - guard self.count > 0 else { return result } - result.update { target in - let source = self.segments() - target.initialize(at: startSlot, from: source.first) - if let second = source.second { - target.initialize(at: .zero, from: second) + makingHeaderWith: { _ in unsafe header }) + let result = unsafe Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object)) + guard unsafe self.count > 0 else { return result } + unsafe result.update { target in + let source = unsafe self.segments() + unsafe target.initialize(at: startSlot, from: source.first) + if let second = unsafe source.second { + unsafe target.initialize(at: .zero, from: second) } } return result @@ -292,24 +317,25 @@ extension Deque._UnsafeHandle { /// Copy elements into a new storage instance with the specified minimum /// capacity. @inlinable + @unsafe internal func copyElements(minimumCapacity: Int) -> Deque._Storage { - assert(minimumCapacity >= count) + assert(unsafe minimumCapacity >= count) let object = _DequeBuffer.create( minimumCapacity: minimumCapacity, makingHeaderWith: { _ in - return _DequeBufferHeader( + return unsafe _DequeBufferHeader( capacity: minimumCapacity, count: count, startSlot: .zero) }) - let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object)) - guard count > 0 else { return result } - result.update { target in - assert(target.count == count && target.startSlot.position == 0) - let source = self.segments() - let next = target.initialize(at: .zero, from: source.first) - if let second = source.second { - target.initialize(at: next, from: second) + let result = unsafe Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object)) + guard unsafe count > 0 else { return result } + unsafe result.update { target in + assert(unsafe target.count == count && target.startSlot.position == 0) + let source = unsafe self.segments() + let next = unsafe target.initialize(at: .zero, from: source.first) + if let second = unsafe source.second { + unsafe target.initialize(at: next, from: second) } } return result @@ -319,9 +345,10 @@ extension Deque._UnsafeHandle { /// capacity. Existing indices in `self` won't necessarily be valid in the /// result. `self` is left empty. @inlinable + @unsafe internal func moveElements(minimumCapacity: Int) -> Deque._Storage { assertMutable() - let count = self.count + let count = unsafe self.count assert(minimumCapacity >= count) let object = _DequeBuffer.create( minimumCapacity: minimumCapacity, @@ -331,37 +358,38 @@ extension Deque._UnsafeHandle { count: count, startSlot: .zero) }) - let result = Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object)) + let result = unsafe Deque._Storage(_buffer: ManagedBufferPointer(unsafeBufferObject: object)) guard count > 0 else { return result } - result.update { target in - let source = self.mutableSegments() - let next = target.moveInitialize(at: .zero, from: source.first) - if let second = source.second { - target.moveInitialize(at: next, from: second) + unsafe result.update { target in + let source = unsafe self.mutableSegments() + let next = unsafe target.moveInitialize(at: .zero, from: source.first) + if let second = unsafe source.second { + unsafe target.moveInitialize(at: next, from: second) } } - self.count = 0 + unsafe self.count = 0 return result } } extension Deque._UnsafeHandle { @inlinable + @unsafe internal func withUnsafeSegment( startingAt start: Int, maxCount: Int?, _ body: (UnsafeBufferPointer) throws -> R ) rethrows -> (end: Int, result: R) { - assert(start <= count) - guard start < count else { - return try (count, body(UnsafeBufferPointer(start: nil, count: 0))) + assert(unsafe start <= count) + guard unsafe start < count else { + return unsafe try (count, body(UnsafeBufferPointer(start: nil, count: 0))) } - let endSlot = self.endSlot + let endSlot = unsafe self.endSlot - let segmentStart = self.slot(forOffset: start) - let segmentEnd = segmentStart < endSlot ? endSlot : limSlot + let segmentStart = unsafe self.slot(forOffset: start) + let segmentEnd = unsafe segmentStart < endSlot ? endSlot : limSlot let count = Swift.min(maxCount ?? Int.max, segmentEnd.position - segmentStart.position) - let result = try body(UnsafeBufferPointer(start: ptr(at: segmentStart), count: count)) + let result = unsafe try body(UnsafeBufferPointer(start: ptr(at: segmentStart), count: count)) return (start + count, result) } } @@ -375,16 +403,17 @@ extension Deque._UnsafeHandle { /// This function does not validate its input arguments in release builds. Nor /// does it ensure that the storage buffer is uniquely referenced. @inlinable + @unsafe internal func uncheckedReplaceInPlace( inOffsets range: Range, with newElements: C ) where C.Element == Element { assertMutable() - assert(range.upperBound <= count) + assert(unsafe range.upperBound <= count) assert(newElements.count == range.count) guard !range.isEmpty else { return } - let target = mutableSegments(forOffsets: range) - target.reassign(copying: newElements) + let target = unsafe mutableSegments(forOffsets: range) + unsafe target.reassign(copying: newElements) } } @@ -397,11 +426,12 @@ extension Deque._UnsafeHandle { /// This function does not validate its input arguments in release builds. Nor /// does it ensure that the storage buffer is uniquely referenced. @inlinable + @unsafe internal func uncheckedAppend(_ element: Element) { assertMutable() - assert(count < capacity) - ptr(at: endSlot).initialize(to: element) - count += 1 + assert(unsafe count < capacity) + unsafe ptr(at: endSlot).initialize(to: element) + unsafe count += 1 } /// Append the contents of `source` to this buffer. The buffer must have @@ -410,14 +440,15 @@ extension Deque._UnsafeHandle { /// This function does not validate its input arguments in release builds. Nor /// does it ensure that the storage buffer is uniquely referenced. @inlinable + @unsafe internal func uncheckedAppend(contentsOf source: UnsafeBufferPointer) { assertMutable() - assert(count + source.count <= capacity) + assert(unsafe count + source.count <= capacity) guard source.count > 0 else { return } - let c = self.count - count += source.count - let gap = mutableSegments(forOffsets: c ..< count) - gap.initialize(copying: source) + let c = unsafe self.count + unsafe count += source.count + let gap = unsafe mutableSegments(forOffsets: c ..< count) + unsafe gap.initialize(copying: source) } } @@ -425,13 +456,14 @@ extension Deque._UnsafeHandle { extension Deque._UnsafeHandle { @inlinable + @unsafe internal func uncheckedPrepend(_ element: Element) { assertMutable() - assert(count < capacity) - let slot = self.slot(before: startSlot) - ptr(at: slot).initialize(to: element) - startSlot = slot - count += 1 + assert(unsafe count < capacity) + let slot = unsafe self.slot(before: startSlot) + unsafe ptr(at: slot).initialize(to: element) + unsafe startSlot = slot + unsafe count += 1 } /// Prepend the contents of `source` to this buffer. The buffer must have @@ -440,17 +472,18 @@ extension Deque._UnsafeHandle { /// This function does not validate its input arguments in release builds. Nor /// does it ensure that the storage buffer is uniquely referenced. @inlinable + @unsafe internal func uncheckedPrepend(contentsOf source: UnsafeBufferPointer) { assertMutable() - assert(count + source.count <= capacity) + assert(unsafe count + source.count <= capacity) guard source.count > 0 else { return } - let oldStart = startSlot - let newStart = self.slot(startSlot, offsetBy: -source.count) - startSlot = newStart - count += source.count + let oldStart = unsafe startSlot + let newStart = unsafe self.slot(startSlot, offsetBy: -source.count) + unsafe startSlot = newStart + unsafe count += source.count - let gap = mutableWrappedBuffer(between: newStart, and: oldStart) - gap.initialize(copying: source) + let gap = unsafe mutableWrappedBuffer(between: newStart, and: oldStart) + unsafe gap.initialize(copying: source) } } @@ -469,30 +502,34 @@ extension Deque._UnsafeHandle { /// - Parameter offset: The desired offset from the start at which to place /// the first element. @inlinable + @unsafe internal func uncheckedInsert( contentsOf newElements: __owned C, count newCount: Int, atOffset offset: Int ) where C.Element == Element { assertMutable() - assert(offset <= count) + assert(unsafe offset <= count) assert(newElements.count == newCount) guard newCount > 0 else { return } - let gap = openGap(ofSize: newCount, atOffset: offset) - gap.initialize(copying: newElements) + let gap = unsafe openGap(ofSize: newCount, atOffset: offset) + unsafe gap.initialize(copying: newElements) } @inlinable + @unsafe internal func mutableWrappedBuffer( between start: Slot, and end: Slot ) -> _UnsafeMutableDequeSegments { - assert(start.position <= capacity) - assert(end.position <= capacity) + assert(unsafe start.position <= capacity) + assert(unsafe end.position <= capacity) if start < end { - return .init(start: ptr(at: start), count: end.position - start.position) + return unsafe .init( + start: ptr(at: start), + count: end.position - start.position) } - return .init( + return unsafe .init( first: ptr(at: start), count: capacity - start.position, second: ptr(at: .zero), count: end.position) } @@ -508,27 +545,28 @@ extension Deque._UnsafeHandle { /// - Parameter offset: The offset from the start at which the uninitialized /// slots should start. @inlinable + @unsafe internal func openGap( ofSize gapSize: Int, atOffset offset: Int ) -> _UnsafeMutableDequeSegments { assertMutable() - assert(offset >= 0 && offset <= self.count) - assert(self.count + gapSize <= capacity) + assert(unsafe offset >= 0 && offset <= self.count) + assert(unsafe self.count + gapSize <= capacity) assert(gapSize > 0) let headCount = offset - let tailCount = count - offset + let tailCount = unsafe count - offset if tailCount <= headCount { // Open the gap by sliding elements to the right. - let originalEnd = self.slot(startSlot, offsetBy: count) - let newEnd = self.slot(startSlot, offsetBy: count + gapSize) - let gapStart = self.slot(forOffset: offset) - let gapEnd = self.slot(gapStart, offsetBy: gapSize) + let originalEnd = unsafe self.slot(startSlot, offsetBy: count) + let newEnd = unsafe self.slot(startSlot, offsetBy: count + gapSize) + let gapStart = unsafe self.slot(forOffset: offset) + let gapEnd = unsafe self.slot(gapStart, offsetBy: gapSize) - let sourceIsContiguous = gapStart <= originalEnd.orIfZero(capacity) - let targetIsContiguous = gapEnd <= newEnd.orIfZero(capacity) + let sourceIsContiguous = unsafe gapStart <= originalEnd.orIfZero(capacity) + let targetIsContiguous = unsafe gapEnd <= newEnd.orIfZero(capacity) if sourceIsContiguous && targetIsContiguous { // No need to deal with wrapping; we just need to slide @@ -538,7 +576,7 @@ extension Deque._UnsafeHandle { // // 0) ....ABCDE̲F̲G̲H..... EFG̲H̲.̲........ABCD .̲.......ABCDEFGH̲.̲ // 1) ....ABCD.̲.̲.̲EFGH.. EF.̲.̲.̲GH......ABCD .̲H......ABCDEFG.̲.̲ - move(from: gapStart, to: gapEnd, count: tailCount) + unsafe move(from: gapStart, to: gapEnd, count: tailCount) } else if targetIsContiguous { // The gap itself will be wrapped. @@ -547,9 +585,9 @@ extension Deque._UnsafeHandle { // 0) E̲FGH.........ABC̲D̲ // 1) .̲..EFGH......ABC̲D̲ // 2) .̲CDEFGH......AB.̲.̲ - assert(startSlot > originalEnd.orIfZero(capacity)) - move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position) - move(from: gapStart, to: gapEnd, count: capacity - gapStart.position) + assert(unsafe startSlot > originalEnd.orIfZero(capacity)) + unsafe move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position) + unsafe move(from: gapStart, to: gapEnd, count: capacity - gapStart.position) } else if sourceIsContiguous { // Opening the gap pushes subsequent elements across the wrap. @@ -558,8 +596,8 @@ extension Deque._UnsafeHandle { // 0) ........ABC̲D̲E̲FGH. // 1) GH......ABC̲D̲E̲F... // 2) GH......AB.̲.̲.̲CDEF - move(from: limSlot.advanced(by: -gapSize), to: .zero, count: newEnd.position) - move(from: gapStart, to: gapEnd, count: tailCount - newEnd.position) + unsafe move(from: limSlot.advanced(by: -gapSize), to: .zero, count: newEnd.position) + unsafe move(from: gapStart, to: gapEnd, count: tailCount - newEnd.position) } else { // The rest of the items are wrapped, and will remain so. @@ -569,23 +607,23 @@ extension Deque._UnsafeHandle { // 1) ...GH......AB̲C̲D̲EF // 2) DEFGH......AB̲C̲.̲.. // 3) DEFGH......A.̲.̲.̲BC - move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position) - move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize) - move(from: gapStart, to: gapEnd, count: tailCount - gapSize - originalEnd.position) + unsafe move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position) + unsafe move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize) + unsafe move(from: gapStart, to: gapEnd, count: tailCount - gapSize - originalEnd.position) } - count += gapSize - return mutableWrappedBuffer(between: gapStart, and: gapEnd.orIfZero(capacity)) + unsafe count += gapSize + return unsafe mutableWrappedBuffer(between: gapStart, and: gapEnd.orIfZero(capacity)) } // Open the gap by sliding elements to the left. - let originalStart = self.startSlot - let newStart = self.slot(originalStart, offsetBy: -gapSize) - let gapEnd = self.slot(forOffset: offset) - let gapStart = self.slot(gapEnd, offsetBy: -gapSize) + let originalStart = unsafe self.startSlot + let newStart = unsafe self.slot(originalStart, offsetBy: -gapSize) + let gapEnd = unsafe self.slot(forOffset: offset) + let gapStart = unsafe self.slot(gapEnd, offsetBy: -gapSize) - let sourceIsContiguous = originalStart <= gapEnd.orIfZero(capacity) - let targetIsContiguous = newStart <= gapStart.orIfZero(capacity) + let sourceIsContiguous = unsafe originalStart <= gapEnd.orIfZero(capacity) + let targetIsContiguous = unsafe newStart <= gapStart.orIfZero(capacity) if sourceIsContiguous && targetIsContiguous { // No need to deal with any wrapping. @@ -594,7 +632,7 @@ extension Deque._UnsafeHandle { // // 0) ....A̲B̲C̲DEFGH... GH.........̲A̲B̲CDEF .̲A̲B̲CDEFGH.......̲.̲ // 1) .ABC.̲.̲.̲DEFGH... GH......AB.̲.̲.̲CDEF .̲.̲.̲CDEFGH....AB.̲.̲ - move(from: originalStart, to: newStart, count: headCount) + unsafe move(from: originalStart, to: newStart, count: headCount) } else if targetIsContiguous { // The gap itself will be wrapped. @@ -604,8 +642,8 @@ extension Deque._UnsafeHandle { // 1) C̲D̲EFGH.....AB...̲.̲ // 2) .̲.̲EFGH.....ABCD.̲.̲ assert(originalStart >= newStart) - move(from: originalStart, to: newStart, count: capacity - originalStart.position) - move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapEnd.position) + unsafe move(from: originalStart, to: newStart, count: capacity - originalStart.position) + unsafe move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapEnd.position) } else if sourceIsContiguous { // Opening the gap pushes preceding elements across the wrap. @@ -614,8 +652,8 @@ extension Deque._UnsafeHandle { // 0) .AB̲C̲D̲EFGH......... // 1) ...̲C̲D̲EFGH.......AB // 2) CD.̲.̲.̲EFGH.......AB - move(from: originalStart, to: newStart, count: capacity - newStart.position) - move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position) + unsafe move(from: originalStart, to: newStart, count: capacity - newStart.position) + unsafe move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position) } else { // The preceding of the items are wrapped, and will remain so. @@ -624,13 +662,13 @@ extension Deque._UnsafeHandle { // 1) CD̲E̲F̲GHIJKL......AB... // 2) ..̲.̲F̲GHIJKL......ABCDE // 3) F.̲.̲.̲GHIJKL......ABCDE - move(from: originalStart, to: newStart, count: capacity - originalStart.position) - move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapSize) - move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position) + unsafe move(from: originalStart, to: newStart, count: capacity - originalStart.position) + unsafe move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapSize) + unsafe move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position) } - startSlot = newStart - count += gapSize - return mutableWrappedBuffer(between: gapStart, and: gapEnd.orIfZero(capacity)) + unsafe startSlot = newStart + unsafe count += gapSize + return unsafe mutableWrappedBuffer(between: gapStart, and: gapEnd.orIfZero(capacity)) } } @@ -638,44 +676,48 @@ extension Deque._UnsafeHandle { extension Deque._UnsafeHandle { @inlinable + @unsafe internal func uncheckedRemoveFirst() -> Element { assertMutable() - assert(count > 0) - let result = ptr(at: startSlot).move() - startSlot = slot(after: startSlot) - count -= 1 + assert(unsafe count > 0) + let result = unsafe ptr(at: startSlot).move() + unsafe startSlot = slot(after: startSlot) + unsafe count -= 1 return result } @inlinable + @unsafe internal func uncheckedRemoveLast() -> Element { assertMutable() - assert(count > 0) - let slot = self.slot(forOffset: count - 1) - let result = ptr(at: slot).move() - count -= 1 + assert(unsafe count > 0) + let slot = unsafe self.slot(forOffset: count - 1) + let result = unsafe ptr(at: slot).move() + unsafe count -= 1 return result } @inlinable + @unsafe internal func uncheckedRemoveFirst(_ n: Int) { assertMutable() - assert(count >= n) + assert(unsafe count >= n) guard n > 0 else { return } - let target = mutableSegments(forOffsets: 0 ..< n) - target.deinitialize() - startSlot = slot(startSlot, offsetBy: n) - count -= n + let target = unsafe mutableSegments(forOffsets: 0 ..< n) + unsafe target.deinitialize() + unsafe startSlot = slot(startSlot, offsetBy: n) + unsafe count -= n } @inlinable + @unsafe internal func uncheckedRemoveLast(_ n: Int) { assertMutable() - assert(count >= n) + assert(unsafe count >= n) guard n > 0 else { return } - let target = mutableSegments(forOffsets: count - n ..< count) - target.deinitialize() - count -= n + let target = unsafe mutableSegments(forOffsets: count - n ..< count) + unsafe target.deinitialize() + unsafe count -= n } /// Remove all elements stored in this instance, deinitializing their storage. @@ -683,13 +725,14 @@ extension Deque._UnsafeHandle { /// This method does not ensure that the storage buffer is uniquely /// referenced. @inlinable + @unsafe internal func uncheckedRemoveAll() { assertMutable() - guard count > 0 else { return } - let target = mutableSegments() - target.deinitialize() - count = 0 - startSlot = .zero + guard unsafe count > 0 else { return } + let target = unsafe mutableSegments() + unsafe target.deinitialize() + unsafe count = 0 + unsafe startSlot = .zero } /// Remove all elements in `bounds`, deinitializing their storage and sliding @@ -698,13 +741,14 @@ extension Deque._UnsafeHandle { /// This function does not validate its input arguments in release builds. Nor /// does it ensure that the storage buffer is uniquely referenced. @inlinable + @unsafe internal func uncheckedRemove(offsets bounds: Range) { assertMutable() - assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count) + assert(unsafe bounds.lowerBound >= 0 && bounds.upperBound <= self.count) // Deinitialize elements in `bounds`. - mutableSegments(forOffsets: bounds).deinitialize() - closeGap(offsets: bounds) + unsafe mutableSegments(forOffsets: bounds).deinitialize() + unsafe closeGap(offsets: bounds) } /// Close the gap of already uninitialized elements in `bounds`, sliding @@ -713,25 +757,26 @@ extension Deque._UnsafeHandle { /// This function does not validate its input arguments in release builds. Nor /// does it ensure that the storage buffer is uniquely referenced. @inlinable + @unsafe internal func closeGap(offsets bounds: Range) { assertMutable() - assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count) + assert(unsafe bounds.lowerBound >= 0 && bounds.upperBound <= self.count) let gapSize = bounds.count guard gapSize > 0 else { return } - let gapStart = self.slot(forOffset: bounds.lowerBound) - let gapEnd = self.slot(forOffset: bounds.upperBound) + let gapStart = unsafe self.slot(forOffset: bounds.lowerBound) + let gapEnd = unsafe self.slot(forOffset: bounds.upperBound) let headCount = bounds.lowerBound - let tailCount = count - bounds.upperBound + let tailCount = unsafe count - bounds.upperBound if headCount >= tailCount { // Close the gap by sliding elements to the left. - let originalEnd = endSlot - let newEnd = self.slot(forOffset: count - gapSize) + let originalEnd = unsafe endSlot + let newEnd = unsafe self.slot(forOffset: count - gapSize) - let sourceIsContiguous = gapEnd < originalEnd.orIfZero(capacity) - let targetIsContiguous = gapStart <= newEnd.orIfZero(capacity) + let sourceIsContiguous = unsafe gapEnd < originalEnd.orIfZero(capacity) + let targetIsContiguous = unsafe gapStart <= newEnd.orIfZero(capacity) if tailCount == 0 { // No need to move any elements. } else if sourceIsContiguous && targetIsContiguous { @@ -739,17 +784,17 @@ extension Deque._UnsafeHandle { // 0) ....ABCD.̲.̲.̲EFGH.. EF.̲.̲.̲GH........ABCD .̲.̲.̲E..........ABCD.̲.̲ .̲.̲.̲EF........ABCD .̲.̲.̲DE.......ABC // 1) ....ABCDE̲F̲G̲H..... EFG̲H̲.̲..........ABCD .̲.̲.̲...........ABCDE̲.̲ E̲F̲.̲..........ABCD D̲E̲.̲.........ABC - move(from: gapEnd, to: gapStart, count: tailCount) + unsafe move(from: gapEnd, to: gapStart, count: tailCount) } else if sourceIsContiguous { // The gap lies across the wrap from the subsequent elements. // 0) .̲.̲.̲EFGH.......ABCD.̲.̲ EFGH.......ABCD.̲.̲.̲ // 1) .̲.̲.̲..GH.......ABCDE̲F̲ ..GH.......ABCDE̲F̲G̲ // 2) G̲H̲.̲...........ABCDE̲F̲ GH.........ABCDE̲F̲G̲ - let c = capacity - gapStart.position + let c = unsafe capacity - gapStart.position assert(tailCount > c) - let next = move(from: gapEnd, to: gapStart, count: c) - move(from: next.source, to: .zero, count: tailCount - c) + let next = unsafe move(from: gapEnd, to: gapStart, count: c) + unsafe move(from: next.source, to: .zero, count: tailCount - c) } else if targetIsContiguous { // We need to move elements across a wrap, but the wrap will // disappear when we're done. @@ -757,8 +802,8 @@ extension Deque._UnsafeHandle { // 0) HI....ABCDE.̲.̲.̲FG // 1) HI....ABCDEF̲G̲.̲.. // 2) ......ABCDEF̲G̲H̲I. - let next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position) - move(from: .zero, to: next.target, count: originalEnd.position) + let next = unsafe move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position) + unsafe move(from: .zero, to: next.target, count: originalEnd.position) } else { // We need to move elements across a wrap that won't go away. @@ -766,18 +811,18 @@ extension Deque._UnsafeHandle { // 1) HIJKL....ABCDEF̲G̲.̲.. // 2) ...KL....ABCDEF̲G̲H̲IJ // 3) KL.......ABCDEF̲G̲H̲IJ - var next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position) - next = move(from: .zero, to: next.target, count: gapSize) - move(from: next.source, to: .zero, count: newEnd.position) + var next = unsafe move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position) + next = unsafe move(from: .zero, to: next.target, count: gapSize) + unsafe move(from: next.source, to: .zero, count: newEnd.position) } - count -= gapSize + unsafe count -= gapSize } else { // Close the gap by sliding elements to the right. - let originalStart = startSlot - let newStart = slot(startSlot, offsetBy: gapSize) + let originalStart = unsafe startSlot + let newStart = unsafe slot(startSlot, offsetBy: gapSize) - let sourceIsContiguous = originalStart < gapStart.orIfZero(capacity) - let targetIsContiguous = newStart <= gapEnd.orIfZero(capacity) + let sourceIsContiguous = unsafe originalStart < gapStart.orIfZero(capacity) + let targetIsContiguous = unsafe newStart <= gapEnd.orIfZero(capacity) if headCount == 0 { // No need to move any elements. @@ -786,15 +831,15 @@ extension Deque._UnsafeHandle { // 0) ....ABCD.̲.̲.̲EFGH..... EFGH........AB.̲.̲.̲CD .̲.̲.̲CDEFGH.......AB.̲.̲ DEFGH.......ABC.̲.̲ // 1) .......AB̲C̲D̲EFGH..... EFGH...........̲A̲B̲CD .̲A̲B̲CDEFGH..........̲.̲ DEFGH.........AB̲C̲ ABCDEFGH........̲.̲.̲ - move(from: originalStart, to: newStart, count: headCount) + unsafe move(from: originalStart, to: newStart, count: headCount) } else if sourceIsContiguous { // The gap lies across the wrap from the preceding elements. // 0) .̲.̲DEFGH.......ABC.̲.̲ .̲.̲.̲EFGH.......ABCD // 1) B̲C̲DEFGH.......A...̲.̲ B̲C̲D̲DEFGH......A... // 2) B̲C̲DEFGH...........̲A̲ B̲C̲D̲DEFGH.........A - move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapEnd.position) - move(from: startSlot, to: newStart, count: headCount - gapEnd.position) + unsafe move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapEnd.position) + unsafe move(from: startSlot, to: newStart, count: headCount - gapEnd.position) } else if targetIsContiguous { // We need to move elements across a wrap, but the wrap will // disappear when we're done. @@ -802,20 +847,20 @@ extension Deque._UnsafeHandle { // 0) CD.̲.̲.̲EFGHI.....AB // 1) ...̲C̲D̲EFGHI.....AB // 1) .AB̲C̲D̲EFGHI....... - move(from: .zero, to: gapEnd.advanced(by: -gapStart.position), count: gapStart.position) - move(from: startSlot, to: newStart, count: headCount - gapStart.position) + unsafe move(from: .zero, to: gapEnd.advanced(by: -gapStart.position), count: gapStart.position) + unsafe move(from: startSlot, to: newStart, count: headCount - gapStart.position) } else { // We need to move elements across a wrap that won't go away. // 0) FG.̲.̲.̲HIJKLMNO....ABCDE // 1) ...̲F̲G̲HIJKLMNO....ABCDE // 2) CDE̲F̲G̲HIJKLMNO....AB... // 3) CDE̲F̲G̲HIJKLMNO.......AB - move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: gapStart.position) - move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize) - move(from: startSlot, to: newStart, count: headCount - gapEnd.position) + unsafe move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: gapStart.position) + unsafe move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize) + unsafe move(from: startSlot, to: newStart, count: headCount - gapEnd.position) } - startSlot = newStart - count -= gapSize + unsafe startSlot = newStart + unsafe count -= gapSize } } } diff --git a/Sources/DequeModule/Deque/_DequeBuffer.swift b/Sources/DequeModule/Deque/_DequeBuffer.swift index 41e3e8ad..a26d4aa0 100644 --- a/Sources/DequeModule/Deque/_DequeBuffer.swift +++ b/Sources/DequeModule/Deque/_DequeBuffer.swift @@ -16,19 +16,19 @@ internal final class _DequeBuffer: ManagedBuffer<_DequeBufferHeader, Element> { @inlinable deinit { - self.withUnsafeMutablePointers { header, elements in - header.pointee._checkInvariants() + unsafe self.withUnsafeMutablePointers { header, elements in + unsafe header.pointee._checkInvariants() - let capacity = header.pointee.capacity - let count = header.pointee.count - let startSlot = header.pointee.startSlot + let capacity = unsafe header.pointee.capacity + let count = unsafe header.pointee.count + let startSlot = unsafe header.pointee.startSlot if startSlot.position + count <= capacity { - (elements + startSlot.position).deinitialize(count: count) + unsafe (elements + startSlot.position).deinitialize(count: count) } else { let firstRegion = capacity - startSlot.position - (elements + startSlot.position).deinitialize(count: firstRegion) - elements.deinitialize(count: count - firstRegion) + unsafe (elements + startSlot.position).deinitialize(count: firstRegion) + unsafe elements.deinitialize(count: count - firstRegion) } } } @@ -37,7 +37,9 @@ internal final class _DequeBuffer: ManagedBuffer<_DequeBufferHeader, El extension _DequeBuffer: CustomStringConvertible { @usableFromInline internal var description: String { - withUnsafeMutablePointerToHeader { "_DequeStorage<\(Element.self)>\($0.pointee)" } + unsafe withUnsafeMutablePointerToHeader { + unsafe "_DequeStorage<\(Element.self)>\($0.pointee)" + } } } diff --git a/Sources/DequeModule/Deque/_DequeBufferHeader.swift b/Sources/DequeModule/Deque/_DequeBufferHeader.swift index 31f37179..ecaff8f0 100644 --- a/Sources/DequeModule/Deque/_DequeBufferHeader.swift +++ b/Sources/DequeModule/Deque/_DequeBufferHeader.swift @@ -12,6 +12,7 @@ //===----------------------------------------------------------------------===// @usableFromInline +@safe internal struct _DequeBufferHeader { @usableFromInline var capacity: Int diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift index 312f8c43..b69bbba9 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Append.swift @@ -30,7 +30,7 @@ extension RigidDeque where Element: ~Copyable { @inline(__always) public mutating func append(_ item: consuming Element) { precondition(!isFull, "RigidDeque capacity overflow") - _handle.uncheckedAppend(item) + unsafe _handle.uncheckedAppend(item) } /// Adds an element to the end of the deque, if possible. @@ -107,10 +107,11 @@ extension RigidDeque where Element: ~Copyable { ) throws(E) -> Range { precondition(newItemCount >= 0, "Cannot append a negative number of items") guard newItemCount > 0 else { - return Range(uncheckedBounds: (count, count)) + return unsafe Range(uncheckedBounds: (count, count)) } precondition(freeCapacity >= newItemCount, "RigidDeque capacity overflow") - return try _handle.uncheckedAppend(addingCount: newItemCount, initializingWith: body) + return unsafe try _handle.uncheckedAppend( + addingCount: newItemCount, initializingWith: body) } } @@ -133,7 +134,7 @@ extension RigidDeque where Element: ~Copyable { moving items: UnsafeMutableBufferPointer ) -> Range { precondition(items.count <= freeCapacity, "RigidDeque capacity overflow") - return _handle.uncheckedAppend(moving: items) + return unsafe _handle.uncheckedAppend(moving: items) } #if UnstableContainersPreview @@ -152,8 +153,8 @@ extension RigidDeque where Element: ~Copyable { public mutating func append( moving items: inout InputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(last: count) count = 0 return unsafe self.append(moving: source) } @@ -175,8 +176,8 @@ extension RigidDeque where Element: ~Copyable { public mutating func append( moving items: inout OutputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe self.append(moving: source) } @@ -204,7 +205,7 @@ extension RigidDeque /*where Element: Copyable*/ { precondition( items.count <= freeCapacity, "RigidDeque capacity overflow") - return _handle.uncheckedAppend(copying: items) + return unsafe _handle.uncheckedAppend(copying: items) } /// Copies the elements of a buffer and append them to the end of this @@ -296,7 +297,7 @@ extension RigidDeque /*where Element: Copyable*/ { } if done != nil { return } - var it = _handle.uncheckedAppend(copyingPrefixOf: newElements) + var it = unsafe _handle.uncheckedAppend(copyingPrefixOf: newElements) precondition(it.next() == nil, "RigidDeque capacity overflow") } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift index b82726ad..a8bcde59 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Consumption.swift @@ -43,19 +43,19 @@ extension RigidDeque where Element: ~Copyable { consumingWith consumer: (inout InputSpan) -> Void ) -> Index { _checkValidBounds(subrange) - let segments = self._handle.mutableSegments(forOffsets: subrange) + let segments = unsafe self._handle.mutableSegments(forOffsets: subrange) - var span = InputSpan( + var span = unsafe InputSpan( buffer: segments.first, initializedCount: segments.first.count) consumer(&span) _ = consume span - if let second = segments.second { - var span = InputSpan(buffer: second, initializedCount: second.count) + if let second = unsafe segments.second { + var span = unsafe InputSpan(buffer: second, initializedCount: second.count) consumer(&span) _ = consume span } - _handle.closeGap(offsets: subrange) + unsafe _handle.closeGap(offsets: subrange) return subrange.lowerBound } @@ -188,13 +188,16 @@ extension RigidDeque where Element: ~Copyable { @available(SwiftStdlib 5.0, *) @frozen + @safe public struct SubrangeConsumer: ~Copyable, ~Escapable { // FIXME: We have to use our own MutableRef because the standard one // provides no access to the underlying pointer. See deinit why we need it. @usableFromInline + @unsafe // Setter internal var _base: _MutableRef @usableFromInline + @unsafe // Setter internal var _offsetRange: Range // FIXME: This ought to be using `Element` directly, but when the package is @@ -203,33 +206,36 @@ extension RigidDeque where Element: ~Copyable { // failure. The availability indicates it may be `Iterable.Element` via // the `Container` conformance; this is super confusing though. @usableFromInline + @unsafe internal var _buffer1: UnsafeMutableBufferPointer<_Element> @usableFromInline + @unsafe internal var _buffer2: UnsafeMutableBufferPointer<_Element> @_alwaysEmitIntoClient @inline(__always) + @safe @_lifetime(&_base) internal init(_base: inout RigidDeque, offsetRange: Range) { _base._checkValidBounds(offsetRange) - let segments = _base._handle.mutableSegments(forOffsets: offsetRange) - self._buffer1 = segments.first - self._buffer2 = segments.second ?? .init(start: nil, count: 0) - self._base = _MutableRef(&_base) - self._offsetRange = offsetRange + let segments = unsafe _base._handle.mutableSegments(forOffsets: offsetRange) + unsafe self._buffer1 = segments.first + unsafe self._buffer2 = segments.second ?? .init(start: nil, count: 0) + unsafe self._base = _MutableRef(&_base) + unsafe self._offsetRange = offsetRange } @inlinable deinit { - self._buffer1.deinitialize() - self._buffer2.deinitialize() + unsafe self._buffer1.deinitialize() + unsafe self._buffer2.deinitialize() // FIXME: This needs to be written as // self._base[]._handle.closeGap(offsets: self._offsetRange) // but unfortunately we cannot mutate self in deinit yet. // Inout's dereferencing operation is necessarily declared mutating // to avoid exclusivity violations. - self._base._pointer.pointee._handle.closeGap(offsets: self._offsetRange) + unsafe self._base._pointer.pointee._handle.closeGap(offsets: self._offsetRange) } } } @@ -240,28 +246,28 @@ extension RigidDeque.SubrangeConsumer where Element: ~Copyable { @inlinable public var count: Int { - _buffer1.count + _buffer2.count + unsafe _buffer1.count + _buffer2.count } @inlinable @_lifetime(&self) @_lifetime(self: copy self) public mutating func drainNext(maxCount: Int) -> InputSpan { - if _buffer1.isEmpty { - if _buffer2.isEmpty { + if unsafe _buffer1.isEmpty { + if unsafe _buffer2.isEmpty { return .init() } - swap(&_buffer1, &_buffer2) + unsafe swap(&_buffer1, &_buffer2) } - let buffer = _buffer1._trim(first: maxCount) - return _overrideLifetime( + let buffer = unsafe _buffer1._trim(first: maxCount) + return unsafe _overrideLifetime( InputSpan(buffer: buffer, initializedCount: buffer.count), mutating: &self) } @inlinable public consuming func finalize() -> Int { - _offsetRange.lowerBound + unsafe _offsetRange.lowerBound } } #endif diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+ContainerOperations.swift b/Sources/DequeModule/RigidDeque/RigidDeque+ContainerOperations.swift index 210d92ad..fc70cd13 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+ContainerOperations.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+ContainerOperations.swift @@ -50,9 +50,9 @@ extension RigidDeque where Element: ~Copyable { @_lifetime(borrow self) public func nextSpan(after index: inout Int) -> Span { _checkValidIndex(index) - let segment = self._handle.nextSegment(after: index) + let segment = unsafe self._handle.nextSegment(after: index) index &+= segment.count - return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) + return unsafe _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) } @_alwaysEmitIntoClient @@ -63,9 +63,9 @@ extension RigidDeque where Element: ~Copyable { _checkValidIndex(index) _checkValidIndex(limit) precondition(maxCount > 0, "maxCount must be positive") - let segment = self._handle.nextSegment( + let segment = unsafe self._handle.nextSegment( after: &index, maxCount: maxCount, limitedBy: limit) - return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) + return unsafe _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) } @_lifetime(&self) @@ -73,9 +73,9 @@ extension RigidDeque where Element: ~Copyable { after index: inout Int ) -> MutableSpan { _checkValidIndex(index) - let segment = self._handle.nextSegment(after: index) + let segment = unsafe self._handle.nextSegment(after: index) index &+= segment.count - return _overrideLifetime( + return unsafe _overrideLifetime( MutableSpan(_unsafeElements: .init(mutating: segment)), mutating: &self) } @@ -87,9 +87,9 @@ extension RigidDeque where Element: ~Copyable { _checkValidIndex(index) _checkValidIndex(limit) precondition(maxCount > 0, "maxCount must be positive") - let segment = self._handle.nextSegment( + let segment = unsafe self._handle.nextSegment( after: &index, maxCount: maxCount, limitedBy: limit) - return _overrideLifetime( + return unsafe _overrideLifetime( MutableSpan(_unsafeElements: .init(mutating: segment)), mutating: &self) } @@ -97,7 +97,7 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient public func spanBoundary(before index: Index) -> (index: Index, distance: Int) { precondition(index >= 0 && index <= count, "Index out of bounds") - let r = self._handle.spanBoundary(before: index) + let r = unsafe self._handle.spanBoundary(before: index) return (r.offset, r.distance) } @@ -108,7 +108,7 @@ extension RigidDeque where Element: ~Copyable { precondition(index >= 0 && index <= count, "Index out of bounds") precondition(limit >= 0 && limit <= count, "Index out of bounds") precondition(maxDistance > 0, "maxDistance must be positive") - let r = self._handle.spanBoundary(before: index, maxDistance: maxDistance, limitedBy: limit) + let r = unsafe self._handle.spanBoundary(before: index, maxDistance: maxDistance, limitedBy: limit) return (r.offset, r.distance) } @@ -118,10 +118,10 @@ extension RigidDeque where Element: ~Copyable { // FIXME: Remove this in favor of the BidirectionalContainer algorithm. _checkValidIndex(index) precondition(maxCount > 0, "maxCount must be positive") - let segment = self._handle + let segment = unsafe self._handle .previousSegment(before: index) ._extracting(last: maxCount) index &-= segment.count - return _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) + return unsafe _overrideLifetime(Span(_unsafeElements: segment), borrowing: self) } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Deprecations.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Deprecations.swift index 78a7de0d..1d940056 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Deprecations.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Deprecations.swift @@ -32,7 +32,7 @@ extension RigidDeque where Element: ~Copyable { @available(*, deprecated, renamed: "setCapacity(_:)") @_alwaysEmitIntoClient public mutating func reallocate(capacity newCapacity: Int) { - _handle.reallocate(capacity: newCapacity) + unsafe _handle.reallocate(capacity: newCapacity) } /// Replaces the specified range of elements by a given count of new items, @@ -116,11 +116,12 @@ extension RigidDeque where Element: ~Copyable { /// - Complexity: O(`self.count` + `items.count`) @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") @_alwaysEmitIntoClient + @unsafe public mutating func replace( removing subrange: Range, moving items: UnsafeMutableBufferPointer, ) { - replaceSubrange(subrange, moving: items) + unsafe replaceSubrange(subrange, moving: items) } /// Replaces the specified range of elements by moving the contents of an @@ -155,6 +156,7 @@ extension RigidDeque where Element: ~Copyable { removing subrange: Range, moving items: inout OutputSpan ) { + self.replaceSubrange(subrange, moving: &items) } } @@ -188,11 +190,12 @@ extension RigidDeque /* where Element: Copyable */ { /// - Complexity: O(`self.count` + `items.count`) @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") @inlinable + @unsafe public mutating func replace( removing subrange: Range, copying items: UnsafeBufferPointer ) { - replaceSubrange(subrange, copying: items) + unsafe replaceSubrange(subrange, copying: items) } /// Replaces the specified subrange of elements by copying the elements of @@ -223,11 +226,12 @@ extension RigidDeque /* where Element: Copyable */ { /// - Complexity: O(`self.count` + `items.count`) @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") @inlinable + @unsafe public mutating func replace( removing subrange: Range, copying items: UnsafeMutableBufferPointer ) { - replaceSubrange(subrange, copying: items) + unsafe replaceSubrange(subrange, copying: items) } /// Replaces the specified subrange of elements by copying the elements of diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift index b4d630d3..0b04ee54 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Equatable.swift @@ -18,7 +18,7 @@ import InternalCollectionsUtilities @available(SwiftStdlib 5.0, *) extension RigidDeque where Element: ~Copyable { public func isTriviallyIdentical(to other: borrowing Self) -> Bool { - self._handle.isIdentical(to: other._handle) + unsafe self._handle.isIdentical(to: other._handle) } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift index 42f03b92..9ba77c45 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Hashable.swift @@ -25,10 +25,10 @@ extension RigidDeque where Element: Hashable & ~Copyable { @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(self.count) - let segments = self._handle.segments() - segments.first.span._hashContents(into: &hasher) - if let second = segments.second { - second.span._hashContents(into: &hasher) + let segments = unsafe self._handle.segments() + unsafe segments.first.span._hashContents(into: &hasher) + if let second = unsafe segments.second { + unsafe second.span._hashContents(into: &hasher) } } } @@ -38,10 +38,10 @@ extension RigidDeque where Element: Hashable { @inlinable public func hash(into hasher: inout Hasher) { hasher.combine(self.count) - let segments = self._handle.segments() - segments.first.span._hashContents(into: &hasher) - if let second = segments.second { - second.span._hashContents(into: &hasher) + let segments = unsafe self._handle.segments() + unsafe segments.first.span._hashContents(into: &hasher) + if let second = unsafe segments.second { + unsafe second.span._hashContents(into: &hasher) } } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift index f21c01d2..e276fe43 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Initializers.swift @@ -22,13 +22,13 @@ extension RigidDeque where Element: ~Copyable { /// - Complexity: O(1) @inlinable public init() { - self.init(_handle: .allocate(capacity: 0)) + unsafe self.init(_handle: .allocate(capacity: 0)) } /// Creates an empty rigid deque with the specified capacity. @_alwaysEmitIntoClient public init(capacity: Int) { - self.init(_handle: .allocate(capacity: capacity)) + unsafe self.init(_handle: .allocate(capacity: capacity)) } /// Creates a rigid deque with the specified capacity, then calls the given @@ -45,7 +45,7 @@ extension RigidDeque where Element: ~Copyable { capacity: Int, initializingWith initializer: (inout OutputSpan) throws(E) -> Void ) throws(E) { - self.init(_handle: .allocate(capacity: capacity)) + unsafe self.init(_handle: .allocate(capacity: capacity)) try self.append(addingCount: capacity, initializingWith: initializer) } } @@ -77,8 +77,8 @@ extension RigidDeque /*where Element: Copyable*/ { @inlinable public init(repeating repeatedValue: Element, count: Int) { self.init(capacity: count) - _handle.mutableBuffer.initialize(repeating: repeatedValue) - _handle.count = count + unsafe _handle.mutableBuffer.initialize(repeating: repeatedValue) + unsafe _handle._count = count } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift index 9ad36fd3..e82c9c1b 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Insertions.swift @@ -42,7 +42,7 @@ extension RigidDeque where Element: ~Copyable { public mutating func insert(_ item: consuming Element, at index: Int) -> Int { precondition(!isFull, "RigidDeque capacity overflow") _checkValidIndex(index) - return _handle.uncheckedInsert(item, at: index) + return unsafe _handle.uncheckedInsert(item, at: index) } } @@ -104,7 +104,7 @@ extension RigidDeque where Element: ~Copyable { precondition(newItemCount >= 0, "Cannot add a negative number of items") guard newItemCount > 0 else { return index ..< index } precondition(newItemCount <= freeCapacity, "RigidDeque capacity overflow") - return try _handle.uncheckedInsert( + return unsafe try _handle.uncheckedInsert( addingCount: newItemCount, at: index, initializingWith: initializer) } } @@ -131,15 +131,16 @@ extension RigidDeque where Element: ~Copyable { /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func insert( moving items: UnsafeMutableBufferPointer, at index: Int ) -> Range { guard !items.isEmpty else { return index ..< index } - var remainder = items + var remainder = unsafe items let range = insert(addingCount: items.count, at: index) { target in - target.withUnsafeMutableBufferPointer { buffer, count in - buffer.moveInitializeAll( + unsafe target.withUnsafeMutableBufferPointer { buffer, count in + unsafe buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) count = buffer.count } @@ -172,8 +173,8 @@ extension RigidDeque where Element: ~Copyable { moving items: inout InputSpan, at index: Int ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(last: count) count = 0 return unsafe self.insert(moving: source, at: index) } @@ -203,8 +204,8 @@ extension RigidDeque where Element: ~Copyable { moving items: inout OutputSpan, at index: Int ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe self.insert(moving: source, at: index) } @@ -240,12 +241,12 @@ extension RigidDeque /* where Element: Copyable */ { copying items: UnsafeBufferPointer, at index: Int ) -> Range { guard items.count > 0 else { return index ..< index } - var remainder = items + var remainder = unsafe items let range = insert(addingCount: remainder.count, at: index) { target in - target.withUnsafeMutableBufferPointer { buffer, count in - buffer.initializeAll( + unsafe target.withUnsafeMutableBufferPointer { buffer, count in + unsafe buffer.initializeAll( fromContentsOf: remainder._extracting(first: buffer.count)) - remainder = remainder._extracting(droppingFirst: buffer.count) + unsafe remainder = remainder._extracting(droppingFirst: buffer.count) count = buffer.count } } @@ -276,6 +277,7 @@ extension RigidDeque /* where Element: Copyable */ { /// - Complexity: O(`count` + `items.count`) @inlinable @discardableResult + @unsafe public mutating func insert( copying items: UnsafeMutableBufferPointer, at index: Int @@ -319,7 +321,7 @@ extension RigidDeque /* where Element: Copyable */ { newCount: Int ) -> Range { let res: Range? = items.withContiguousStorageIfAvailable { src in - self.insert(copying: src, at: index) + unsafe self.insert(copying: src, at: index) } if let res { return res } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Iterable.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Iterable.swift index 3d03f302..c72b9842 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Iterable.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Iterable.swift @@ -20,6 +20,7 @@ import InternalCollectionsUtilities @available(SwiftStdlib 5.0, *) extension RigidDeque: Iterable where Element: ~Copyable { @frozen + @safe public struct BorrowingIterator: ~Escapable, BorrowingIteratorProtocol { @usableFromInline package var _currentSegment: Span @@ -33,11 +34,11 @@ extension RigidDeque: Iterable where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(borrow _deque) package init(_deque: borrowing RigidDeque) { - let segments = _deque._handle.segments() - self._currentSegment = _overrideLifetime( + let segments = unsafe _deque._handle.segments() + self._currentSegment = unsafe _overrideLifetime( Span(_unsafeElements: segments.first), borrowing: _deque) - self._nextSegment = _overrideLifetime( + self._nextSegment = unsafe _overrideLifetime( Span( _unsafeElements: segments.second ?? UnsafeBufferPointer._empty), borrowing: _deque) @@ -54,11 +55,11 @@ extension RigidDeque: Iterable where Element: ~Copyable { precondition(start >= 0 && start <= _deque.count, "Index out of bounds") precondition(end >= 0 && end <= _deque.count, "Index out of bounds") precondition(start <= end, "The start must not be greater than the end") - let segments = _deque._handle.segments(forOffsets: start ..< end) - self._currentSegment = _overrideLifetime( + let segments = unsafe _deque._handle.segments(forOffsets: start ..< end) + self._currentSegment = unsafe _overrideLifetime( Span(_unsafeElements: segments.first), borrowing: _deque) - self._nextSegment = _overrideLifetime( + self._nextSegment = unsafe _overrideLifetime( Span( _unsafeElements: segments.second ?? UnsafeBufferPointer._empty), borrowing: _deque) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift index db98df27..f587ca50 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Prepend.swift @@ -30,7 +30,7 @@ extension RigidDeque where Element: ~Copyable { @_transparent public mutating func prepend(_ item: consuming Element) { precondition(!isFull, "RigidDeque capacity overflow") - _handle.uncheckedPrepend(item) + unsafe _handle.uncheckedPrepend(item) } /// Adds an element to the front of the deque, if possible. @@ -111,7 +111,7 @@ extension RigidDeque where Element: ~Copyable { precondition(newItemCount >= 0, "Cannot prepend a negative number of items") guard newItemCount > 0 else { return 0 ..< 0 } precondition(freeCapacity >= newItemCount, "RigidDeque capacity overflow") - return try _handle.uncheckedPrepend( + return unsafe try _handle.uncheckedPrepend( addingCount: newItemCount, initializingWith: body) } } @@ -132,11 +132,12 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) @discardableResult + @unsafe public mutating func prepend( moving items: UnsafeMutableBufferPointer ) -> Range { precondition(items.count <= freeCapacity, "RigidDeque capacity overflow") - return _handle.uncheckedPrepend(moving: items) + return unsafe _handle.uncheckedPrepend(moving: items) } #if UnstableContainersPreview @@ -155,8 +156,8 @@ extension RigidDeque where Element: ~Copyable { public mutating func prepend( moving items: inout InputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(last: count) count = 0 return unsafe self.prepend(moving: source) } @@ -178,8 +179,8 @@ extension RigidDeque where Element: ~Copyable { public mutating func prepend( moving items: inout OutputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe self.prepend(moving: source) } @@ -202,13 +203,14 @@ extension RigidDeque /*where Element: Copyable*/ { @inlinable @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func prepend( copying items: UnsafeBufferPointer ) -> Range { precondition( items.count <= freeCapacity, "RigidDeque capacity overflow") - return _handle.uncheckedPrepend(copying: items) + return unsafe _handle.uncheckedPrepend(copying: items) } /// Copies the elements of a buffer and prepend them to the front of this @@ -225,6 +227,7 @@ extension RigidDeque /*where Element: Copyable*/ { @inlinable @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func prepend( copying items: UnsafeMutableBufferPointer ) -> Range { @@ -261,13 +264,9 @@ extension RigidDeque /*where Element: Copyable*/ { // We don't know the exact count of new elements, so we cannot initialize // them in place. Append them to the end of the deque first, then rotate // them to their correct location. - // - // FIXME: If we get a Iterable.estimatedCount with an exact case, - // then we should use that when possible to copy items to their final - // location in a single pass. let oldCount = self.count try self._append(copying: items) // Not a typo! - _handle.rotate(toStartAtOffset: oldCount) + unsafe _handle.rotate(toStartAtOffset: oldCount) } @available(SwiftStdlib 6.4, *) @@ -343,7 +342,7 @@ extension RigidDeque /*where Element: Copyable*/ { guard done == nil else { return } let oldCount = self.count self.append(copying: items) // Not a typo! - _handle.rotate(toStartAtOffset: oldCount) + unsafe _handle.rotate(toStartAtOffset: oldCount) } /// Prepend the elements of a collection to the front of this deque by copying @@ -376,7 +375,7 @@ extension RigidDeque /*where Element: Copyable*/ { let c = items.count guard c > 0 else { return 0 ..< 0 } precondition(c <= freeCapacity, "RigidDeque capacity overflow") - return _handle.uncheckedPrepend(copying: items, exactCount: c) + return unsafe _handle.uncheckedPrepend(copying: items, exactCount: c) } #if compiler(>=6.4) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift index a2e582a2..e6d891cd 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Removals.swift @@ -52,7 +52,7 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient public mutating func remove(at index: Int) -> Element { _checkItemIndex(index) - return _handle.uncheckedRemove(at: index) + return unsafe _handle.uncheckedRemove(at: index) } /// Removes all elements from the deque, preserving its allocated capacity. @@ -60,7 +60,7 @@ extension RigidDeque where Element: ~Copyable { /// - Complexity: O(`count`) @_alwaysEmitIntoClient public mutating func removeAll() { - _handle.uncheckedRemoveAll() + unsafe _handle.uncheckedRemoveAll() } /// Removes and returns the first element of the deque. @@ -74,13 +74,13 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient public mutating func removeFirst() -> Element { precondition(!isEmpty, "Cannot remove first element of an empty RigidDeque") - return _handle.uncheckedRemoveFirst() + return unsafe _handle.uncheckedRemoveFirst() } @_alwaysEmitIntoClient public mutating func _customRemoveLast() -> Element? { precondition(!isEmpty, "Cannot remove last element of an empty RigidDeque") - return _handle.uncheckedRemoveLast() + return unsafe _handle.uncheckedRemoveLast() } /// Removes and returns the last element of the deque. @@ -94,7 +94,7 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient public mutating func removeLast() -> Element { precondition(!isEmpty, "Cannot remove last element of an empty RigidDeque") - return _handle.uncheckedRemoveLast() + return unsafe _handle.uncheckedRemoveLast() } /// Removes and discards the specified number of elements from the start of @@ -112,14 +112,14 @@ extension RigidDeque where Element: ~Copyable { public mutating func removeFirst(_ k: Int) { precondition(k >= 0, "Cannot remove a negative number of elements") precondition(k <= count, "Cannot remove more elements than there are in the container") - _handle.uncheckedRemoveFirst(k) + unsafe _handle.uncheckedRemoveFirst(k) } @_alwaysEmitIntoClient public mutating func _customRemoveLast(_ n: Int) -> Bool { precondition(n >= 0, "Cannot remove a negative number of elements") precondition(n <= count, "Cannot remove more elements than there are in the container") - _handle.uncheckedRemoveLast(n) + unsafe _handle.uncheckedRemoveLast(n) return true } @@ -138,7 +138,7 @@ extension RigidDeque where Element: ~Copyable { public mutating func removeLast(_ n: Int) { precondition(n >= 0, "Cannot remove a negative number of elements") precondition(n <= count, "Cannot remove more elements than there are in the container") - _handle.uncheckedRemoveLast(n) + unsafe _handle.uncheckedRemoveLast(n) } /// Removes the specified subrange of elements from the deque. @@ -154,7 +154,7 @@ extension RigidDeque where Element: ~Copyable { precondition( bounds.lowerBound >= 0 && bounds.upperBound <= count, "Subrange out of bounds") - return _handle.uncheckedRemove(offsets: bounds) + return unsafe _handle.uncheckedRemove(offsets: bounds) } } @@ -169,7 +169,7 @@ extension RigidDeque where Element: ~Copyable { @_alwaysEmitIntoClient public mutating func popFirst() -> Element? { guard !isEmpty else { return nil } - return _handle.uncheckedRemoveFirst() + return unsafe _handle.uncheckedRemoveFirst() } /// Removes and returns the last element of the deque, if there is one. @@ -183,6 +183,6 @@ extension RigidDeque where Element: ~Copyable { // FIXME: Remove this algorithm; it is already provided by // RangeReplaceableContainer, albeit with stricter availability. guard !isEmpty else { return nil } - return _handle.uncheckedRemoveLast() + return unsafe _handle.uncheckedRemoveLast() } } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift index 3ed1f7ac..a06c33d4 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Replacements.swift @@ -70,7 +70,7 @@ extension RigidDeque where Element: ~Copyable { precondition( count - subrange.count + newItemCount <= capacity, "RigidDeque capacity overflow") - return try _handle.uncheckedReplaceSubrange( + return unsafe try _handle.uncheckedReplaceSubrange( subrange, addingCount: newItemCount, initializingWith: initializer) @@ -146,7 +146,7 @@ extension RigidDeque where Element: ~Copyable { precondition( count - subrange.count + newItemCount <= capacity, "RigidDeque capacity overflow") - return try _handle.uncheckedReplaceSubrange( + return unsafe try _handle.uncheckedReplaceSubrange( subrange, consumingWith: consumer, addingCount: newItemCount, @@ -187,14 +187,15 @@ extension RigidDeque where Element: ~Copyable { /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func replaceSubrange( _ subrange: Range, moving items: UnsafeMutableBufferPointer, ) -> Range { - var remainder = items + var remainder = unsafe items let range = replaceSubrange(subrange, addingCount: remainder.count) { target in - target.withUnsafeMutableBufferPointer { buffer, count in - buffer.moveInitializeAll( + unsafe target.withUnsafeMutableBufferPointer { buffer, count in + unsafe buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) count = buffer.count } @@ -236,8 +237,8 @@ extension RigidDeque where Element: ~Copyable { _ subrange: Range, moving items: inout InputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(last: count) count = 0 return unsafe self.replaceSubrange(subrange, moving: source) } @@ -276,8 +277,8 @@ extension RigidDeque where Element: ~Copyable { _ subrange: Range, moving items: inout OutputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe self.replaceSubrange(subrange, moving: source) } @@ -314,14 +315,15 @@ extension RigidDeque /* where Element: Copyable */ { /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func replaceSubrange( _ subrange: Range, copying items: UnsafeBufferPointer ) -> Range { - var remainder = items + var remainder = unsafe items let range = replaceSubrange(subrange, addingCount: remainder.count) { target in - target.withUnsafeMutableBufferPointer { dst, dstCount in - dst.initializeAll(fromContentsOf: remainder._trim(first: dst.count)) + unsafe target.withUnsafeMutableBufferPointer { dst, dstCount in + unsafe dst.initializeAll(fromContentsOf: remainder._trim(first: dst.count)) dstCount += dst.count } } @@ -357,6 +359,7 @@ extension RigidDeque /* where Element: Copyable */ { /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func replaceSubrange( _ subrange: Range, copying items: UnsafeMutableBufferPointer @@ -411,7 +414,7 @@ extension RigidDeque /* where Element: Copyable */ { precondition( src.count == newCount, "Broken Collection: count doesn't match contents") - return self.replaceSubrange(subrange, copying: src) + return unsafe self.replaceSubrange(subrange, copying: src) } if let res { return res } diff --git a/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift b/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift index 7a470fad..92135f1e 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque+Testing.swift @@ -26,9 +26,9 @@ extension RigidDeque where Element: ~Copyable { /// /// This property isn't intended to be used outside of `DequeModule`'s own test /// target. - @usableFromInline + @_alwaysEmitIntoClient package var _startSlot: Int { - _handle.startSlot.position + unsafe _handle.startSlot.position } } @@ -39,7 +39,7 @@ extension RigidDeque { /// /// This initializer isn't intended to be used outside of `DequeModule`'s /// own test target. - @usableFromInline + @_alwaysEmitIntoClient package init( _capacity capacity: Int, startSlot: Int, @@ -48,7 +48,7 @@ extension RigidDeque { let contents = Array(contents) self.init(capacity: capacity) - _handle.startSlot = _handle.slot(_handle.startSlot, offsetBy: startSlot) + unsafe _handle._startSlot = _handle.slot(_handle.startSlot, offsetBy: startSlot) self.append(copying: contents) assert(self.capacity == capacity) assert(self._startSlot == startSlot) diff --git a/Sources/DequeModule/RigidDeque/RigidDeque.swift b/Sources/DequeModule/RigidDeque/RigidDeque.swift index aefc8320..5e6a4d45 100644 --- a/Sources/DequeModule/RigidDeque/RigidDeque.swift +++ b/Sources/DequeModule/RigidDeque/RigidDeque.swift @@ -126,18 +126,18 @@ public struct RigidDeque: ~Copyable { @_alwaysEmitIntoClient @inline(__always) package init(_handle: consuming _UnsafeHandle) { - self._handle = _handle + unsafe self._handle = _handle } @inlinable @inline(__always) deinit { - _handle.dispose() + unsafe _handle.dispose() } @inlinable @inline(__always) package mutating func _takeHandle() -> _UnsafeHandle { - exchange(&_handle, with: .allocate(capacity: 0)) + unsafe exchange(&_handle, with: .allocate(capacity: 0)) } } @@ -167,7 +167,7 @@ extension RigidDeque where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient @_transparent - public var capacity: Int { _assumeNonNegative(_handle.capacity) } + public var capacity: Int { unsafe _handle.capacity } /// The number of additional elements that can be added to this deque without /// exceeding its storage capacity. @@ -203,14 +203,14 @@ extension RigidDeque where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient @_transparent - public var isEmpty: Bool { _handle.count == 0 } + public var isEmpty: Bool { count == 0 } /// The number of elements in this deque. /// /// - Complexity: O(1) @_alwaysEmitIntoClient @_transparent - public var count: Int { _handle.count } + public var count: Int { unsafe _handle.count } /// The position of the first element in a nonempty deque. This is always zero. /// @@ -226,7 +226,7 @@ extension RigidDeque where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient @_transparent - public var endIndex: Int { _handle.count } + public var endIndex: Int { self.count } /// The range of indices that are valid for subscripting this deque. /// @@ -239,7 +239,7 @@ extension RigidDeque where Element: ~Copyable { @_transparent package func _checkItemIndex(_ index: Int) { precondition( - UInt(bitPattern: index) < UInt(bitPattern: _handle.count), + UInt(bitPattern: index) < UInt(bitPattern: count), "Index out of bounds") } @@ -247,7 +247,7 @@ extension RigidDeque where Element: ~Copyable { @_transparent package func _checkValidIndex(_ index: Int) { precondition( - UInt(bitPattern: index) <= UInt(bitPattern: _handle.count), + UInt(bitPattern: index) <= UInt(bitPattern: count), "Index out of bounds") } @@ -255,7 +255,7 @@ extension RigidDeque where Element: ~Copyable { @_transparent package func _checkValidBounds(_ subrange: Range) { precondition( - subrange.lowerBound >= 0 && subrange.upperBound <= _handle.count, + subrange.lowerBound >= 0 && subrange.upperBound <= count, "Index range out of bounds") } @@ -267,16 +267,16 @@ extension RigidDeque where Element: ~Copyable { @_unsafeSelfDependentResult borrow { _checkItemIndex(position) - let slot = _handle.slot(forOffset: position) - return _handle.ptr(at: slot).pointee + let slot = unsafe _handle.slot(forOffset: position) + return unsafe _handle.ptr(at: slot).pointee } @inline(__always) @_transparent @_unsafeSelfDependentResult mutate { _checkItemIndex(position) - let slot = _handle.slot(forOffset: position) - return &_handle.mutablePtr(at: slot).pointee + let slot = unsafe _handle.slot(forOffset: position) + return unsafe &_handle.mutablePtr(at: slot).pointee } } #else @@ -286,15 +286,15 @@ extension RigidDeque where Element: ~Copyable { @_transparent unsafeAddress { _checkItemIndex(position) - let slot = _handle.slot(forOffset: position) - return _handle.ptr(at: slot) + let slot = unsafe _handle.slot(forOffset: position) + return unsafe _handle.ptr(at: slot) } @inline(__always) @_transparent unsafeMutableAddress { _checkItemIndex(position) - let slot = _handle.slot(forOffset: position) - return _handle.mutablePtr(at: slot) + let slot = unsafe _handle.slot(forOffset: position) + return unsafe _handle.mutablePtr(at: slot) } } #endif @@ -315,7 +315,7 @@ extension RigidDeque where Element: ~Copyable { public mutating func swapAt(_ i: Int, _ j: Int) { _checkItemIndex(i) _checkItemIndex(j) - _handle.uncheckedSwapAt(i, j) + unsafe _handle.uncheckedSwapAt(i, j) } } @@ -336,7 +336,7 @@ extension RigidDeque where Element: ~Copyable { /// - Complexity: O(`count`) @inlinable public mutating func setCapacity(_ newCapacity: Int) { - _handle.reallocate(capacity: newCapacity) + unsafe _handle.reallocate(capacity: newCapacity) } /// Ensure that the deque has capacity to store the specified number of @@ -364,7 +364,7 @@ extension RigidDeque { /// - Complexity: O(`count`) @_alwaysEmitIntoClient public func clone() -> Self { - RigidDeque(_handle: _handle.allocateCopy(capacity: count)) + unsafe RigidDeque(_handle: _handle.allocateCopy(capacity: count)) } /// Copy the contents of this deque into a newly allocated rigid deque @@ -376,7 +376,7 @@ extension RigidDeque { /// - Complexity: O(`count`) @_alwaysEmitIntoClient public func clone(capacity: Int) -> Self { - RigidDeque(_handle: _handle.allocateCopy(capacity: capacity)) + unsafe RigidDeque(_handle: _handle.allocateCopy(capacity: capacity)) } } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift index d045e066..c8646c20 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Append.swift @@ -31,7 +31,7 @@ extension UniqueDeque where Element: ~Copyable { @_transparent public mutating func append(_ item: consuming Element) { _ensureFreeCapacity(1) - _storage._handle.uncheckedAppend(item) + unsafe _storage._handle.uncheckedAppend(item) } } @@ -91,7 +91,7 @@ extension UniqueDeque where Element: ~Copyable { ) throws(E) -> Range { guard newItemCount > 0 else { return count ..< count } _ensureFreeCapacity(newItemCount) - return try _storage._handle.uncheckedAppend( + return unsafe try _storage._handle.uncheckedAppend( addingCount: newItemCount, initializingWith: body) } } @@ -117,7 +117,7 @@ extension UniqueDeque where Element: ~Copyable { moving items: UnsafeMutableBufferPointer ) -> Range { _ensureFreeCapacity(items.count) - return _storage._handle.uncheckedAppend(moving: items) + return unsafe _storage._handle.uncheckedAppend(moving: items) } #if UnstableContainersPreview @@ -138,8 +138,8 @@ extension UniqueDeque where Element: ~Copyable { public mutating func append( moving items: inout InputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(last: count) count = 0 return unsafe self.append(moving: source) } @@ -163,8 +163,8 @@ extension UniqueDeque where Element: ~Copyable { public mutating func append( moving items: inout OutputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe self.append(moving: source) } @@ -294,7 +294,7 @@ extension UniqueDeque /*where Element: Copyable*/ { if done != nil { return } _ensureFreeCapacity(items.underestimatedCount) - var it = _storage._handle.uncheckedAppend(copyingPrefixOf: items) + var it = unsafe _storage._handle.uncheckedAppend(copyingPrefixOf: items) while let item = it.next() { _ensureFreeCapacity(1) _storage.append(item) diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Deprecations.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Deprecations.swift index 0b8afb37..4a726924 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Deprecations.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Deprecations.swift @@ -134,11 +134,12 @@ extension UniqueDeque where Element: ~Copyable { /// - Complexity: O(`self.count` + `items.count`) @available(*, deprecated, renamed: "replaceSubrange(_:moving:)") @_alwaysEmitIntoClient + @unsafe public mutating func replace( removing subrange: Range, moving items: UnsafeMutableBufferPointer, ) { - replaceSubrange(subrange, moving: items) + unsafe replaceSubrange(subrange, moving: items) } /// Replaces the specified range of elements by moving the contents of an @@ -209,11 +210,12 @@ extension UniqueDeque /* where Element: Copyable */ { /// - Complexity: O(`self.count` + `items.count`) @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") @inlinable + @unsafe public mutating func replace( removing subrange: Range, copying items: UnsafeBufferPointer ) { - replaceSubrange(subrange, copying: items) + unsafe replaceSubrange(subrange, copying: items) } /// Replaces the specified subrange of elements by copying the elements of @@ -245,11 +247,12 @@ extension UniqueDeque /* where Element: Copyable */ { /// - Complexity: O(`self.count` + `items.count`) @available(*, deprecated, renamed: "replaceSubrange(_:copying:)") @inlinable + @unsafe public mutating func replace( removing subrange: Range, copying items: UnsafeMutableBufferPointer ) { - replaceSubrange(subrange, copying: items) + unsafe replaceSubrange(subrange, copying: items) } /// Replaces the specified subrange of elements by copying the elements of diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift index 2b59781f..345b2b02 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Insertions.swift @@ -44,7 +44,7 @@ extension UniqueDeque where Element: ~Copyable { public mutating func insert(_ item: consuming Element, at index: Int) -> Int { _storage._checkValidIndex(index) _ensureFreeCapacity(1) - return _storage._handle.uncheckedInsert(item, at: index) + return unsafe _storage._handle.uncheckedInsert(item, at: index) } } @@ -108,7 +108,7 @@ extension UniqueDeque where Element: ~Copyable { precondition(newItemCount >= 0, "Cannot add a negative number of items") guard newItemCount > 0 else { return index ..< index } _ensureFreeCapacity(newItemCount) - return try _storage._handle.uncheckedInsert( + return unsafe try _storage._handle.uncheckedInsert( addingCount: newItemCount, at: index, initializingWith: initializer) } } @@ -137,15 +137,16 @@ extension UniqueDeque where Element: ~Copyable { /// similar invocations on the same deque. @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func insert( moving items: UnsafeMutableBufferPointer, at index: Int ) -> Range { guard !items.isEmpty else { return index ..< index } - var remainder = items + var remainder = unsafe items let range = insert(addingCount: items.count, at: index) { target in - target.withUnsafeMutableBufferPointer { buffer, count in - buffer.moveInitializeAll( + unsafe target.withUnsafeMutableBufferPointer { buffer, count in + unsafe buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) count = buffer.count } @@ -180,8 +181,8 @@ extension UniqueDeque where Element: ~Copyable { moving items: inout InputSpan, at index: Int ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(last: count) count = 0 return unsafe self.insert(moving: source, at: index) } @@ -213,8 +214,8 @@ extension UniqueDeque where Element: ~Copyable { moving items: inout OutputSpan, at index: Int ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe self.insert(moving: source, at: index) } @@ -248,16 +249,17 @@ extension UniqueDeque /* where Element: Copyable */ { /// similar invocations on the same deque. @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func insert( copying items: UnsafeBufferPointer, at index: Int ) -> Range { guard items.count > 0 else { return index ..< index } - var remainder = items + var remainder = unsafe items let range = insert(addingCount: remainder.count, at: index) { target in - target.withUnsafeMutableBufferPointer { buffer, count in - buffer.initializeAll( + unsafe target.withUnsafeMutableBufferPointer { buffer, count in + unsafe buffer.initializeAll( fromContentsOf: remainder._extracting(first: buffer.count)) - remainder = remainder._extracting(droppingFirst: buffer.count) + unsafe remainder = remainder._extracting(droppingFirst: buffer.count) count = buffer.count } } @@ -290,6 +292,7 @@ extension UniqueDeque /* where Element: Copyable */ { /// similar invocations on the same deque. @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func insert( copying items: UnsafeMutableBufferPointer, at index: Int @@ -335,7 +338,7 @@ extension UniqueDeque /* where Element: Copyable */ { newCount: Int ) -> Range { let done: Range? = items.withContiguousStorageIfAvailable { src in - self.insert(copying: src, at: index) + unsafe self.insert(copying: src, at: index) } if let done { return done } diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift index d99c88a3..0199f1c1 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Prepend.swift @@ -31,7 +31,7 @@ extension UniqueDeque where Element: ~Copyable { @_transparent public mutating func prepend(_ item: consuming Element) { _ensureFreeCapacity(1) - _storage._handle.uncheckedPrepend(item) + unsafe _storage._handle.uncheckedPrepend(item) } } @@ -95,7 +95,7 @@ extension UniqueDeque where Element: ~Copyable { ) throws(E) -> Range { guard newItemCount > 0 else { return 0 ..< 0 } _ensureFreeCapacity(newItemCount) - return try _storage._handle.uncheckedPrepend( + return unsafe try _storage._handle.uncheckedPrepend( addingCount: newItemCount, initializingWith: body) } } @@ -118,11 +118,12 @@ extension UniqueDeque where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) @discardableResult + @unsafe public mutating func prepend( moving items: UnsafeMutableBufferPointer ) -> Range { _ensureFreeCapacity(items.count) - return _storage._handle.uncheckedPrepend(moving: items) + return unsafe _storage._handle.uncheckedPrepend(moving: items) } #if UnstableContainersPreview @@ -143,8 +144,8 @@ extension UniqueDeque where Element: ~Copyable { public mutating func prepend( moving items: inout InputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(last: count) count = 0 return unsafe self.prepend(moving: source) } @@ -168,8 +169,8 @@ extension UniqueDeque where Element: ~Copyable { public mutating func prepend( moving items: inout OutputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe self.prepend(moving: source) } @@ -193,11 +194,12 @@ extension UniqueDeque /*where Element: Copyable*/ { /// invocations on the same deque. @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func prepend( copying items: UnsafeBufferPointer ) -> Range { _ensureFreeCapacity(items.count) - return _storage._handle.uncheckedPrepend(copying: items) + return unsafe _storage._handle.uncheckedPrepend(copying: items) } /// Copies the elements of a buffer and prepend them to the front of this @@ -214,6 +216,7 @@ extension UniqueDeque /*where Element: Copyable*/ { /// - Complexity: O(`items.count`) when amortized over many similar /// invocations on the same deque. @_alwaysEmitIntoClient + @unsafe public mutating func prepend( copying items: UnsafeMutableBufferPointer ) -> Range { @@ -255,7 +258,7 @@ extension UniqueDeque /*where Element: Copyable*/ { // location in a single pass. let oldCount = self.count try self._append(copying: items) // Not a typo! - _storage._handle.rotate(toStartAtOffset: oldCount) + unsafe _storage._handle.rotate(toStartAtOffset: oldCount) } @available(SwiftStdlib 6.4, *) @@ -332,7 +335,7 @@ extension UniqueDeque /*where Element: Copyable*/ { guard done == nil else { return } let oldCount = self.count self.append(copying: items) // Not a typo! - _storage._handle.rotate(toStartAtOffset: oldCount) + unsafe _storage._handle.rotate(toStartAtOffset: oldCount) } /// Prepend the elements of a collection to the front of this deque by copying @@ -366,7 +369,7 @@ extension UniqueDeque /*where Element: Copyable*/ { let c = items.count guard c > 0 else { return 0 ..< 0 } _ensureFreeCapacity(c) - return _storage._handle.uncheckedPrepend(copying: items, exactCount: c) + return unsafe _storage._handle.uncheckedPrepend(copying: items, exactCount: c) } #if compiler(>=6.4) diff --git a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift index dc39b3ad..d0461fbe 100644 --- a/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift +++ b/Sources/DequeModule/UniqueDeque/UniqueDeque+Replacements.swift @@ -82,7 +82,7 @@ extension UniqueDeque where Element: ~Copyable { _storage._checkValidBounds(subrange) precondition(newItemCount >= 0, "Cannot add a negative number of items") _ensureFreeCapacity(newItemCount - subrange.count) - return try _storage._handle.uncheckedReplaceSubrange( + return unsafe try _storage._handle.uncheckedReplaceSubrange( subrange, addingCount: newItemCount, initializingWith: initializer) @@ -151,7 +151,7 @@ extension UniqueDeque where Element: ~Copyable { _storage._checkValidBounds(subrange) precondition(newItemCount >= 0, "Cannot add a negative number of items") _ensureFreeCapacity(newItemCount - subrange.count) - return try _storage._handle.uncheckedReplaceSubrange( + return unsafe try _storage._handle.uncheckedReplaceSubrange( subrange, consumingWith: consumer, addingCount: newItemCount, @@ -193,16 +193,17 @@ extension UniqueDeque where Element: ~Copyable { /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func replaceSubrange( _ subrange: Range, moving items: UnsafeMutableBufferPointer, ) -> Range { - var remainder = items + var remainder = unsafe items let range = replaceSubrange( subrange, addingCount: remainder.count ) { target in - target.withUnsafeMutableBufferPointer { buffer, count in - buffer.moveInitializeAll( + unsafe target.withUnsafeMutableBufferPointer { buffer, count in + unsafe buffer.moveInitializeAll( fromContentsOf: remainder._trim(first: buffer.count)) count = buffer.count } @@ -245,8 +246,8 @@ extension UniqueDeque where Element: ~Copyable { _ subrange: Range, moving items: inout InputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(last: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(last: count) count = 0 return unsafe self.replaceSubrange(subrange, moving: source) } @@ -286,8 +287,8 @@ extension UniqueDeque where Element: ~Copyable { _ subrange: Range, moving items: inout OutputSpan ) -> Range { - items.withUnsafeMutableBufferPointer { buffer, count in - let source = buffer._extracting(first: count) + unsafe items.withUnsafeMutableBufferPointer { buffer, count in + let source = unsafe buffer._extracting(first: count) count = 0 return unsafe self.replaceSubrange(subrange, moving: source) } @@ -325,14 +326,15 @@ extension UniqueDeque /* where Element: Copyable */ { /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func replaceSubrange( _ subrange: Range, copying items: UnsafeBufferPointer ) -> Range { - var remainder = items + var remainder = unsafe items let range = replaceSubrange(subrange, addingCount: remainder.count) { target in - target.withUnsafeMutableBufferPointer { dst, dstCount in - dst.initializeAll(fromContentsOf: remainder._trim(first: dst.count)) + unsafe target.withUnsafeMutableBufferPointer { dst, dstCount in + unsafe dst.initializeAll(fromContentsOf: remainder._trim(first: dst.count)) dstCount += dst.count } } @@ -369,6 +371,7 @@ extension UniqueDeque /* where Element: Copyable */ { /// - Complexity: O(`self.count` + `items.count`) @_alwaysEmitIntoClient @discardableResult + @unsafe public mutating func replaceSubrange( _ subrange: Range, copying items: UnsafeMutableBufferPointer @@ -424,7 +427,7 @@ extension UniqueDeque /* where Element: Copyable */ { precondition( src.count == newCount, "Broken Collection: count doesn't match contents") - return self.replaceSubrange(subrange, copying: src) + return unsafe self.replaceSubrange(subrange, copying: src) } if let done { return done } diff --git a/Sources/DequeModule/_DequeSlot.swift b/Sources/DequeModule/_DequeSlot.swift index 4a28672c..60a52d80 100644 --- a/Sources/DequeModule/_DequeSlot.swift +++ b/Sources/DequeModule/_DequeSlot.swift @@ -13,6 +13,7 @@ @usableFromInline @frozen +@safe package struct _DequeSlot { @usableFromInline internal var position: Int @@ -75,6 +76,6 @@ extension Range where Bound == _DequeSlot { @_alwaysEmitIntoClient @_transparent internal var _offsets: Range { - Range(uncheckedBounds: (lowerBound.position, upperBound.position)) + unsafe Range(uncheckedBounds: (lowerBound.position, upperBound.position)) } } diff --git a/Sources/DequeModule/_UnsafeDequeHandle.swift b/Sources/DequeModule/_UnsafeDequeHandle.swift index ddc853c3..70729818 100644 --- a/Sources/DequeModule/_UnsafeDequeHandle.swift +++ b/Sources/DequeModule/_UnsafeDequeHandle.swift @@ -18,6 +18,7 @@ import SpanPreview @frozen @usableFromInline +@unsafe // FIXME: This doesn't own its storage; should we dissolve it into RigidDeque? package struct _UnsafeDequeHandle: ~Copyable { @usableFromInline package typealias Slot = _DequeSlot @@ -26,10 +27,12 @@ package struct _UnsafeDequeHandle: ~Copyable { package var _buffer: UnsafeMutableBufferPointer @usableFromInline - package var count: Int + @unsafe // Setter + package var _count: Int @usableFromInline - package var startSlot: Slot + @unsafe // Setter + package var _startSlot: Slot @_alwaysEmitIntoClient @_transparent @@ -38,16 +41,16 @@ package struct _UnsafeDequeHandle: ~Copyable { count: Int, startSlot: _DequeSlot ) { - self._buffer = buffer - self.count = count - self.startSlot = startSlot + unsafe self._buffer = buffer + unsafe self._count = count + unsafe self._startSlot = startSlot } @inlinable internal consuming func dispose() { - _checkInvariants() - self.mutableSegments().deinitialize() - _buffer.deallocate() + unsafe _checkInvariants() + unsafe self.mutableSegments().deinitialize() + unsafe _buffer.deallocate() } } @@ -55,7 +58,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent internal static var empty: Self { - Self(buffer: ._empty, count: 0, startSlot: .zero) + unsafe Self(buffer: ._empty, count: 0, startSlot: .zero) } @_alwaysEmitIntoClient @@ -63,7 +66,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { internal static func allocate( capacity: Int ) -> Self { - Self( + unsafe Self( buffer: capacity > 0 ? .allocate(capacity: capacity) : ._empty, count: 0, startSlot: .zero) @@ -74,9 +77,9 @@ extension _UnsafeDequeHandle where Element: ~Copyable { #if COLLECTIONS_INTERNAL_CHECKS @usableFromInline @inline(never) @_effects(releasenone) internal func _checkInvariants() { - precondition(capacity >= 0) - precondition(count >= 0 && count <= capacity) - precondition(startSlot.position >= 0 && startSlot.position <= capacity) + precondition(unsafe capacity >= 0) + precondition(unsafe count >= 0 && count <= capacity) + precondition(unsafe startSlot.position >= 0 && startSlot.position <= capacity) } #else @inlinable @inline(__always) @@ -86,6 +89,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { extension _UnsafeDequeHandle where Element: ~Copyable { @usableFromInline + @safe internal var description: String { "(capacity: \(capacity), count: \(count), start: \(startSlot))" } @@ -95,21 +99,37 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent internal var _baseAddress: UnsafeMutablePointer { - _buffer.baseAddress.unsafelyUnwrapped + unsafe _buffer.baseAddress.unsafelyUnwrapped } @_alwaysEmitIntoClient @_transparent + @safe + internal var count: Int { + unsafe _assumeNonNegative(_count) + } + + @_alwaysEmitIntoClient + @_transparent + @safe internal var capacity: Int { - _buffer.count + unsafe _assumeNonNegative(_buffer.count) + } + + @_alwaysEmitIntoClient + @_transparent + @safe + internal var startSlot: Slot { + unsafe _startSlot } } extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent + @safe internal func isIdentical(to other: borrowing Self) -> Bool { - self._buffer._isIdentical(to: other._buffer) + unsafe self._buffer._isIdentical(to: other._buffer) && self.count == other.count && self.startSlot == other.startSlot } @@ -130,22 +150,22 @@ extension _UnsafeDequeHandle where Element: ~Copyable { (startSlot.position < capacity || (capacity == 0 && startSlot.position == 0))) precondition(count <= capacity) - var h = Self.allocate(capacity: capacity) - h.count = count - h.startSlot = startSlot + var h = unsafe Self.allocate(capacity: capacity) + unsafe h._count = count + unsafe h._startSlot = startSlot if h.count > 0 { - let segments = h.mutableSegments() - let c = segments.first.count + let segments = unsafe h.mutableSegments() + let c = unsafe segments.first.count for i in 0 ..< c { - segments.first.initializeElement(at: i, to: generator(i)) + unsafe segments.first.initializeElement(at: i, to: generator(i)) } - if let second = segments.second { + if let second = unsafe segments.second { for i in c ..< h.count { - second.initializeElement(at: i - c, to: generator(i)) + unsafe second.initializeElement(at: i - c, to: generator(i)) } } } - return h + return unsafe h } } @@ -157,12 +177,14 @@ extension _UnsafeDequeHandle where Element: ~Copyable { /// entirely.) @_alwaysEmitIntoClient @_transparent + @safe internal var limSlot: Slot { Slot(at: capacity) } @_alwaysEmitIntoClient @_transparent + @safe internal func slot(after slot: Slot) -> Slot { assert(slot.position < capacity) let position = slot.position + 1 @@ -174,6 +196,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent + @safe internal func slot(before slot: Slot) -> Slot { assert(slot.position < capacity) if slot.position == 0 { return Slot(at: capacity - 1) } @@ -182,6 +205,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent + @safe internal func slot(_ slot: Slot, offsetBy delta: Int) -> Slot { assert(slot.position <= capacity) let position = slot.position + delta @@ -195,6 +219,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent + @safe internal var endSlot: Slot { slot(startSlot, offsetBy: count) } @@ -203,6 +228,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { /// or may not address an existing element. @_alwaysEmitIntoClient @_transparent + @safe internal func slot(forOffset offset: Int) -> Slot { assert(offset >= 0) assert(offset <= capacity) // Not `count`! @@ -218,6 +244,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent + @safe internal func distance(from start: Slot, to end: Slot) -> Int { assert(start.position >= 0 && start.position <= capacity) assert(end.position >= 0 && end.position <= capacity) @@ -238,7 +265,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_transparent internal func ptr(at slot: Slot) -> UnsafePointer { assert(slot.position >= 0 && slot.position <= capacity) - return UnsafePointer(_baseAddress + slot.position) + return unsafe UnsafePointer(_baseAddress + slot.position) } @_alwaysEmitIntoClient @@ -247,25 +274,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { at slot: Slot ) -> UnsafeMutablePointer { assert(slot.position >= 0 && slot.position <= capacity) - return _baseAddress + slot.position - } -} - -extension _UnsafeDequeHandle where Element: ~Copyable { - @inlinable - internal subscript(offset offset: Int) -> Element { - @inline(__always) - _read { - precondition(offset >= 0 && offset < count, "Index out of bounds") - let slot = slot(forOffset: offset) - yield ptr(at: slot).pointee - } - @inline(__always) - _modify { - precondition(offset >= 0 && offset < count, "Index out of bounds") - let slot = slot(forOffset: offset) - yield &mutablePtr(at: slot).pointee - } + return unsafe _baseAddress + slot.position } } @@ -276,7 +285,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_transparent internal var mutableBuffer: UnsafeMutableBufferPointer { mutating get { - _buffer + unsafe _buffer } } @@ -284,7 +293,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_transparent internal func buffer(for range: Range) -> UnsafeBufferPointer { assert(range.upperBound.position <= capacity) - return .init(_buffer._extracting(unchecked: range._offsets)) + return unsafe .init(_buffer._extracting(unchecked: range._offsets)) } @_alwaysEmitIntoClient @@ -293,7 +302,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { for range: Range ) -> UnsafeMutableBufferPointer { assert(range.upperBound.position <= capacity) - return _buffer._extracting(unchecked: range._offsets) + return unsafe _buffer._extracting(unchecked: range._offsets) } } @@ -306,7 +315,7 @@ extension _UnsafeDequeHandle { ) -> Slot { assert(start.position + source.count <= capacity) guard source.count > 0 else { return start } - mutablePtr(at: start).initialize(from: source.baseAddress!, count: source.count) + unsafe mutablePtr(at: start).initialize(from: source.baseAddress!, count: source.count) return Slot(at: start.position + source.count) } } @@ -320,7 +329,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { ) -> Slot { assert(start.position + source.count <= capacity) guard source.count > 0 else { return start } - mutablePtr(at: start) + unsafe mutablePtr(at: start) .moveInitialize(from: source.baseAddress!, count: source.count) return Slot(at: start.position + source.count) } @@ -334,17 +343,17 @@ extension _UnsafeDequeHandle where Element: ~Copyable { after offset: Int ) -> UnsafeBufferPointer { assert(offset >= 0 && offset <= count) - guard _buffer.baseAddress != nil else { + guard unsafe _buffer.baseAddress != nil else { return .init(._empty) } let position = startSlot.position &+ offset if position < capacity { - return UnsafeBufferPointer( + return unsafe UnsafeBufferPointer( start: ptr(at: Slot(at: position)), count: Swift.min(count &- offset, capacity &- position)) } // We're after the wrap - return UnsafeBufferPointer( + return unsafe UnsafeBufferPointer( start: ptr(at: Slot(at: position &- capacity)), count: startSlot.position &+ count &- position) } @@ -357,13 +366,13 @@ extension _UnsafeDequeHandle where Element: ~Copyable { ) -> UnsafeBufferPointer { assert(limit >= 0 && limit <= count) assert(maxCount > 0) - var segment = self.nextSegment(after: offset) + var segment = unsafe self.nextSegment(after: offset) ._extracting(first: maxCount) if limit >= offset, segment.count > limit &- offset { - segment = segment._extracting(first: limit &- offset) + unsafe segment = segment._extracting(first: limit &- offset) } offset &+= segment.count - return segment + return unsafe segment } @_alwaysEmitIntoClient @@ -371,17 +380,17 @@ extension _UnsafeDequeHandle where Element: ~Copyable { before offset: Int ) -> UnsafeBufferPointer { assert(offset >= 0 && offset <= count) - guard _buffer.baseAddress != nil else { + guard unsafe _buffer.baseAddress != nil else { return .init(._empty) } let slot = startSlot.position &+ offset if slot <= capacity { - return UnsafeBufferPointer( + return unsafe UnsafeBufferPointer( start: ptr(at: startSlot), count: offset) } // We're after the wrap - return UnsafeBufferPointer( + return unsafe UnsafeBufferPointer( start: ptr(at: Slot(at: 0)), count: slot - capacity) } @@ -414,15 +423,16 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient internal func segments() -> _UnsafeDequeSegments { - guard _buffer.baseAddress != nil else { - return .init(._empty) + guard unsafe _buffer.baseAddress != nil else { + return unsafe .init(._empty) } let wrap = capacity &- startSlot.position if count <= wrap { - return .init(start: ptr(at: startSlot), count: count) + return unsafe .init(start: ptr(at: startSlot), count: count) } - return .init(first: ptr(at: startSlot), count: wrap, - second: ptr(at: .zero), count: count &- wrap) + return unsafe .init( + first: ptr(at: startSlot), count: wrap, + second: ptr(at: .zero), count: count &- wrap) } @_alwaysEmitIntoClient @@ -432,15 +442,15 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // Note: no asserts for bounds checks, as this is used to implement // appends/prepends assert(offsets.count <= capacity) - guard _buffer.baseAddress != nil else { - return .init(._empty) + guard unsafe _buffer.baseAddress != nil else { + return unsafe .init(._empty) } let start = slot(forOffset: offsets.lowerBound) let wrap = capacity &- start.position if offsets.count <= wrap { - return .init(start: ptr(at: start), count: offsets.count) + return unsafe .init(start: ptr(at: start), count: offsets.count) } - return .init( + return unsafe .init( first: ptr(at: start), count: capacity &- start.position, second: ptr(at: .zero), count: offsets.count &- wrap) } @@ -448,7 +458,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent internal mutating func mutableSegments() -> _UnsafeMutableDequeSegments { - .init(mutating: segments()) + unsafe .init(mutating: segments()) } @_alwaysEmitIntoClient @@ -456,7 +466,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { internal mutating func mutableSegments( forOffsets range: Range ) -> _UnsafeMutableDequeSegments { - .init(mutating: segments(forOffsets: range)) + unsafe .init(mutating: segments(forOffsets: range)) } @_alwaysEmitIntoClient @@ -467,11 +477,11 @@ extension _UnsafeDequeHandle where Element: ~Copyable { assert(start.position <= capacity) assert(end.position <= capacity) if start < end { - return .init( + return unsafe .init( start: mutablePtr(at: start), count: end.position - start.position) } - return .init( + return unsafe .init( first: mutablePtr(at: start), count: capacity - start.position, second: mutablePtr(at: .zero), count: end.position) } @@ -480,14 +490,19 @@ extension _UnsafeDequeHandle where Element: ~Copyable { extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient internal mutating func availableSegments() -> _UnsafeMutableDequeSegments { - guard _buffer.baseAddress != nil else { - return .init(._empty) + guard unsafe _buffer.baseAddress != nil else { + return unsafe .init(._empty) } let endSlot = self.endSlot - guard count < capacity else { return .init(start: mutablePtr(at: endSlot), count: 0) } - if endSlot < startSlot { return .init(mutableBuffer(for: endSlot ..< startSlot)) } - return .init(mutableBuffer(for: endSlot ..< limSlot), - mutableBuffer(for: .zero ..< startSlot)) + guard count < capacity else { + return unsafe .init(start: mutablePtr(at: endSlot), count: 0) + } + if endSlot < startSlot { + return unsafe .init(mutableBuffer(for: endSlot ..< startSlot)) + } + return unsafe .init( + mutableBuffer(for: endSlot ..< limSlot), + mutableBuffer(for: .zero ..< startSlot)) } } @@ -498,15 +513,15 @@ extension _UnsafeDequeHandle { /// capacity or layout. @_alwaysEmitIntoClient internal borrowing func allocateCopy() -> Self { - var result: _UnsafeDequeHandle = .allocate(capacity: self.capacity) - result.count = self.count - result.startSlot = self.startSlot - let src = self.segments() - result.initialize(at: self.startSlot, from: src.first) - if let second = src.second { - result.initialize(at: .zero, from: second) + var result: _UnsafeDequeHandle = unsafe .allocate(capacity: self.capacity) + unsafe result._count = self.count + unsafe result._startSlot = self.startSlot + let src = unsafe self.segments() + unsafe result.initialize(at: self.startSlot, from: src.first) + if let second = unsafe src.second { + unsafe result.initialize(at: .zero, from: second) } - return result + return unsafe result } /// Copy elements in `handle` into a newly allocated handle with the specified @@ -514,14 +529,14 @@ extension _UnsafeDequeHandle { @_alwaysEmitIntoClient internal func allocateCopy(capacity: Int) -> Self { precondition(capacity >= self.count) - var result: _UnsafeDequeHandle = .allocate(capacity: capacity) - result.count = self.count - let src = self.segments() - let next = result.initialize(at: .zero, from: src.first) - if let second = src.second { - result.initialize(at: next, from: second) + var result: _UnsafeDequeHandle = unsafe .allocate(capacity: capacity) + unsafe result._count = self.count + let src = unsafe self.segments() + let next = unsafe result.initialize(at: .zero, from: src.first) + if let second = unsafe src.second { + unsafe result.initialize(at: next, from: second) } - return result + return unsafe result } } @@ -531,15 +546,15 @@ extension _UnsafeDequeHandle where Element: ~Copyable { let newCapacity = Swift.max(newCapacity, count) guard newCapacity != capacity else { return } - var new = _UnsafeDequeHandle.allocate(capacity: newCapacity) - let source = self.mutableSegments() - let next = new.moveInitialize(at: .zero, from: source.first) - if let second = source.second { - new.moveInitialize(at: next, from: second) + var new = unsafe _UnsafeDequeHandle.allocate(capacity: newCapacity) + let source = unsafe self.mutableSegments() + let next = unsafe new.moveInitialize(at: .zero, from: source.first) + if let second = unsafe source.second { + unsafe new.moveInitialize(at: next, from: second) } - _buffer.deallocate() - _buffer = new._buffer - startSlot = .zero + unsafe _buffer.deallocate() + unsafe _buffer = new._buffer + unsafe _startSlot = .zero } } @@ -549,39 +564,39 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient internal func slotRange(following offset: inout Int) -> Range { precondition(offset >= 0 && offset <= count, "Index out of bounds") - guard _buffer.baseAddress != nil else { - return Range(uncheckedBounds: (Slot.zero, Slot.zero)) + guard unsafe _buffer.baseAddress != nil else { + return unsafe Range(uncheckedBounds: (Slot.zero, Slot.zero)) } let wrapOffset = Swift.min(capacity - startSlot.position, count) if offset < wrapOffset { defer { offset += wrapOffset - offset } - return Range( + return unsafe Range( uncheckedBounds: (startSlot.advanced(by: offset), startSlot.advanced(by: wrapOffset))) } let lowerSlot = Slot.zero.advanced(by: offset - wrapOffset) let upperSlot = lowerSlot.advanced(by: count - wrapOffset) defer { offset += count - offset } - return Range(uncheckedBounds: (lower: lowerSlot, upper: upperSlot)) + return unsafe Range(uncheckedBounds: (lower: lowerSlot, upper: upperSlot)) } @_alwaysEmitIntoClient internal func slotRange(preceding offset: inout Int) -> Range { precondition(offset >= 0 && offset <= count, "Index out of bounds") - guard _buffer.baseAddress != nil else { - return Range(uncheckedBounds: (Slot.zero, Slot.zero)) + guard unsafe _buffer.baseAddress != nil else { + return unsafe Range(uncheckedBounds: (Slot.zero, Slot.zero)) } let wrapOffset = Swift.min(capacity - startSlot.position, count) if offset <= wrapOffset { defer { offset = 0 } - return Range( + return unsafe Range( uncheckedBounds: (startSlot, startSlot.advanced(by: offset))) } let lowerSlot = Slot.zero let upperSlot = lowerSlot.advanced(by: offset - wrapOffset) defer { offset = wrapOffset } - return Range(uncheckedBounds: (lower: lowerSlot, upper: upperSlot)) + return unsafe Range(uncheckedBounds: (lower: lowerSlot, upper: upperSlot)) } } @@ -593,7 +608,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { internal mutating func uncheckedSwapAt(_ i: Int, _ j: Int) { let slot1 = self.slot(forOffset: i) let slot2 = self.slot(forOffset: j) - self.mutableBuffer.swapAt(slot1.position, slot2.position) + unsafe self.mutableBuffer.swapAt(slot1.position, slot2.position) } } @@ -613,8 +628,8 @@ extension _UnsafeDequeHandle { assert(range.upperBound <= count) assert(newElements.count == range.count) guard !range.isEmpty else { return } - let target = mutableSegments(forOffsets: range) - target.reassign(copying: newElements) + let target = unsafe mutableSegments(forOffsets: range) + unsafe target.reassign(copying: newElements) } } @@ -626,12 +641,12 @@ extension _UnsafeDequeHandle where Element: ~Copyable { internal mutating func unsafeConsumeAll( with body: (UnsafeMutableBufferPointer) -> Void ) { - let segments = mutableSegments() - body(segments.first) - if let second = segments.second { - body(second) + let segments = unsafe mutableSegments() + unsafe body(segments.first) + if let second = unsafe segments.second { + unsafe body(second) } - self.count = 0 + unsafe self._count = 0 } @_alwaysEmitIntoClient @@ -641,13 +656,13 @@ extension _UnsafeDequeHandle where Element: ~Copyable { with body: (UnsafeMutableBufferPointer) -> Void ) { assert(offset >= 0 && offset <= count) - let segments = mutableSegments(forOffsets: Range(uncheckedBounds: (0, offset))) - body(segments.first) - if let second = segments.second { - body(second) + let segments = unsafe mutableSegments(forOffsets: Range(uncheckedBounds: (0, offset))) + unsafe body(segments.first) + if let second = unsafe segments.second { + unsafe body(second) } - self.startSlot = self.slot(forOffset: offset) - self.count &-= offset + unsafe self._startSlot = self.slot(forOffset: offset) + unsafe self._count &-= offset } } @@ -663,8 +678,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_transparent internal mutating func uncheckedAppend(_ element: consuming Element) { assert(count < capacity) - mutablePtr(at: endSlot).initialize(to: element) - count &+= 1 + unsafe mutablePtr(at: endSlot).initialize(to: element) + unsafe _count &+= 1 } /// Prepend `element` to the front of this buffer. The buffer must have enough @@ -677,9 +692,9 @@ extension _UnsafeDequeHandle where Element: ~Copyable { internal mutating func uncheckedPrepend(_ element: consuming Element) { assert(count < capacity) let slot = self.slot(before: startSlot) - mutablePtr(at: slot).initialize(to: element) - startSlot = slot - count &+= 1 + unsafe mutablePtr(at: slot).initialize(to: element) + unsafe _startSlot = slot + unsafe _count &+= 1 } } @@ -691,9 +706,9 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { initializedCount: inout Int, initializingWith body: (inout OutputSpan) throws(E) -> R ) throws(E) -> R { - var span = OutputSpan(buffer: self, initializedCount: 0) + var span = unsafe OutputSpan(buffer: self, initializedCount: 0) defer { - initializedCount &+= span.finalize(for: self) + unsafe initializedCount &+= span.finalize(for: self) span = OutputSpan() } return try body(&span) @@ -708,8 +723,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { assert(self.count + count <= capacity) guard count > 0 else { return nil } let origCount = self.count - self.count &+= count - return self.mutableSegments(forOffsets: origCount ..< origCount + count) + unsafe self._count &+= count + return unsafe self.mutableSegments(forOffsets: origCount ..< origCount + count) } @_alwaysEmitIntoClient @@ -719,9 +734,9 @@ extension _UnsafeDequeHandle where Element: ~Copyable { assert(self.count + count <= capacity) guard count > 0 else { return nil } let oldStart = self.startSlot - self.startSlot = self.slot(startSlot, offsetBy: -count) - self.count &+= count - return self.mutableSegments(between: self.startSlot, and: oldStart) + unsafe self._startSlot = self.slot(startSlot, offsetBy: -count) + unsafe self._count &+= count + return unsafe self.mutableSegments(between: self.startSlot, and: oldStart) } } @@ -756,15 +771,15 @@ extension _UnsafeDequeHandle where Element: ~Copyable { initializingWith body: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Range { let origCount = count - let gap = self.mutableSegments(forOffsets: count ..< count + newItemCount) - let c = self.count &+ gap.first.count - try gap.first._initialize( - initializedCount: &self.count, initializingWith: body) - if self.count == c, let second = gap.second { - try second._initialize( - initializedCount: &self.count, initializingWith: body) + let gap = unsafe self.mutableSegments(forOffsets: count ..< count + newItemCount) + let c = unsafe self.count &+ gap.first.count + unsafe try gap.first._initialize( + initializedCount: &self._count, initializingWith: body) + if self.count == c, let second = unsafe gap.second { + unsafe try second._initialize( + initializedCount: &self._count, initializingWith: body) } - return Range(uncheckedBounds: (origCount, count)) + return unsafe Range(uncheckedBounds: (origCount, count)) } /// Prepend a given number of items to the end of this deque by populating @@ -817,19 +832,21 @@ extension _UnsafeDequeHandle where Element: ~Copyable { addingCount newItemCount: Int, initializingWith body: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Range { - guard let gap = self._prepend(count: newItemCount) else { return 0 ..< 0 } + guard let gap = unsafe self._prepend(count: newItemCount) else { + return 0 ..< 0 + } var c = 0 defer { if c < newItemCount { - closeGap(offsets: c ..< newItemCount) + unsafe closeGap(offsets: c ..< newItemCount) } } - try gap.first._initialize(initializedCount: &c, initializingWith: body) - if c == gap.first.count, let second = gap.second { - try second._initialize(initializedCount: &c, initializingWith: body) + unsafe try gap.first._initialize(initializedCount: &c, initializingWith: body) + if unsafe c == gap.first.count, let second = unsafe gap.second { + unsafe try second._initialize(initializedCount: &c, initializingWith: body) } - return Range(uncheckedBounds: (0, c)) + return unsafe Range(uncheckedBounds: (0, c)) } } @@ -850,17 +867,19 @@ extension _UnsafeDequeHandle where Element: ~Copyable { internal mutating func uncheckedAppend( moving items: UnsafeMutableBufferPointer ) -> Range { - guard let gap = _append(count: items.count) else { return count ..< count } + guard let gap = unsafe _append(count: items.count) else { + return count ..< count + } - gap.first.moveInitializeAll( + unsafe gap.first.moveInitializeAll( fromContentsOf: items._extracting(first: gap.first.count)) - if let second = gap.second { - assert(gap.first.count + second.count == items.count) - second.moveInitializeAll( + if let second = unsafe gap.second { + assert(unsafe gap.first.count + second.count == items.count) + unsafe second.moveInitializeAll( fromContentsOf: items._extracting(last: second.count)) } - return Range(uncheckedBounds: (count &- items.count, count)) + return unsafe Range(uncheckedBounds: (count &- items.count, count)) } /// Prepends the elements of a buffer to the front of this deque, leaving the @@ -878,17 +897,17 @@ extension _UnsafeDequeHandle where Element: ~Copyable { internal mutating func uncheckedPrepend( moving items: UnsafeMutableBufferPointer ) -> Range { - guard let gap = _prepend(count: items.count) else { return 0 ..< 0 } + guard let gap = unsafe _prepend(count: items.count) else { return 0 ..< 0 } - gap.first.moveInitializeAll( + unsafe gap.first.moveInitializeAll( fromContentsOf: items._extracting(first: gap.first.count)) - if let second = gap.second { - assert(gap.first.count + second.count == items.count) - second.moveInitializeAll( + if let second = unsafe gap.second { + assert(unsafe gap.first.count + second.count == items.count) + unsafe second.moveInitializeAll( fromContentsOf: items._extracting(last: second.count)) } - return Range(uncheckedBounds: (0, items.count)) + return unsafe Range(uncheckedBounds: (0, items.count)) } } @@ -903,9 +922,11 @@ extension _UnsafeDequeHandle { internal mutating func uncheckedAppend( copying source: UnsafeBufferPointer ) -> Range { - guard let gap = _append(count: source.count) else { return count ..< count } - gap.initialize(copying: source) - return Range(uncheckedBounds: (count &- source.count, count)) + guard let gap = unsafe _append(count: source.count) else { + return count ..< count + } + unsafe gap.initialize(copying: source) + return unsafe Range(uncheckedBounds: (count &- source.count, count)) } /// Prepend the contents of `source` to this buffer. The buffer must have @@ -918,9 +939,9 @@ extension _UnsafeDequeHandle { internal mutating func uncheckedPrepend( copying source: UnsafeBufferPointer ) -> Range { - guard let gap = _prepend(count: source.count) else { return 0 ..< 0 } - gap.initialize(copying: source) - return Range(uncheckedBounds: (0, source.count)) + guard let gap = unsafe _prepend(count: source.count) else { return 0 ..< 0 } + unsafe gap.initialize(copying: source) + return unsafe Range(uncheckedBounds: (0, source.count)) } } @@ -933,8 +954,8 @@ extension _UnsafeDequeHandle { ) -> S.Iterator { // Note: You're supposed to handle contiguous sequences before calling // this function. You do this by invoking `withContiguousStorageIfAvailable`. - let (it, c) = self.availableSegments().initialize(fromSequencePrefix: items) - self.count += c + let (it, c) = unsafe self.availableSegments().initialize(fromSequencePrefix: items) + unsafe self._count += c return it } @@ -946,9 +967,11 @@ extension _UnsafeDequeHandle { ) -> Range { // Note: You're supposed to handle contiguous sequences before calling // this function. You do this by invoking `withContiguousStorageIfAvailable`. - guard let gap = self._prepend(count: exactCount) else { return 0 ..< 0 } - gap.initialize(copying: items) - return Range(uncheckedBounds: (0, exactCount)) + guard let gap = unsafe self._prepend(count: exactCount) else { + return 0 ..< 0 + } + unsafe gap.initialize(copying: items) + return unsafe Range(uncheckedBounds: (0, exactCount)) } } @@ -967,7 +990,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { assert(source.position + count <= self.capacity) assert(target.position + count <= self.capacity) guard count > 0 else { return (source, target) } - mutablePtr(at: target) + unsafe mutablePtr(at: target) .moveInitialize(from: mutablePtr(at: source), count: count) return (slot(source, offsetBy: count), slot(target, offsetBy: count)) } @@ -980,7 +1003,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent - func isLeftLeaning(_ subrange: Range) -> Bool { + @safe + internal func isLeftLeaning(_ subrange: Range) -> Bool { subrange.lowerBound < count - subrange.upperBound } @@ -1024,7 +1048,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // // 0) ....ABCDE̲F̲G̲H..... EFG̲H̲.̲........ABCD .̲.......ABCDEFGH̲.̲ // 1) ....ABCD.̲.̲.̲EFGH.. EF.̲.̲.̲GH......ABCD .̲H......ABCDEFG.̲.̲ - move(from: gapStart, to: gapEnd, count: tailCount) + unsafe move(from: gapStart, to: gapEnd, count: tailCount) } else if targetIsContiguous { // The gap itself will be wrapped. @@ -1034,8 +1058,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 1) .̲..EFGH......ABC̲D̲ // 2) .̲CDEFGH......AB.̲.̲ assert(startSlot > originalEnd.orIfZero(capacity)) - move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position) - move(from: gapStart, to: gapEnd, count: capacity - gapStart.position) + unsafe move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position) + unsafe move(from: gapStart, to: gapEnd, count: capacity - gapStart.position) } else if sourceIsContiguous { // Opening the gap pushes subsequent elements across the wrap. @@ -1044,8 +1068,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 0) ........ABC̲D̲E̲FGH. // 1) GH......ABC̲D̲E̲F... // 2) GH......AB.̲.̲.̲CDEF - move(from: limSlot.advanced(by: -gapSize), to: .zero, count: newEnd.position) - move(from: gapStart, to: gapEnd, count: tailCount - newEnd.position) + unsafe move(from: limSlot.advanced(by: -gapSize), to: .zero, count: newEnd.position) + unsafe move(from: gapStart, to: gapEnd, count: tailCount - newEnd.position) } else { // The rest of the items are wrapped, and will remain so. @@ -1055,12 +1079,12 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 1) ...GH......AB̲C̲D̲EF // 2) DEFGH......AB̲C̲.̲.. // 3) DEFGH......A.̲.̲.̲BC - move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position) - move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize) - move(from: gapStart, to: gapEnd, count: tailCount - gapSize - originalEnd.position) + unsafe move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: originalEnd.position) + unsafe move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize) + unsafe move(from: gapStart, to: gapEnd, count: tailCount - gapSize - originalEnd.position) } - count += gapSize - return mutableSegments(between: gapStart, and: gapEnd.orIfZero(capacity)) + unsafe _count += gapSize + return unsafe mutableSegments(between: gapStart, and: gapEnd.orIfZero(capacity)) } // Open the gap by sliding elements to the left. @@ -1080,7 +1104,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // // 0) ....A̲B̲C̲DEFGH... GH.........̲A̲B̲CDEF .̲A̲B̲CDEFGH.......̲.̲ // 1) .ABC.̲.̲.̲DEFGH... GH......AB.̲.̲.̲CDEF .̲.̲.̲CDEFGH....AB.̲.̲ - move(from: originalStart, to: newStart, count: headCount) + unsafe move(from: originalStart, to: newStart, count: headCount) } else if targetIsContiguous { // The gap itself will be wrapped. @@ -1090,8 +1114,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 1) C̲D̲EFGH.....AB...̲.̲ // 2) .̲.̲EFGH.....ABCD.̲.̲ assert(originalStart >= newStart) - move(from: originalStart, to: newStart, count: capacity - originalStart.position) - move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapEnd.position) + unsafe move(from: originalStart, to: newStart, count: capacity - originalStart.position) + unsafe move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapEnd.position) } else if sourceIsContiguous { // Opening the gap pushes preceding elements across the wrap. @@ -1100,8 +1124,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 0) .AB̲C̲D̲EFGH......... // 1) ...̲C̲D̲EFGH.......AB // 2) CD.̲.̲.̲EFGH.......AB - move(from: originalStart, to: newStart, count: capacity - newStart.position) - move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position) + unsafe move(from: originalStart, to: newStart, count: capacity - newStart.position) + unsafe move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position) } else { // The preceding of the items are wrapped, and will remain so. @@ -1110,13 +1134,13 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 1) CD̲E̲F̲GHIJKL......AB... // 2) ..̲.̲F̲GHIJKL......ABCDE // 3) F.̲.̲.̲GHIJKL......ABCDE - move(from: originalStart, to: newStart, count: capacity - originalStart.position) - move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapSize) - move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position) + unsafe move(from: originalStart, to: newStart, count: capacity - originalStart.position) + unsafe move(from: .zero, to: limSlot.advanced(by: -gapSize), count: gapSize) + unsafe move(from: Slot.zero.advanced(by: gapSize), to: .zero, count: gapStart.position) } - startSlot = newStart - count += gapSize - return mutableSegments(between: gapStart, and: gapEnd.orIfZero(capacity)) + unsafe _startSlot = newStart + unsafe _count += gapSize + return unsafe mutableSegments(between: gapStart, and: gapEnd.orIfZero(capacity)) } /// Close the gap of already uninitialized elements in `bounds`, sliding @@ -1152,7 +1176,7 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 0) ....ABCD.̲.̲.̲EFGH.. EF.̲.̲.̲GH........ABCD .̲.̲.̲E..........ABCD.̲.̲ .̲.̲.̲EF........ABCD .̲.̲.̲DE.......ABC // 1) ....ABCDE̲F̲G̲H..... EFG̲H̲.̲..........ABCD .̲.̲.̲...........ABCDE̲.̲ E̲F̲.̲..........ABCD D̲E̲.̲.........ABC - move(from: gapEnd, to: gapStart, count: tailCount) + unsafe move(from: gapEnd, to: gapStart, count: tailCount) } else if sourceIsContiguous { // The gap lies across the wrap from the subsequent elements. @@ -1161,8 +1185,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 2) G̲H̲.̲...........ABCDE̲F̲ GH.........ABCDE̲F̲G̲ let c = capacity - gapStart.position assert(tailCount > c) - let next = move(from: gapEnd, to: gapStart, count: c) - move(from: next.source, to: .zero, count: tailCount - c) + let next = unsafe move(from: gapEnd, to: gapStart, count: c) + unsafe move(from: next.source, to: .zero, count: tailCount - c) } else if targetIsContiguous { // We need to move elements across a wrap, but the wrap will // disappear when we're done. @@ -1170,8 +1194,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 0) HI....ABCDE.̲.̲.̲FG // 1) HI....ABCDEF̲G̲.̲.. // 2) ......ABCDEF̲G̲H̲I. - let next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position) - move(from: .zero, to: next.target, count: originalEnd.position) + let next = unsafe move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position) + unsafe move(from: .zero, to: next.target, count: originalEnd.position) } else { // We need to move elements across a wrap that won't go away. @@ -1179,11 +1203,11 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 1) HIJKL....ABCDEF̲G̲.̲.. // 2) ...KL....ABCDEF̲G̲H̲IJ // 3) KL.......ABCDEF̲G̲H̲IJ - var next = move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position) - next = move(from: .zero, to: next.target, count: gapSize) - move(from: next.source, to: .zero, count: newEnd.position) + var next = unsafe move(from: gapEnd, to: gapStart, count: capacity - gapEnd.position) + next = unsafe move(from: .zero, to: next.target, count: gapSize) + unsafe move(from: next.source, to: .zero, count: newEnd.position) } - count -= gapSize + unsafe _count -= gapSize } else { // Close the gap by sliding elements to the right. let originalStart = startSlot @@ -1199,15 +1223,15 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 0) ....ABCD.̲.̲.̲EFGH..... EFGH........AB.̲.̲.̲CD .̲.̲.̲CDEFGH.......AB.̲.̲ DEFGH.......ABC.̲.̲ // 1) .......AB̲C̲D̲EFGH..... EFGH...........̲A̲B̲CD .̲A̲B̲CDEFGH..........̲.̲ DEFGH.........AB̲C̲ ABCDEFGH........̲.̲.̲ - move(from: originalStart, to: newStart, count: headCount) + unsafe move(from: originalStart, to: newStart, count: headCount) } else if sourceIsContiguous { // The gap lies across the wrap from the preceding elements. // 0) .̲.̲DEFGH.......ABC.̲.̲ .̲.̲.̲EFGH.......ABCD // 1) B̲C̲DEFGH.......A...̲.̲ B̲C̲D̲DEFGH......A... // 2) B̲C̲DEFGH...........̲A̲ B̲C̲D̲DEFGH.........A - move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapEnd.position) - move(from: startSlot, to: newStart, count: headCount - gapEnd.position) + unsafe move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapEnd.position) + unsafe move(from: startSlot, to: newStart, count: headCount - gapEnd.position) } else if targetIsContiguous { // We need to move elements across a wrap, but the wrap will // disappear when we're done. @@ -1215,20 +1239,20 @@ extension _UnsafeDequeHandle where Element: ~Copyable { // 0) CD.̲.̲.̲EFGHI.....AB // 1) ...̲C̲D̲EFGHI.....AB // 1) .AB̲C̲D̲EFGHI....... - move(from: .zero, to: gapEnd.advanced(by: -gapStart.position), count: gapStart.position) - move(from: startSlot, to: newStart, count: headCount - gapStart.position) + unsafe move(from: .zero, to: gapEnd.advanced(by: -gapStart.position), count: gapStart.position) + unsafe move(from: startSlot, to: newStart, count: headCount - gapStart.position) } else { // We need to move elements across a wrap that won't go away. // 0) FG.̲.̲.̲HIJKLMNO....ABCDE // 1) ...̲F̲G̲HIJKLMNO....ABCDE // 2) CDE̲F̲G̲HIJKLMNO....AB... // 3) CDE̲F̲G̲HIJKLMNO.......AB - move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: gapStart.position) - move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize) - move(from: startSlot, to: newStart, count: headCount - gapEnd.position) + unsafe move(from: .zero, to: Slot.zero.advanced(by: gapSize), count: gapStart.position) + unsafe move(from: limSlot.advanced(by: -gapSize), to: .zero, count: gapSize) + unsafe move(from: startSlot, to: newStart, count: headCount - gapEnd.position) } - startSlot = newStart - count -= gapSize + unsafe _startSlot = newStart + unsafe _count -= gapSize } } } @@ -1253,13 +1277,13 @@ extension _UnsafeDequeHandle where Element: ~Copyable { let gapSize = capacity - count if gapSize > 0 { - _ = openGap(ofSize: gapSize, atOffset: newStart) + _ = unsafe openGap(ofSize: gapSize, atOffset: newStart) } // With the prefix and suffix swapped, update the starting slot and // restore the count. - startSlot = slot(startSlot, offsetBy: newStart - oldCount) - count = oldCount + unsafe _startSlot = slot(startSlot, offsetBy: newStart - oldCount) + unsafe _count = oldCount } } @@ -1273,16 +1297,16 @@ extension _UnsafeDequeHandle where Element: ~Copyable { ) -> Int { assert(count < capacity) if offset == 0 { - uncheckedPrepend(newElement) + unsafe uncheckedPrepend(newElement) return offset } if offset == count { - uncheckedAppend(newElement) + unsafe uncheckedAppend(newElement) return offset } - let gap = openGap(ofSize: 1, atOffset: offset) - assert(gap.first.count == 1) - gap.first.baseAddress!.initialize(to: newElement) + let gap = unsafe openGap(ofSize: 1, atOffset: offset) + assert(unsafe gap.first.count == 1) + unsafe gap.first.baseAddress!.initialize(to: newElement) return offset } } @@ -1296,19 +1320,19 @@ extension _UnsafeDequeHandle where Element: ~Copyable { initializingWith body: (inout OutputSpan) throws(E) -> Void ) throws(E) -> Range { guard newItemCount > 0 else { return offset ..< offset } - let gap = self.openGap(ofSize: newItemCount, atOffset: offset) + let gap = unsafe self.openGap(ofSize: newItemCount, atOffset: offset) var c = 0 defer { if c < newItemCount { - closeGap(offsets: offset + c ..< offset + newItemCount) + unsafe closeGap(offsets: offset + c ..< offset + newItemCount) } } - try gap.first._initialize(initializedCount: &c, initializingWith: body) - if c == gap.first.count, let second = gap.second { - try second._initialize(initializedCount: &c, initializingWith: body) + unsafe try gap.first._initialize(initializedCount: &c, initializingWith: body) + if unsafe c == gap.first.count, let second = unsafe gap.second { + unsafe try second._initialize(initializedCount: &c, initializingWith: body) } - return Range(uncheckedBounds: (offset, offset &+ c)) + return unsafe Range(uncheckedBounds: (offset, offset &+ c)) } } @@ -1333,8 +1357,8 @@ extension _UnsafeDequeHandle { assert(offset <= count) assert(newElements.count == newCount) guard newCount > 0 else { return } - let gap = openGap(ofSize: newCount, atOffset: offset) - gap.initialize(copying: newElements) + let gap = unsafe openGap(ofSize: newCount, atOffset: offset) + unsafe gap.initialize(copying: newElements) } } @@ -1345,8 +1369,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_transparent internal mutating func uncheckedRemove(at offset: Int) -> Element { let slot = self.slot(forOffset: offset) - let result = mutablePtr(at: slot).move() - closeGap(offsets: Range(uncheckedBounds: (offset, offset + 1))) + let result = unsafe mutablePtr(at: slot).move() + unsafe closeGap(offsets: Range(uncheckedBounds: (offset, offset + 1))) return result } @@ -1354,9 +1378,9 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_transparent internal mutating func uncheckedRemoveFirst() -> Element { assert(count > 0) - let result = mutablePtr(at: startSlot).move() - startSlot = slot(after: startSlot) - count -= 1 + let result = unsafe mutablePtr(at: startSlot).move() + unsafe _startSlot = slot(after: startSlot) + unsafe _count -= 1 return result } @@ -1365,8 +1389,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { internal mutating func uncheckedRemoveLast() -> Element { assert(count > 0) let slot = self.slot(forOffset: count - 1) - let result = mutablePtr(at: slot).move() - count -= 1 + let result = unsafe mutablePtr(at: slot).move() + unsafe _count -= 1 return result } @@ -1375,10 +1399,10 @@ extension _UnsafeDequeHandle where Element: ~Copyable { internal mutating func uncheckedRemoveFirst(_ n: Int) { assert(count >= n) guard n > 0 else { return } - let target = mutableSegments(forOffsets: 0 ..< n) - target.deinitialize() - startSlot = slot(startSlot, offsetBy: n) - count -= n + let target = unsafe mutableSegments(forOffsets: 0 ..< n) + unsafe target.deinitialize() + unsafe _startSlot = slot(startSlot, offsetBy: n) + unsafe _count -= n } @_alwaysEmitIntoClient @@ -1386,9 +1410,9 @@ extension _UnsafeDequeHandle where Element: ~Copyable { internal mutating func uncheckedRemoveLast(_ n: Int) { assert(count >= n) guard n > 0 else { return } - let target = mutableSegments(forOffsets: count - n ..< count) - target.deinitialize() - count -= n + let target = unsafe mutableSegments(forOffsets: count - n ..< count) + unsafe target.deinitialize() + unsafe _count -= n } /// Remove all elements stored in this instance, deinitializing their storage. @@ -1399,10 +1423,10 @@ extension _UnsafeDequeHandle where Element: ~Copyable { @_transparent internal mutating func uncheckedRemoveAll() { guard count > 0 else { return } - let target = mutableSegments() - target.deinitialize() - count = 0 - startSlot = .zero + let target = unsafe mutableSegments() + unsafe target.deinitialize() + unsafe _count = 0 + unsafe _startSlot = .zero } /// Remove all elements in `bounds`, deinitializing their storage and sliding @@ -1416,8 +1440,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { assert(bounds.lowerBound >= 0 && bounds.upperBound <= self.count) // Deinitialize elements in `bounds`. - mutableSegments(forOffsets: bounds).deinitialize() - closeGap(offsets: bounds) + unsafe mutableSegments(forOffsets: bounds).deinitialize() + unsafe closeGap(offsets: bounds) return bounds.lowerBound } } @@ -1437,30 +1461,30 @@ extension _UnsafeDequeHandle where Element: ~Copyable { let delta = newItemCount - subrange.count let left = isLeftLeaning(subrange) if delta > 0 { - _ = self.openGap( + _ = unsafe self.openGap( ofSize: delta, atOffset: (left ? subrange.lowerBound : subrange.upperBound)) } else { - self.closeGap( + unsafe self.closeGap( offsets: (left ? subrange.prefix(-delta) : subrange.suffix(-delta))) } - let newRange = Range( + let newRange = unsafe Range( uncheckedBounds: ( subrange.lowerBound, subrange.lowerBound &+ newItemCount)) - let gap = self.mutableSegments(forOffsets: newRange) + let gap = unsafe self.mutableSegments(forOffsets: newRange) var c = 0 defer { if c < newItemCount { - closeGap(offsets: newRange.dropFirst(c)) + unsafe closeGap(offsets: newRange.dropFirst(c)) } } - try gap.first._initialize(initializedCount: &c, initializingWith: initializer) - if c == gap.first.count, let second = gap.second { - try second._initialize(initializedCount: &c, initializingWith: initializer) + try unsafe gap.first._initialize(initializedCount: &c, initializingWith: initializer) + if unsafe c == gap.first.count, let second = unsafe gap.second { + unsafe try second._initialize(initializedCount: &c, initializingWith: initializer) } - return Range(uncheckedBounds: (newRange.lowerBound, newRange.lowerBound &+ c)) + return unsafe Range(uncheckedBounds: (newRange.lowerBound, newRange.lowerBound &+ c)) } @_alwaysEmitIntoClient @@ -1474,8 +1498,8 @@ extension _UnsafeDequeHandle where Element: ~Copyable { "Subrange out of bounds") assert(newItemCount >= 0, "Cannot add a negative number of items") assert(count + newItemCount - subrange.count <= capacity, "RigidDeque capacity overflow") - self.mutableSegments(forOffsets: subrange).deinitialize() - return try _insertAfterReplace( + unsafe self.mutableSegments(forOffsets: subrange).deinitialize() + return unsafe try _insertAfterReplace( subrange, addingCount: newItemCount, initializingWith: initializer) @@ -1495,17 +1519,17 @@ extension _UnsafeDequeHandle where Element: ~Copyable { assert(newItemCount >= 0, "Cannot add a negative number of items") assert(count + newItemCount - subrange.count <= capacity, "RigidDeque capacity overflow") do { - let removed = self.mutableSegments(forOffsets: subrange) - var span = InputSpan( + let removed = unsafe self.mutableSegments(forOffsets: subrange) + var span = unsafe InputSpan( buffer: removed.first, initializedCount: removed.first.count) consumer(&span) - if let second = removed.second { - span = InputSpan(buffer: second, initializedCount: second.count) + if let second = unsafe removed.second { + span = unsafe InputSpan(buffer: second, initializedCount: second.count) consumer(&span) } } - return try _insertAfterReplace( + return unsafe try _insertAfterReplace( subrange, addingCount: newItemCount, initializingWith: initializer) diff --git a/Sources/DequeModule/_UnsafeDequeSegments.swift b/Sources/DequeModule/_UnsafeDequeSegments.swift index 35c056ca..8019d598 100644 --- a/Sources/DequeModule/_UnsafeDequeSegments.swift +++ b/Sources/DequeModule/_UnsafeDequeSegments.swift @@ -17,6 +17,7 @@ import InternalCollectionsUtilities @frozen @usableFromInline +@unsafe internal struct _UnsafeDequeSegments { @usableFromInline internal let first: UnsafeBufferPointer @@ -30,9 +31,9 @@ internal struct _UnsafeDequeSegments { _ first: UnsafeBufferPointer, _ second: UnsafeBufferPointer? = nil ) { - self.first = first - self.second = second - assert(first.count > 0 || second == nil) + unsafe self.first = first + unsafe self.second = second + assert(unsafe first.count > 0 || second == nil) } @_alwaysEmitIntoClient @@ -41,7 +42,7 @@ internal struct _UnsafeDequeSegments { start: UnsafePointer, count: Int ) { - self.init(UnsafeBufferPointer(start: start, count: count)) + unsafe self.init(UnsafeBufferPointer(start: start, count: count)) } @_alwaysEmitIntoClient @@ -52,19 +53,21 @@ internal struct _UnsafeDequeSegments { second start2: UnsafePointer, count count2: Int ) { - self.init(UnsafeBufferPointer(start: start1, count: count1), - UnsafeBufferPointer(start: start2, count: count2)) + unsafe self.init( + UnsafeBufferPointer(start: start1, count: count1), + UnsafeBufferPointer(start: start2, count: count2)) } @_alwaysEmitIntoClient @_transparent - internal var count: Int { first.count + (second?.count ?? 0) } + internal var count: Int { unsafe first.count + (second?.count ?? 0) } @_alwaysEmitIntoClient @_transparent + @safe internal func isIdentical(to other: Self) -> Bool { - guard self.first._isIdentical(to: other.first) else { return false } - switch (self.second, other.second) { + guard unsafe self.first._isIdentical(to: other.first) else { return false } + switch (unsafe self.second, unsafe other.second) { case (nil, nil): return true case let (a?, b?): return a._isIdentical(to: b) default: return false @@ -74,6 +77,7 @@ internal struct _UnsafeDequeSegments { @frozen @usableFromInline +@unsafe internal struct _UnsafeMutableDequeSegments { @usableFromInline internal let first: UnsafeMutableBufferPointer @@ -84,8 +88,8 @@ internal struct _UnsafeMutableDequeSegments { @_alwaysEmitIntoClient @_transparent internal init() { - self.first = .init(start: nil, count: 0) - self.second = nil + unsafe self.first = .init(start: nil, count: 0) + unsafe self.second = nil } @_alwaysEmitIntoClient @@ -94,9 +98,9 @@ internal struct _UnsafeMutableDequeSegments { _ first: UnsafeMutableBufferPointer, _ second: UnsafeMutableBufferPointer? = nil ) { - self.first = first - self.second = second?.count == 0 ? nil : second - assert(first.count > 0 || second == nil) + unsafe self.first = first + unsafe self.second = second?.count == 0 ? nil : second + assert(unsafe first.count > 0 || second == nil) } @_alwaysEmitIntoClient @@ -105,7 +109,7 @@ internal struct _UnsafeMutableDequeSegments { start: UnsafeMutablePointer, count: Int ) { - self.init(UnsafeMutableBufferPointer(start: start, count: count)) + unsafe self.init(UnsafeMutableBufferPointer(start: start, count: count)) } @_alwaysEmitIntoClient @@ -116,15 +120,17 @@ internal struct _UnsafeMutableDequeSegments { second start2: UnsafeMutablePointer, count count2: Int ) { - self.init(UnsafeMutableBufferPointer(start: start1, count: count1), - UnsafeMutableBufferPointer(start: start2, count: count2)) + unsafe self.init( + UnsafeMutableBufferPointer(start: start1, count: count1), + UnsafeMutableBufferPointer(start: start2, count: count2)) } @_alwaysEmitIntoClient @_transparent internal init(mutating buffer: _UnsafeDequeSegments) { - self.init(.init(mutating: buffer.first), - buffer.second.map { .init(mutating: $0) }) + unsafe self.init( + .init(mutating: buffer.first), + buffer.second.map { unsafe .init(mutating: $0) }) } } @@ -135,7 +141,7 @@ extension _UnsafeMutableDequeSegments { _ first: UnsafeMutableBufferPointer.SubSequence, _ second: UnsafeMutableBufferPointer? = nil ) { - self.init(UnsafeMutableBufferPointer(rebasing: first), second) + unsafe self.init(UnsafeMutableBufferPointer(rebasing: first), second) } @_alwaysEmitIntoClient @@ -144,51 +150,52 @@ extension _UnsafeMutableDequeSegments { _ first: UnsafeMutableBufferPointer, _ second: UnsafeMutableBufferPointer.SubSequence ) { - self.init(first, UnsafeMutableBufferPointer(rebasing: second)) + unsafe self.init(first, UnsafeMutableBufferPointer(rebasing: second)) } } extension _UnsafeMutableDequeSegments where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent - internal var count: Int { first.count + (second?.count ?? 0) } + internal var count: Int { unsafe first.count + (second?.count ?? 0) } @_alwaysEmitIntoClient @_transparent internal func prefix(_ n: Int) -> Self { assert(n >= 0) - if n >= self.count { - return self + if unsafe n >= self.count { + return unsafe self } - if n <= first.count { - return Self(first._extracting(first: n)) + if unsafe n <= first.count { + return unsafe Self(first._extracting(first: n)) } - return Self(first, second!._extracting(first: n - first.count)) + return unsafe Self(first, second!._extracting(first: n - first.count)) } @_alwaysEmitIntoClient @_transparent internal func suffix(_ n: Int) -> Self { assert(n >= 0) - if n >= self.count { - return self + if unsafe n >= self.count { + return unsafe self } - guard let second = second else { - return Self(first._extracting(last: n)) + guard let second = unsafe second else { + return unsafe Self(first._extracting(last: n)) } if n <= second.count { - return Self(second._extracting(last: n)) + return unsafe Self(second._extracting(last: n)) } - return Self(first._extracting(last: n - second.count), second) + return unsafe Self(first._extracting(last: n - second.count), second) } } extension _UnsafeMutableDequeSegments where Element: ~Copyable { @_alwaysEmitIntoClient @_transparent + @unsafe internal func deinitialize() { - first.deinitialize() - second?.deinitialize() + unsafe first.deinitialize() + unsafe second?.deinitialize() } } @@ -201,20 +208,20 @@ extension _UnsafeMutableDequeSegments { ) -> Int where I.Element == Element { var copied = 0 - var gap = first + var gap = unsafe first var wrapped = false while true { if copied == gap.count { - guard !wrapped, let second = second, second.count > 0 else { break } - gap = second + guard !wrapped, let second = unsafe second, second.count > 0 else { break } + unsafe gap = second copied = 0 wrapped = true } guard let next = iterator.next() else { break } - (gap.baseAddress! + copied).initialize(to: next) + unsafe (gap.baseAddress! + copied).initialize(to: next) copied += 1 } - return wrapped ? first.count + copied : copied + return wrapped ? unsafe first.count + copied : copied } @_alwaysEmitIntoClient @@ -223,9 +230,9 @@ extension _UnsafeMutableDequeSegments { fromSequencePrefix elements: __owned S ) -> (iterator: S.Iterator, count: Int) where S.Element == Element { - guard second == nil || first.count >= elements.underestimatedCount else { + guard unsafe second == nil || first.count >= elements.underestimatedCount else { var it = elements.makeIterator() - let copied = initialize(copyingPrefixOf: &it) + let copied = unsafe initialize(copyingPrefixOf: &it) return (it, copied) } // Note: Array._copyContents traps when not given enough space, so we @@ -233,12 +240,12 @@ extension _UnsafeMutableDequeSegments { // // FIXME: Add support for segmented (a.k.a. piecewise contiguous) // collections to the stdlib. - var (it, copied) = elements._copyContents(initializing: first) - if copied == first.count, let second = second { + var (it, copied) = unsafe elements._copyContents(initializing: first) + if unsafe copied == first.count, let second = unsafe second { var i = 0 while i < second.count { guard let next = it.next() else { break } - (second.baseAddress! + i).initialize(to: next) + unsafe (second.baseAddress! + i).initialize(to: next) i += 1 } copied += i @@ -251,13 +258,13 @@ extension _UnsafeMutableDequeSegments { internal func initialize( copying elements: UnsafeBufferPointer ) { - assert(self.count == elements.count) - if let second = second { - let wrap = first.count - first.initializeAll(fromContentsOf: elements._extracting(first: wrap)) - second.initializeAll(fromContentsOf: elements._extracting(last: second.count)) + assert(unsafe self.count == elements.count) + if let second = unsafe second { + let wrap = unsafe first.count + unsafe first.initializeAll(fromContentsOf: elements._extracting(first: wrap)) + unsafe second.initializeAll(fromContentsOf: elements._extracting(last: second.count)) } else { - first.initializeAll(fromContentsOf: elements) + unsafe first.initializeAll(fromContentsOf: elements) } } @@ -266,7 +273,7 @@ extension _UnsafeMutableDequeSegments { internal func initialize( copying elements: UnsafeMutableBufferPointer ) { - self.initialize(copying: UnsafeBufferPointer(elements)) + unsafe self.initialize(copying: UnsafeBufferPointer(elements)) } @_alwaysEmitIntoClient @@ -274,13 +281,13 @@ extension _UnsafeMutableDequeSegments { internal func initialize( copying elements: __owned some Collection ) { - assert(self.count == elements.count) - if let second = second { - let wrap = elements.index(elements.startIndex, offsetBy: first.count) - first.initializeAll(fromContentsOf: elements[..( copying elements: C ) where C.Element == Element { - assert(elements.count == self.count) - deinitialize() - initialize(copying: elements) + assert(unsafe elements.count == self.count) + unsafe deinitialize() + unsafe initialize(copying: elements) } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Builder.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Builder.swift index 1906623a..d7edfcdb 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Builder.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Builder.swift @@ -121,7 +121,9 @@ extension _HashNode.Builder { assert(!node.hasSingletonItem) kind = .collisionNode(node) } else if node.hasSingletonItem { - kind = node.read { .item($0[item: .zero], at: $0.itemMap.first!) } + kind = unsafe node.read { + unsafe .item($0[item: .zero], at: $0.itemMap.first!) + } } else { kind = .node(node) } @@ -145,6 +147,7 @@ extension _HashNode.Builder { extension _HashNode { @inlinable + @unsafe internal mutating func applyReplacement( _ level: _HashLevel, _ replacement: Builder @@ -168,6 +171,7 @@ extension _HashNode { extension _HashNode.Builder { @inlinable + @unsafe internal mutating func addNewCollision( _ level: _HashLevel, _ newItem: __owned Element, _ hash: _Hash ) { @@ -183,7 +187,7 @@ extension _HashNode.Builder { kind = .empty assert(node.isCollisionNode) assert(hash == node.collisionHash) - _ = node.ensureUniqueAndAppendCollision(isUnique: true, newItem) + _ = unsafe node.ensureUniqueAndAppendCollision(isUnique: true, newItem) kind = .collisionNode(node) case .node: fatalError() @@ -191,6 +195,7 @@ extension _HashNode.Builder { } @inlinable + @unsafe internal mutating func addNewItem( _ level: _HashLevel, _ newItem: __owned Element, at newBucket: _Bucket ) { @@ -218,6 +223,7 @@ extension _HashNode.Builder { } @inlinable + @unsafe internal mutating func addNewChildNode( _ level: _HashLevel, _ newChild: __owned _HashNode, at newBucket: _Bucket ) { @@ -239,7 +245,7 @@ extension _HashNode.Builder { let isUnique = node.isUnique() node.ensureUnique( isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild) - node.insertChild(newChild, newBucket) + unsafe node.insertChild(newChild, newBucket) self.kind = .node(node) case .collisionNode(var node): // Expansion @@ -252,6 +258,7 @@ extension _HashNode.Builder { } @inlinable + @unsafe internal mutating func addNewChildBranch( _ level: _HashLevel, _ newChild: __owned Self, at newBucket: _Bucket ) { @@ -261,13 +268,14 @@ extension _HashNode.Builder { case .empty: break case .item(let newItem, _): - self.addNewItem(level, newItem, at: newBucket) + unsafe self.addNewItem(level, newItem, at: newBucket) case .node(let newNode), .collisionNode(let newNode): - self.addNewChildNode(level, newNode, at: newBucket) + unsafe self.addNewChildNode(level, newNode, at: newBucket) } } @inlinable + @unsafe internal static func childBranch( _ level: _HashLevel, _ child: Self, at bucket: _Bucket ) -> Self { @@ -289,20 +297,22 @@ extension _HashNode.Builder { extension _HashNode.Builder { @inlinable + @unsafe internal mutating func copyCollisions( from source: _HashNode.UnsafeHandle, upTo end: _HashSlot ) { assert(isEmpty) - assert(source.isCollisionNode) - assert(end < source.itemsEndSlot) - let h = source.collisionHash + assert(unsafe source.isCollisionNode) + assert(unsafe end < source.itemsEndSlot) + let h = unsafe source.collisionHash for slot: _HashSlot in stride(from: .zero, to: end, by: 1) { - self.addNewCollision(self.level, source[item: slot], h) + unsafe self.addNewCollision(self.level, source[item: slot], h) } } @inlinable + @unsafe internal mutating func copyItems( _ level: _HashLevel, from source: _HashNode.UnsafeHandle, @@ -310,13 +320,14 @@ extension _HashNode.Builder { ) { assert(level == self.level) assert(isEmpty) - assert(!source.isCollisionNode) - for (b, s) in source.itemMap.intersection(_Bitmap(upTo: end)) { - self.addNewItem(level, source[item: s], at: b) + assert(unsafe !source.isCollisionNode) + for (b, s) in unsafe source.itemMap.intersection(_Bitmap(upTo: end)) { + unsafe self.addNewItem(level, source[item: s], at: b) } } @inlinable + @unsafe internal mutating func copyItemsAndChildren( _ level: _HashLevel, from source: _HashNode.UnsafeHandle, @@ -324,12 +335,12 @@ extension _HashNode.Builder { ) { assert(level == self.level) assert(isEmpty) - assert(!source.isCollisionNode) - for (b, s) in source.itemMap { - self.addNewItem(level, source[item: s], at: b) + assert(unsafe !source.isCollisionNode) + for (b, s) in unsafe source.itemMap { + unsafe self.addNewItem(level, source[item: s], at: b) } - for (b, s) in source.childMap.intersection(_Bitmap(upTo: end)) { - self.addNewChildNode(level, source[child: s], at: b) + for (b, s) in unsafe source.childMap.intersection(_Bitmap(upTo: end)) { + unsafe self.addNewChildNode(level, source[child: s], at: b) } } } @@ -355,7 +366,7 @@ extension _HashNode.Builder { @inlinable internal func mapValuesToVoid() -> _HashNode.Builder { if Value.self == Void.self { - return unsafeBitCast(self, to: _HashNode.Builder.self) + return unsafe unsafeBitCast(self, to: _HashNode.Builder.self) } return mapValues { _ in () } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Debugging.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Debugging.swift index e393c73f..da0da591 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Debugging.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Debugging.swift @@ -24,8 +24,8 @@ extension _HashNode { restPrefix: String = "", depth: Int = 0 ) { - read { - $0.dump( + unsafe read { + unsafe $0.dump( iterationOrder: iterationOrder, limit: limit, extra: "count: \(count), ", @@ -39,7 +39,9 @@ extension _HashNode { extension _HashNode.Storage { @usableFromInline final internal func dump(iterationOrder: Bool = false) { - UnsafeHandle.read(self) { $0.dump(iterationOrder: iterationOrder) } + unsafe UnsafeHandle.read(self) { + unsafe $0.dump(iterationOrder: iterationOrder) + } } } @@ -51,7 +53,7 @@ extension _HashNode { } extension _HashNode.UnsafeHandle { internal func _itemString(at slot: _HashSlot) -> String { - let item = self[item: slot] + let item = unsafe self[item: slot] return _HashNode._itemString(for: item) } @@ -74,20 +76,20 @@ extension _HashNode.UnsafeHandle { firstPrefix += " " } print(""" - \(firstPrefix)\(isCollisionNode ? "CollisionNode" : "Node")(\ - at: \(_addressString(for: _header)), \ - \(isCollisionNode ? "hash: \(collisionHash), " : "")\ + \(firstPrefix)\(unsafe isCollisionNode ? "CollisionNode" : "Node")(\ + at: \(_addressString(for: unsafe _header)), \ + \(unsafe isCollisionNode ? "hash: \(unsafe collisionHash), " : "")\ \(extra)\ - byteCapacity: \(byteCapacity), \ - freeBytes: \(bytesFree)) + byteCapacity: \(unsafe byteCapacity), \ + freeBytes: \(unsafe bytesFree)) """) guard limit > 0 else { return } if iterationOrder { - for slot in stride(from: .zero, to: itemsEndSlot, by: 1) { - print(" \(restPrefix)[\(slot)] \(_itemString(at: slot))") + for slot in stride(from: .zero, to: unsafe itemsEndSlot, by: 1) { + print(" \(restPrefix)[\(slot)] \(unsafe _itemString(at: slot))") } - for slot in stride(from: .zero, to: childrenEndSlot, by: 1) { - self[child: slot].dump( + for slot in stride(from: .zero, to: unsafe childrenEndSlot, by: 1) { + unsafe self[child: slot].dump( iterationOrder: true, limit: limit - 1, firstPrefix: " \(restPrefix).\(slot)", @@ -95,9 +97,9 @@ extension _HashNode.UnsafeHandle { depth: depth + 1) } } - else if isCollisionNode { - for slot in stride(from: .zero, to: itemsEndSlot, by: 1) { - print("\(restPrefix)[\(slot)] \(_itemString(at: slot))") + else if unsafe isCollisionNode { + for slot in stride(from: .zero, to: unsafe itemsEndSlot, by: 1) { + print("\(restPrefix)[\(slot)] \(unsafe _itemString(at: slot))") } } else { var itemSlot: _HashSlot = .zero @@ -105,11 +107,11 @@ extension _HashNode.UnsafeHandle { for b in 0 ..< UInt(_Bitmap.capacity) { let bucket = _Bucket(b) let bucketStr = "#\(String(b, radix: _Bitmap.capacity, uppercase: true))" - if itemMap.contains(bucket) { - print("\(restPrefix) \(bucketStr) \(_itemString(at: itemSlot))") + if unsafe itemMap.contains(bucket) { + print("\(restPrefix) \(bucketStr) \(unsafe _itemString(at: itemSlot))") itemSlot = itemSlot.next() - } else if childMap.contains(bucket) { - self[child: childSlot].dump( + } else if unsafe childMap.contains(bucket) { + unsafe self[child: childSlot].dump( iterationOrder: false, limit: limit - 1, firstPrefix: "\(restPrefix) \(bucketStr) ", diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Initializers.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Initializers.swift index 2a2c466c..421f67e0 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Initializers.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Initializers.swift @@ -18,7 +18,7 @@ import InternalCollectionsUtilities extension _HashNode { @inlinable @inline(__always) internal static func _emptyNode() -> _HashNode { - _HashNode(storage: _emptySingleton, count: 0) + unsafe _HashNode(storage: _emptySingleton, count: 0) } @inlinable @@ -27,9 +27,9 @@ extension _HashNode { _ item1: __owned Element, _ item2: __owned Element ) -> _HashNode { - let node = _HashNode.allocateCollision(count: 2, hash) { items in - items.initializeElement(at: 1, to: item1) - items.initializeElement(at: 0, to: item2) + let node = unsafe _HashNode.allocateCollision(count: 2, hash) { items in + unsafe items.initializeElement(at: 1, to: item1) + unsafe items.initializeElement(at: 0, to: item2) }.node node._invariantCheck() return node @@ -41,9 +41,9 @@ extension _HashNode { _ item1: __owned Element, _ inserter2: (UnsafeMutablePointer) -> Void ) -> _HashNode { - let node = _HashNode.allocateCollision(count: 2, hash) { items in - items.initializeElement(at: 1, to: item1) - inserter2(items.baseAddress.unsafelyUnwrapped) + let node = unsafe _HashNode.allocateCollision(count: 2, hash) { items in + unsafe items.initializeElement(at: 1, to: item1) + unsafe inserter2(items.baseAddress.unsafelyUnwrapped) }.node node._invariantCheck() return node @@ -54,13 +54,13 @@ extension _HashNode { _ item: __owned Element, _ bucket: _Bucket ) -> _HashNode { - let r = _HashNode.allocate( + let r = unsafe _HashNode.allocate( itemMap: _Bitmap(bucket), childMap: .empty, count: 1 ) { children, items in assert(items.count == 1 && children.count == 0) - items.initializeElement(at: 0, to: item) + unsafe items.initializeElement(at: 0, to: item) } r.node._invariantCheck() return r.node @@ -73,9 +73,9 @@ extension _HashNode { _ item2: __owned Element, _ bucket2: _Bucket ) -> _HashNode { - _regularNode( + unsafe _regularNode( item1, bucket1, - { $0.initialize(to: item2) }, bucket2).node + { unsafe $0.initialize(to: item2) }, bucket2).node } @inlinable @@ -86,7 +86,7 @@ extension _HashNode { _ bucket2: _Bucket ) -> (node: _HashNode, slot1: _HashSlot, slot2: _HashSlot) { assert(bucket1 != bucket2) - let r = _HashNode.allocate( + let r = unsafe _HashNode.allocate( itemMap: _Bitmap(bucket1, bucket2), childMap: .empty, count: 2 @@ -94,8 +94,8 @@ extension _HashNode { assert(items.count == 2 && children.count == 0) let i1 = bucket1 < bucket2 ? 1 : 0 let i2 = 1 &- i1 - items.initializeElement(at: i1, to: item1) - inserter2(items.baseAddress.unsafelyUnwrapped + i2) + unsafe items.initializeElement(at: i1, to: item1) + unsafe inserter2(items.baseAddress.unsafelyUnwrapped + i2) return (_HashSlot(i2), _HashSlot(i1)) // Note: swapped } r.node._invariantCheck() @@ -107,13 +107,13 @@ extension _HashNode { _ child: __owned _HashNode, _ bucket: _Bucket ) -> _HashNode { - let r = _HashNode.allocate( + let r = unsafe _HashNode.allocate( itemMap: .empty, childMap: _Bitmap(bucket), count: child.count ) { children, items in assert(items.count == 0 && children.count == 1) - children.initializeElement(at: 0, to: child) + unsafe children.initializeElement(at: 0, to: child) } r.node._invariantCheck() return r.node @@ -126,8 +126,8 @@ extension _HashNode { _ child: __owned _HashNode, _ childBucket: _Bucket ) -> _HashNode { - _regularNode( - { $0.initialize(to: item) }, itemBucket, + unsafe _regularNode( + { unsafe $0.initialize(to: item) }, itemBucket, child, childBucket) } @@ -139,14 +139,14 @@ extension _HashNode { _ childBucket: _Bucket ) -> _HashNode { assert(itemBucket != childBucket) - let r = _HashNode.allocate( + let r = unsafe _HashNode.allocate( itemMap: _Bitmap(itemBucket), childMap: _Bitmap(childBucket), count: child.count &+ 1 ) { children, items in assert(items.count == 1 && children.count == 1) - inserter(items.baseAddress.unsafelyUnwrapped) - children.initializeElement(at: 0, to: child) + unsafe inserter(items.baseAddress.unsafelyUnwrapped) + unsafe children.initializeElement(at: 0, to: child) } r.node._invariantCheck() return r.node @@ -160,7 +160,7 @@ extension _HashNode { _ child2Bucket: _Bucket ) -> _HashNode { assert(child1Bucket != child2Bucket) - let r = _HashNode.allocate( + let r = unsafe _HashNode.allocate( itemMap: .empty, childMap: _Bitmap(child1Bucket, child2Bucket), count: child1.count &+ child2.count @@ -168,8 +168,8 @@ extension _HashNode { assert(items.count == 0 && children.count == 2) let i1 = child1Bucket < child2Bucket ? 0 : 1 let i2 = 1 &- i1 - children.initializeElement(at: i1, to: child1) - children.initializeElement(at: i2, to: child2) + unsafe children.initializeElement(at: i1, to: child1) + unsafe children.initializeElement(at: i2, to: child2) } r.node._invariantCheck() return r.node @@ -178,6 +178,7 @@ extension _HashNode { extension _HashNode { @inlinable + @unsafe internal static func build( level: _HashLevel, item1: __owned Element, @@ -187,15 +188,16 @@ extension _HashNode { ) -> (top: _HashNode, leaf: _UnmanagedHashNode, slot1: _HashSlot, slot2: _HashSlot) { assert(hash1.isEqual(to: hash2, upTo: level.ascend())) if hash1 == hash2 { - let top = _collisionNode(hash1, item1, inserter2) - return (top, top.unmanaged, _HashSlot(0), _HashSlot(1)) + let top = unsafe _collisionNode(hash1, item1, inserter2) + return unsafe (top, top.unmanaged, _HashSlot(0), _HashSlot(1)) } - let r = _build( + let r = unsafe _build( level: level, item1: item1, hash1, item2: inserter2, hash2) - return (r.top, r.leaf, r.slot1, r.slot2) + return unsafe (r.top, r.leaf, r.slot1, r.slot2) } @inlinable + @unsafe internal static func _build( level: _HashLevel, item1: __owned Element, @@ -207,14 +209,14 @@ extension _HashNode { let b1 = hash1[level] let b2 = hash2[level] guard b1 == b2 else { - let r = _regularNode(item1, b1, inserter2, b2) - return (r.node, r.node.unmanaged, r.slot1, r.slot2) + let r = unsafe _regularNode(item1, b1, inserter2, b2) + return unsafe (r.node, r.node.unmanaged, r.slot1, r.slot2) } - let r = _build( + let r = unsafe _build( level: level.descend(), item1: item1, hash1, item2: inserter2, hash2) - return (_regularNode(r.top, b1), r.leaf, r.slot1, r.slot2) + return unsafe (_regularNode(r.top, b1), r.leaf, r.slot1, r.slot2) } @inlinable @@ -230,14 +232,14 @@ extension _HashNode { let b1 = hash1[level] let b2 = hash2[level] if b1 == b2 { - let node = build( + let node = unsafe build( level: level.descend(), item1: inserter1, hash1, child2: child2, hash2) - return (_regularNode(node.top, b1), node.leaf, node.slot1, node.slot2) + return unsafe (_regularNode(node.top, b1), node.leaf, node.slot1, node.slot2) } - let node = _regularNode(inserter1, hash1[level], child2, hash2[level]) - return (node, node.unmanaged, .zero, .zero) + let node = unsafe _regularNode(inserter1, hash1[level], child2, hash2[level]) + return unsafe (node, node.unmanaged, .zero, .zero) } @inlinable diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Lookups.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Lookups.swift index d3dbe436..09357a02 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Lookups.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Lookups.swift @@ -18,7 +18,7 @@ extension _HashNode { internal func find( _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> (descend: Bool, slot: _HashSlot)? { - read { $0.find(level, key, hash) } + unsafe read { unsafe $0.find(level, key, hash) } } } @@ -27,19 +27,19 @@ extension _HashNode.UnsafeHandle { internal func find( _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> (descend: Bool, slot: _HashSlot)? { - guard !isCollisionNode else { - let r = _findInCollision(level, key, hash) + guard unsafe !isCollisionNode else { + let r = unsafe _findInCollision(level, key, hash) guard r.code == 0 else { return nil } return (false, r.slot) } let bucket = hash[level] - if itemMap.contains(bucket) { - let slot = itemMap.slot(of: bucket) - guard self[item: slot].key == key else { return nil } + if unsafe itemMap.contains(bucket) { + let slot = unsafe itemMap.slot(of: bucket) + guard unsafe self[item: slot].key == key else { return nil } return (false, slot) } - if childMap.contains(bucket) { - let slot = childMap.slot(of: bucket) + if unsafe childMap.contains(bucket) { + let slot = unsafe childMap.slot(of: bucket) return (true, slot) } return nil @@ -49,14 +49,14 @@ extension _HashNode.UnsafeHandle { internal func _findInCollision( _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> (code: Int, slot: _HashSlot) { - assert(isCollisionNode) + assert(unsafe isCollisionNode) if !level.isAtBottom { - if hash != self.collisionHash { return (2, .zero) } + if unsafe hash != self.collisionHash { return (2, .zero) } } // Note: this searches the items in reverse insertion order. - guard let slot = reverseItems.firstIndex(where: { $0.key == key }) - else { return (1, self.itemsEndSlot) } - return (0, _HashSlot(itemCount &- 1 &- slot)) + guard let slot = unsafe reverseItems.firstIndex(where: { $0.key == key }) + else { return (1, unsafe self.itemsEndSlot) } + return (0, unsafe _HashSlot(itemCount &- 1 &- slot)) } } @@ -135,7 +135,7 @@ extension _HashNode { internal func findForInsertion( _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> _FindResult { - read { $0.findForInsertion(level, key, hash) } + unsafe read { unsafe $0.findForInsertion(level, key, hash) } } } @@ -144,8 +144,8 @@ extension _HashNode.UnsafeHandle { internal func findForInsertion( _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> _FindResult { - guard !isCollisionNode else { - let r = _findInCollision(level, key, hash) + guard unsafe !isCollisionNode else { + let r = unsafe _findInCollision(level, key, hash) if r.code == 0 { return .found(.invalid, r.slot) } @@ -156,18 +156,18 @@ extension _HashNode.UnsafeHandle { return .expansion } let bucket = hash[level] - if itemMap.contains(bucket) { - let slot = itemMap.slot(of: bucket) - if self[item: slot].key == key { + if unsafe itemMap.contains(bucket) { + let slot = unsafe itemMap.slot(of: bucket) + if unsafe self[item: slot].key == key { return .found(bucket, slot) } return .spawnChild(bucket, slot) } - if childMap.contains(bucket) { - let slot = childMap.slot(of: bucket) + if unsafe childMap.contains(bucket) { + let slot = unsafe childMap.slot(of: bucket) return .descend(bucket, slot) } - let slot = itemMap.slot(of: bucket) + let slot = unsafe itemMap.slot(of: bucket) return .insert(bucket, slot) } } @@ -177,17 +177,17 @@ extension _HashNode.UnsafeHandle { extension _HashNode { @inlinable internal func get(_ level: _HashLevel, _ key: Key, _ hash: _Hash) -> Value? { - var node = unmanaged + var node = unsafe unmanaged var level = level while true { - let r = UnsafeHandle.read(node) { $0.find(level, key, hash) } + let r = unsafe UnsafeHandle.read(node) { unsafe $0.find(level, key, hash) } guard let r = r else { return nil } guard r.descend else { - return UnsafeHandle.read(node) { $0[item: r.slot].value } + return unsafe UnsafeHandle.read(node) { unsafe $0[item: r.slot].value } } - node = node.unmanagedChild(at: r.slot) + unsafe node = node.unmanagedChild(at: r.slot) level = level.descend() } } @@ -198,13 +198,13 @@ extension _HashNode { internal func containsKey( _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> Bool { - var node = unmanaged + var node = unsafe unmanaged var level = level while true { - let r = UnsafeHandle.read(node) { $0.find(level, key, hash) } + let r = unsafe UnsafeHandle.read(node) { unsafe $0.find(level, key, hash) } guard let r = r else { return false } guard r.descend else { return true } - node = node.unmanagedChild(at: r.slot) + unsafe node = node.unmanagedChild(at: r.slot) level = level.descend() } } @@ -215,17 +215,17 @@ extension _HashNode { internal func lookup( _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> (node: _UnmanagedHashNode, slot: _HashSlot)? { - var node = unmanaged + var node = unsafe unmanaged var level = level while true { - let r = UnsafeHandle.read(node) { $0.find(level, key, hash) } + let r = unsafe UnsafeHandle.read(node) { unsafe $0.find(level, key, hash) } guard let r = r else { return nil } guard r.descend else { - return (node, r.slot) + return unsafe (node, r.slot) } - node = node.unmanagedChild(at: r.slot) + unsafe node = node.unmanagedChild(at: r.slot) level = level.descend() } } @@ -238,32 +238,32 @@ extension _HashNode { ) -> Int? { guard let r = find(level, key, hash) else { return nil } guard r.descend else { return r.slot.value } - return read { h in - let children = h.children - let p = children[r.slot.value] + return unsafe read { h in + let children = unsafe h.children + let p = unsafe children[r.slot.value] .position(forKey: key, level.descend(), hash) guard let p = p else { return nil } - let c = h.itemCount &+ p - return children[.. Element { assert(position >= 0 && position < self.count) - return read { + return unsafe read { var itemsToSkip = position - let itemCount = $0.itemCount + let itemCount = unsafe $0.itemCount if itemsToSkip < itemCount { - return $0[item: _HashSlot(itemsToSkip)] + return unsafe $0[item: _HashSlot(itemsToSkip)] } itemsToSkip -= itemCount - let children = $0.children + let children = unsafe $0.children for i in children.indices { - if itemsToSkip < children[i].count { - return children[i].item(position: itemsToSkip) + if unsafe itemsToSkip < children[i].count { + return unsafe children[i].item(position: itemsToSkip) } - itemsToSkip -= children[i].count + unsafe itemsToSkip -= children[i].count } fatalError("Inconsistent tree") } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Insertions.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Insertions.swift index 147260c5..720f3e17 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Insertions.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Insertions.swift @@ -24,35 +24,36 @@ extension _HashNode.UnsafeHandle { /// ready to store the new item. It is the caller's responsibility to /// initialize this memory. @inlinable + @unsafe internal func _makeRoomForNewItem( at slot: _HashSlot, _ bucket: _Bucket ) -> UnsafeMutablePointer { assertMutable() - let c = itemCount + let c = unsafe itemCount assert(slot.value <= c) let stride = MemoryLayout.stride - assert(bytesFree >= stride) - bytesFree &-= stride + assert(unsafe bytesFree >= stride) + unsafe bytesFree &-= stride - let start = _memory + let start = unsafe _memory .advanced(by: byteCapacity &- (c &+ 1) &* stride) .bindMemory(to: Element.self, capacity: 1) let prefix = c &- slot.value - start.moveInitialize(from: start + 1, count: prefix) + unsafe start.moveInitialize(from: start + 1, count: prefix) if bucket.isInvalid { - assert(isCollisionNode) - collisionCount &+= 1 + assert(unsafe isCollisionNode) + unsafe collisionCount &+= 1 } else { - assert(!itemMap.contains(bucket)) - assert(!childMap.contains(bucket)) - itemMap.insert(bucket) - assert(itemMap.slot(of: bucket) == slot) + assert(unsafe !itemMap.contains(bucket)) + assert(unsafe !childMap.contains(bucket)) + unsafe itemMap.insert(bucket) + assert(unsafe itemMap.slot(of: bucket) == slot) } - return start + prefix + return unsafe start + prefix } /// Insert `child` at `slot`. There must be enough free space in the node @@ -61,59 +62,63 @@ extension _HashNode.UnsafeHandle { /// `childMap` must not yet reflect the insertion at the time this /// function is called. This method does not update `childMap`. @inlinable + @unsafe internal func _insertChild(_ child: __owned _HashNode, at slot: _HashSlot) { assertMutable() - assert(!isCollisionNode) + assert(unsafe !isCollisionNode) - let c = childMap.count + let c = unsafe childMap.count assert(slot.value <= c) let stride = MemoryLayout<_HashNode>.stride - assert(bytesFree >= stride) - bytesFree &-= stride + assert(unsafe bytesFree >= stride) + unsafe bytesFree &-= stride - _memory.bindMemory(to: _HashNode.self, capacity: c &+ 1) - let q = _childrenStart + slot.value - (q + 1).moveInitialize(from: q, count: c &- slot.value) - q.initialize(to: child) + unsafe _memory.bindMemory(to: _HashNode.self, capacity: c &+ 1) + let q = unsafe _childrenStart + slot.value + unsafe (q + 1).moveInitialize(from: q, count: c &- slot.value) + unsafe q.initialize(to: child) } } extension _HashNode { @inlinable @inline(__always) + @unsafe internal mutating func insertItem( _ item: __owned Element, at bucket: _Bucket ) { - let slot = read { $0.itemMap.slot(of: bucket) } - self.insertItem(item, at: slot, bucket) + let slot = unsafe read { unsafe $0.itemMap.slot(of: bucket) } + unsafe self.insertItem(item, at: slot, bucket) } @inlinable @inline(__always) + @unsafe internal mutating func insertItem( _ item: __owned Element, at slot: _HashSlot, _ bucket: _Bucket ) { self.count &+= 1 - update { - let p = $0._makeRoomForNewItem(at: slot, bucket) - p.initialize(to: item) + unsafe update { + let p = unsafe $0._makeRoomForNewItem(at: slot, bucket) + unsafe p.initialize(to: item) } } /// Insert `child` in `bucket`. There must be enough free space in the /// node to fit the new child. @inlinable + @unsafe internal mutating func insertChild( _ child: __owned _HashNode, _ bucket: _Bucket ) { count &+= child.count - update { - assert(!$0.isCollisionNode) - assert(!$0.itemMap.contains(bucket)) - assert(!$0.childMap.contains(bucket)) + unsafe update { + assert(unsafe !$0.isCollisionNode) + assert(unsafe !$0.itemMap.contains(bucket)) + assert(unsafe !$0.childMap.contains(bucket)) - let slot = $0.childMap.slot(of: bucket) - $0._insertChild(child, at: slot) - $0.childMap.insert(bucket) + let slot = unsafe $0.childMap.slot(of: bucket) + unsafe $0._insertChild(child, at: slot) + unsafe $0.childMap.insert(bucket) } } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Removals.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Removals.swift index 03950752..094fcacf 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Removals.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Removals.swift @@ -20,26 +20,27 @@ extension _HashNode.UnsafeHandle { /// `itemMap` must not yet reflect the removal at the time this /// function is called. This method does not update `itemMap`. @inlinable + @unsafe internal func _removeItem( at slot: _HashSlot, by remover: (UnsafeMutablePointer) -> R ) -> R { assertMutable() - let c = itemCount + let c = unsafe itemCount assert(slot.value < c) let stride = MemoryLayout.stride - bytesFree &+= stride + unsafe bytesFree &+= stride - let start = _memory + let start = unsafe _memory .advanced(by: byteCapacity &- stride &* c) .assumingMemoryBound(to: Element.self) let prefix = c &- 1 &- slot.value - let q = start + prefix + let q = unsafe start + prefix defer { - (start + 1).moveInitialize(from: start, count: prefix) + unsafe (start + 1).moveInitialize(from: start, count: prefix) } - return remover(q) + return unsafe remover(q) } /// Remove and return the child at `slot`, increasing the amount of free @@ -48,35 +49,38 @@ extension _HashNode.UnsafeHandle { /// `childMap` must not yet reflect the removal at the time this /// function is called. This method does not update `childMap`. @inlinable + @unsafe internal func _removeChild(at slot: _HashSlot) -> _HashNode { assertMutable() - assert(!isCollisionNode) - let count = childCount + assert(unsafe !isCollisionNode) + let count = unsafe childCount assert(slot.value < count) - bytesFree &+= MemoryLayout<_HashNode>.stride + unsafe bytesFree &+= MemoryLayout<_HashNode>.stride - let q = _childrenStart + slot.value - let child = q.move() - q.moveInitialize(from: q + 1, count: count &- 1 &- slot.value) + let q = unsafe _childrenStart + slot.value + let child = unsafe q.move() + unsafe q.moveInitialize(from: q + 1, count: count &- 1 &- slot.value) return child } } extension _HashNode { @inlinable + @unsafe internal mutating func removeItem( at bucket: _Bucket ) -> Element { - let slot = read { $0.itemMap.slot(of: bucket) } - return removeItem(at: bucket, slot, by: { $0.move() }) + let slot = unsafe read { unsafe $0.itemMap.slot(of: bucket) } + return unsafe removeItem(at: bucket, slot, by: { unsafe $0.move() }) } @inlinable + @unsafe internal mutating func removeItem( at bucket: _Bucket, _ slot: _HashSlot ) -> Element { - removeItem(at: bucket, slot, by: { $0.move() }) + unsafe removeItem(at: bucket, slot, by: { unsafe $0.move() }) } /// Remove the item at `slot`, increasing the amount of free @@ -85,6 +89,7 @@ extension _HashNode { /// The closure `remove` is called to perform the deinitialization of the /// storage slot corresponding to the item to be removed. @inlinable + @unsafe internal mutating func removeItem( at bucket: _Bucket, _ slot: _HashSlot, by remover: (UnsafeMutablePointer) -> R @@ -92,30 +97,31 @@ extension _HashNode { defer { _invariantCheck() } assert(count > 0) count &-= 1 - return update { - let old = $0._removeItem(at: slot, by: remover) - if $0.isCollisionNode { - assert(slot.value < $0.collisionCount) - $0.collisionCount &-= 1 + return unsafe update { + let old = unsafe $0._removeItem(at: slot, by: remover) + if unsafe $0.isCollisionNode { + assert(unsafe slot.value < $0.collisionCount) + unsafe $0.collisionCount &-= 1 } else { - assert($0.itemMap.contains(bucket)) - assert($0.itemMap.slot(of: bucket) == slot) - $0.itemMap.remove(bucket) + assert(unsafe $0.itemMap.contains(bucket)) + assert(unsafe $0.itemMap.slot(of: bucket) == slot) + unsafe $0.itemMap.remove(bucket) } return old } } @inlinable + @unsafe internal mutating func removeChild( at bucket: _Bucket, _ slot: _HashSlot ) -> _HashNode { assert(!isCollisionNode) - let child: _HashNode = update { - assert($0.childMap.contains(bucket)) - assert($0.childMap.slot(of: bucket) == slot) - let child = $0._removeChild(at: slot) - $0.childMap.remove(bucket) + let child: _HashNode = unsafe update { + assert(unsafe $0.childMap.contains(bucket)) + assert(unsafe $0.childMap.slot(of: bucket) == slot) + let child = unsafe $0._removeChild(at: slot) + unsafe $0.childMap.remove(bucket) return child } assert(self.count >= child.count) @@ -124,14 +130,15 @@ extension _HashNode { } @inlinable + @unsafe internal mutating func removeSingletonItem() -> Element { defer { _invariantCheck() } assert(count == 1) count = 0 - return update { - assert($0.hasSingletonItem) - let old = $0._removeItem(at: .zero) { $0.move() } - $0.clear() + return unsafe update { + assert(unsafe $0.hasSingletonItem) + let old = unsafe $0._removeItem(at: .zero) { unsafe $0.move() } + unsafe $0.clear() return old } } @@ -139,10 +146,10 @@ extension _HashNode { @inlinable internal mutating func removeSingletonChild() -> _HashNode { defer { _invariantCheck() } - let child: _HashNode = update { - assert($0.hasSingletonChild) - let child = $0._removeChild(at: .zero) - $0.childMap = .empty + let child: _HashNode = unsafe update { + assert(unsafe $0.hasSingletonChild) + let child = unsafe $0._removeChild(at: .zero) + unsafe $0.childMap = .empty return child } assert(self.count == child.count) diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Replacement.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Replacement.swift index 912d5ecd..08968048 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Replacement.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Primitive Replacement.swift @@ -13,36 +13,39 @@ extension _HashNode { @inlinable + @unsafe internal mutating func replaceItem( at bucket: _Bucket, _ slot: _HashSlot, with item: __owned Element ) { - update { - assert($0.isCollisionNode || $0.itemMap.contains(bucket)) - assert($0.isCollisionNode || slot == $0.itemMap.slot(of: bucket)) - assert(!$0.isCollisionNode || slot.value < $0.collisionCount) - $0[item: slot] = item + unsafe update { + assert(unsafe $0.isCollisionNode || $0.itemMap.contains(bucket)) + assert(unsafe $0.isCollisionNode || slot == $0.itemMap.slot(of: bucket)) + assert(unsafe !$0.isCollisionNode || slot.value < $0.collisionCount) + unsafe $0[item: slot] = item } } @inlinable + @unsafe internal mutating func replaceChild( at bucket: _Bucket, with child: __owned _HashNode ) -> Int { - let slot = read { $0.childMap.slot(of: bucket) } - return replaceChild(at: bucket, slot, with: child) + let slot = unsafe read { unsafe $0.childMap.slot(of: bucket) } + return unsafe replaceChild(at: bucket, slot, with: child) } @inlinable + @unsafe internal mutating func replaceChild( at bucket: _Bucket, _ slot: _HashSlot, with child: __owned _HashNode ) -> Int { - let delta: Int = update { - assert(!$0.isCollisionNode) - assert($0.childMap.contains(bucket)) - assert($0.childMap.slot(of: bucket) == slot) - let p = $0.childPtr(at: slot) - let delta = child.count &- p.pointee.count - p.pointee = child + let delta: Int = unsafe update { + assert(unsafe !$0.isCollisionNode) + assert(unsafe $0.childMap.contains(bucket)) + assert(unsafe $0.childMap.slot(of: bucket) == slot) + let p = unsafe $0.childPtr(at: slot) + let delta = unsafe child.count &- p.pointee.count + unsafe p.pointee = child return delta } self.count &+= delta @@ -50,6 +53,7 @@ extension _HashNode { } @inlinable + @unsafe internal func replacingChild( _ level: _HashLevel, at bucket: _Bucket, @@ -57,26 +61,26 @@ extension _HashNode { with child: __owned Builder ) -> Builder { assert(child.level == level.descend()) - read { - assert(!$0.isCollisionNode) - assert($0.childMap.contains(bucket)) - assert(slot == $0.childMap.slot(of: bucket)) + unsafe read { + assert(unsafe !$0.isCollisionNode) + assert(unsafe $0.childMap.contains(bucket)) + assert(unsafe slot == $0.childMap.slot(of: bucket)) } switch child.kind { case .empty: - return _removingChild(level, at: bucket, slot) + return unsafe _removingChild(level, at: bucket, slot) case let .item(item, _): if hasSingletonChild { return .item(level, item, at: bucket) } var node = self.copy(withFreeSpace: _HashNode.spaceForInlinedChild) - _ = node.removeChild(at: bucket, slot) - node.insertItem(item, at: bucket) + _ = unsafe node.removeChild(at: bucket, slot) + unsafe node.insertItem(item, at: bucket) node._invariantCheck() return .node(level, node) case let .node(node): var copy = self.copy() - _ = copy.replaceChild(at: bucket, slot, with: node) + _ = unsafe copy.replaceChild(at: bucket, slot, with: node) return .node(level, copy) case let .collisionNode(node): if hasSingletonChild { @@ -85,7 +89,7 @@ extension _HashNode { return .collisionNode(level, node) } var copy = self.copy() - _ = copy.replaceChild(at: bucket, slot, with: node) + _ = unsafe copy.replaceChild(at: bucket, slot, with: node) return .node(level, copy) } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift index 906bc80e..da933b7b 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Storage.swift @@ -47,9 +47,9 @@ extension _HashNode { @inlinable deinit { - UnsafeHandle.update(self) { handle in - handle.children.deinitialize() - handle.reverseItems.deinitialize() + unsafe UnsafeHandle.update(self) { handle in + unsafe handle.children.deinitialize() + unsafe handle.reverseItems.deinitialize() } } } @@ -89,16 +89,16 @@ extension _HashNode.Storage { _HashNodeHeader(byteCapacity: mincap * childStride) } - object.withUnsafeMutablePointers { header, elements in + unsafe object.withUnsafeMutablePointers { header, elements in let start = UnsafeRawPointer(elements) - let end = start + let end = unsafe start .advanced(by: Int(header.pointee.byteCapacity)) .alignedDown(for: Element.self) - header.pointee._byteCapacity = UInt32(start.distance(to: end)) - header.pointee._bytesFree = header.pointee._byteCapacity - assert(byteCapacity <= header.pointee.byteCapacity) + unsafe header.pointee._byteCapacity = UInt32(start.distance(to: end)) + unsafe header.pointee._bytesFree = header.pointee._byteCapacity + assert(unsafe byteCapacity <= header.pointee.byteCapacity) } - return unsafeDowncast(object, to: _HashNode.Storage.self) + return unsafe unsafeDowncast(object, to: _HashNode.Storage.self) } } @@ -176,19 +176,19 @@ extension _HashNode { let storage = Storage.allocate( byteCapacity: occupiedBytes &+ extraBytes) var node = _HashNode(storage: storage, count: count) - let result: R = node.update { - $0.itemMap = itemMap - $0.childMap = childMap + let result: R = unsafe node.update { + unsafe $0.itemMap = itemMap + unsafe $0.childMap = childMap - assert(occupiedBytes <= $0.bytesFree) - $0.bytesFree &-= occupiedBytes + assert(unsafe occupiedBytes <= $0.bytesFree) + unsafe $0.bytesFree &-= occupiedBytes - let childStart = $0._memory + let childStart = unsafe $0._memory .bindMemory(to: _HashNode.self, capacity: childCount) - let itemStart = ($0._memory + ($0.byteCapacity - itemBytes)) + let itemStart = unsafe ($0._memory + ($0.byteCapacity - itemBytes)) .bindMemory(to: Element.self, capacity: itemCount) - return initializer( + return unsafe initializer( UnsafeMutableBufferPointer(start: childStart, count: childCount), UnsafeMutableBufferPointer(start: itemStart, count: itemCount)) } @@ -210,19 +210,19 @@ extension _HashNode { assert(MemoryLayout<_Hash>.alignment <= MemoryLayout<_RawHashNode>.alignment) let storage = Storage.allocate(byteCapacity: bytes &+ extraBytes) var node = _HashNode(storage: storage, count: count) - let result: R = node.update { - $0.itemMap = _Bitmap(bitPattern: count) - $0.childMap = $0.itemMap - assert(bytes <= $0.bytesFree) - $0.bytesFree &-= bytes + let result: R = unsafe node.update { + unsafe $0.itemMap = _Bitmap(bitPattern: count) + unsafe $0.childMap = $0.itemMap + assert(unsafe bytes <= $0.bytesFree) + unsafe $0.bytesFree &-= bytes - $0._memory.storeBytes(of: hash, as: _Hash.self) + unsafe $0._memory.storeBytes(of: hash, as: _Hash.self) - let itemStart = ($0._memory + ($0.byteCapacity &- itemBytes)) + let itemStart = unsafe ($0._memory + ($0.byteCapacity &- itemBytes)) .bindMemory(to: Element.self, capacity: count) - let items = UnsafeMutableBufferPointer(start: itemStart, count: count) - return initializer(items) + let items = unsafe UnsafeMutableBufferPointer(start: itemStart, count: count) + return unsafe initializer(items) } return (node, result) } @@ -233,23 +233,23 @@ extension _HashNode { assert(space >= 0) if isCollisionNode { - return read { src in - Self.allocateCollision( + return unsafe read { src in + unsafe Self.allocateCollision( count: self.count, self.collisionHash ) { dstItems in - dstItems.initializeAll(fromContentsOf: src.reverseItems) + unsafe dstItems.initializeAll(fromContentsOf: src.reverseItems) }.node } } - return read { src in - Self.allocate( + return unsafe read { src in + unsafe Self.allocate( itemMap: src.itemMap, childMap: src.childMap, count: self.count, extraBytes: space ) { dstChildren, dstItems in - dstChildren.initializeAll(fromContentsOf: src.children) - dstItems.initializeAll(fromContentsOf: src.reverseItems) + unsafe dstChildren.initializeAll(fromContentsOf: src.children) + unsafe dstItems.initializeAll(fromContentsOf: src.reverseItems) }.node } } @@ -259,26 +259,26 @@ extension _HashNode { assert(space >= 0) let c = self.count if isCollisionNode { - self = update { src in - Self.allocateCollision( + self = unsafe update { src in + unsafe Self.allocateCollision( count: c, src.collisionHash ) { dstItems in - dstItems.moveInitializeAll(fromContentsOf: src.reverseItems) - src.clear() + unsafe dstItems.moveInitializeAll(fromContentsOf: src.reverseItems) + unsafe src.clear() }.node } return } - self = update { src in - Self.allocate( + self = unsafe update { src in + unsafe Self.allocate( itemMap: src.itemMap, childMap: src.childMap, count: c, extraBytes: space ) { dstChildren, dstItems in - dstChildren.moveInitializeAll(fromContentsOf: src.children) - dstItems.moveInitializeAll(fromContentsOf: src.reverseItems) - src.clear() + unsafe dstChildren.moveInitializeAll(fromContentsOf: src.children) + unsafe dstItems.moveInitializeAll(fromContentsOf: src.reverseItems) + unsafe src.clear() }.node } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural compactMapValues.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural compactMapValues.swift index b0137e25..59aed2db 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural compactMapValues.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural compactMapValues.swift @@ -17,30 +17,30 @@ extension _HashNode { _ level: _HashLevel, _ transform: (Value) throws -> T? ) rethrows -> _HashNode.Builder { - return try self.read { + return unsafe try self.read { var result: _HashNode.Builder = .empty(level) if isCollisionNode { - let items = $0.reverseItems + let items = unsafe $0.reverseItems for i in items.indices { - if let v = try transform(items[i].value) { - result.addNewCollision(level, (items[i].key, v), $0.collisionHash) + if let v = unsafe try transform(items[i].value) { + unsafe result.addNewCollision(level, (items[i].key, v), $0.collisionHash) } } return result } - for (bucket, slot) in $0.itemMap { - let p = $0.itemPtr(at: slot) - if let v = try transform(p.pointee.value) { - result.addNewItem(level, (p.pointee.key, v), at: bucket) + for (bucket, slot) in unsafe $0.itemMap { + let p = unsafe $0.itemPtr(at: slot) + if let v = unsafe try transform(p.pointee.value) { + unsafe result.addNewItem(level, (p.pointee.key, v), at: bucket) } } - for (bucket, slot) in $0.childMap { - let branch = try $0[child: slot] + for (bucket, slot) in unsafe $0.childMap { + let branch = unsafe try $0[child: slot] .compactMapValues(level.descend(), transform) - result.addNewChildBranch(level, branch, at: bucket) + unsafe result.addNewChildBranch(level, branch, at: bucket) } return result } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural filter.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural filter.swift index 2a6c0422..60edf55d 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural filter.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural filter.swift @@ -20,35 +20,35 @@ extension _HashNode { guard !isCollisionNode else { return try _filter_slow(level, isIncluded) } - return try self.read { + return unsafe try self.read { var result: Builder = .empty(level) var removing = false // true if we need to remove something - for (bucket, slot) in $0.itemMap { - let p = $0.itemPtr(at: slot) - let include = try isIncluded(p.pointee) + for (bucket, slot) in unsafe $0.itemMap { + let p = unsafe $0.itemPtr(at: slot) + let include = try isIncluded(unsafe p.pointee) switch (include, removing) { case (true, true): - result.addNewItem(level, p.pointee, at: bucket) + unsafe result.addNewItem(level, p.pointee, at: bucket) case (false, false): removing = true - result.copyItems(level, from: $0, upTo: bucket) + unsafe result.copyItems(level, from: $0, upTo: bucket) default: break } } - for (bucket, slot) in $0.childMap { - let branch = try $0[child: slot].filter(level.descend(), isIncluded) + for (bucket, slot) in unsafe $0.childMap { + let branch = unsafe try $0[child: slot].filter(level.descend(), isIncluded) if let branch = branch { assert(branch.count < self.count) if !removing { removing = true - result.copyItemsAndChildren(level, from: $0, upTo: bucket) + unsafe result.copyItemsAndChildren(level, from: $0, upTo: bucket) } - result.addNewChildBranch(level, branch, at: bucket) + unsafe result.addNewChildBranch(level, branch, at: bucket) } else if removing { - result.addNewChildNode(level, $0[child: slot], at: bucket) + unsafe result.addNewChildNode(level, $0[child: slot], at: bucket) } } @@ -62,19 +62,19 @@ extension _HashNode { _ level: _HashLevel, _ isIncluded: (Element) throws -> Bool ) rethrows -> Builder? { - try self.read { + unsafe try self.read { var result: Builder = .empty(level) var removing = false - for slot: _HashSlot in stride(from: .zero, to: $0.itemsEndSlot, by: 1) { - let p = $0.itemPtr(at: slot) - let include = try isIncluded(p.pointee) + for slot: _HashSlot in stride(from: .zero, to: unsafe $0.itemsEndSlot, by: 1) { + let p = unsafe $0.itemPtr(at: slot) + let include = unsafe try isIncluded(p.pointee) if include, removing { - result.addNewCollision(level, p.pointee, $0.collisionHash) + unsafe result.addNewCollision(level, p.pointee, $0.collisionHash) } else if !include, !removing { removing = true - result.copyCollisions(from: $0, upTo: slot) + unsafe result.copyCollisions(from: $0, upTo: slot) } } guard removing else { return nil } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural intersection.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural intersection.swift index cff0c600..2873ca33 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural intersection.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural intersection.swift @@ -36,68 +36,68 @@ extension _HashNode { return _intersection_slow(level, other) } - return self.read { l in - other.read { r in + return unsafe self.read { l in + unsafe other.read { r in var result: Builder = .empty(level) var removing = false - for (bucket, lslot) in l.itemMap { - let lp = l.itemPtr(at: lslot) + for (bucket, lslot) in unsafe l.itemMap { + let lp = unsafe l.itemPtr(at: lslot) let include: Bool - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - include = (lp.pointee.key == r[item: rslot].key) + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + include = unsafe (lp.pointee.key == r[item: rslot].key) } - else if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - let h = _Hash(lp.pointee.key) - include = r[child: rslot] + else if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + let h = unsafe _Hash(lp.pointee.key) + include = unsafe r[child: rslot] .containsKey(level.descend(), lp.pointee.key, h) } else { include = false} if include, removing { - result.addNewItem(level, lp.pointee, at: bucket) + unsafe result.addNewItem(level, lp.pointee, at: bucket) } else if !include, !removing { removing = true - result.copyItems(level, from: l, upTo: bucket) + unsafe result.copyItems(level, from: l, upTo: bucket) } } - for (bucket, lslot) in l.childMap { - if r.itemMap.contains(bucket) { + for (bucket, lslot) in unsafe l.childMap { + if unsafe r.itemMap.contains(bucket) { if !removing { removing = true - result.copyItemsAndChildren(level, from: l, upTo: bucket) + unsafe result.copyItemsAndChildren(level, from: l, upTo: bucket) } - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) - let h = _Hash(rp.pointee.key) - let res = l[child: lslot].lookup(level.descend(), rp.pointee.key, h) - if let res = res { - let item = UnsafeHandle.read(res.node) { $0[item: res.slot] } - result.addNewItem(level, item, at: bucket) + let rslot = unsafe r.itemMap.slot(of: bucket) + let rp = unsafe r.itemPtr(at: rslot) + let h = unsafe _Hash(rp.pointee.key) + let res = unsafe l[child: lslot].lookup(level.descend(), rp.pointee.key, h) + if let res = unsafe res { + let item = unsafe UnsafeHandle.read(res.node) { unsafe $0[item: res.slot] } + unsafe result.addNewItem(level, item, at: bucket) } } - else if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - let branch = l[child: lslot] + else if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + let branch = unsafe l[child: lslot] ._intersection(level.descend(), r[child: rslot]) if let branch = branch { assert(branch.count < self.count) if !removing { removing = true - result.copyItemsAndChildren(level, from: l, upTo: bucket) + unsafe result.copyItemsAndChildren(level, from: l, upTo: bucket) } - result.addNewChildBranch(level, branch, at: bucket) + unsafe result.addNewChildBranch(level, branch, at: bucket) } else if removing { - result.addNewChildNode(level, l[child: lslot], at: bucket) + unsafe result.addNewChildNode(level, l[child: lslot], at: bucket) } } else if !removing { removing = true - result.copyItemsAndChildren(level, from: l, upTo: bucket) + unsafe result.copyItemsAndChildren(level, from: l, upTo: bucket) } } guard removing else { return nil } @@ -114,22 +114,22 @@ extension _HashNode { let lc = self.isCollisionNode let rc = other.isCollisionNode if lc && rc { - return read { l in - other.read { r in + return unsafe read { l in + unsafe other.read { r in var result: Builder = .empty(level) - guard l.collisionHash == r.collisionHash else { return result } + guard unsafe l.collisionHash == r.collisionHash else { return result } var removing = false - let ritems = r.reverseItems - for lslot: _HashSlot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { - let lp = l.itemPtr(at: lslot) - let include = ritems.contains { $0.key == lp.pointee.key } + let ritems = unsafe r.reverseItems + for lslot: _HashSlot in stride(from: .zero, to: unsafe l.itemsEndSlot, by: 1) { + let lp = unsafe l.itemPtr(at: lslot) + let include = unsafe ritems.contains { unsafe $0.key == lp.pointee.key } if include, removing { - result.addNewCollision(level, lp.pointee, l.collisionHash) + unsafe result.addNewCollision(level, lp.pointee, l.collisionHash) } else if !include, !removing { removing = true - result.copyCollisions(from: l, upTo: lslot) + unsafe result.copyCollisions(from: l, upTo: lslot) } } guard removing else { return nil } @@ -145,21 +145,21 @@ extension _HashNode { if lc { // `self` is a collision node on a compressed path. The other tree might // have the same set of collisions, just expanded a bit deeper. - return read { l in - other.read { r in - let bucket = l.collisionHash[level] - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let ritem = r.itemPtr(at: rslot) - let litems = l.reverseItems - let i = litems.firstIndex { $0.key == ritem.pointee.key } + return unsafe read { l in + unsafe other.read { r in + let bucket = unsafe l.collisionHash[level] + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let ritem = unsafe r.itemPtr(at: rslot) + let litems = unsafe l.reverseItems + let i = unsafe litems.firstIndex { unsafe $0.key == ritem.pointee.key } guard let i = i else { return .empty(level) } - return .item(level, litems[i], at: l.collisionHash[level]) + return unsafe .item(level, litems[i], at: l.collisionHash[level]) } - if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - return _intersection(level.descend(), r[child: rslot]) - .map { .childBranch(level, $0, at: bucket) } + if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + return unsafe _intersection(level.descend(), r[child: rslot]) + .map { unsafe .childBranch(level, $0, at: bucket) } } return .empty(level) } @@ -168,27 +168,27 @@ extension _HashNode { assert(rc) // `other` is a collision node on a compressed path. - return read { l in - other.read { r in - let bucket = r.collisionHash[level] - if l.itemMap.contains(bucket) { - let lslot = l.itemMap.slot(of: bucket) - let litem = l.itemPtr(at: lslot) - let ritems = r.reverseItems - let found = ritems.contains { $0.key == litem.pointee.key } + return unsafe read { l in + unsafe other.read { r in + let bucket = unsafe r.collisionHash[level] + if unsafe l.itemMap.contains(bucket) { + let lslot = unsafe l.itemMap.slot(of: bucket) + let litem = unsafe l.itemPtr(at: lslot) + let ritems = unsafe r.reverseItems + let found = unsafe ritems.contains { unsafe $0.key == litem.pointee.key } guard found else { return .empty(level) } - return .item(level, litem.pointee, at: bucket) + return unsafe .item(level, litem.pointee, at: bucket) } - if l.childMap.contains(bucket) { - let lslot = l.childMap.slot(of: bucket) - let branch = l[child: lslot]._intersection(level.descend(), other) + if unsafe l.childMap.contains(bucket) { + let lslot = unsafe l.childMap.slot(of: bucket) + let branch = unsafe l[child: lslot]._intersection(level.descend(), other) guard let branch = branch else { - assert(l[child: lslot].isCollisionNode) - assert(l[child: lslot].collisionHash == r.collisionHash) + assert(unsafe l[child: lslot].isCollisionNode) + assert(unsafe l[child: lslot].collisionHash == r.collisionHash) // Compression - return .collisionNode(level, l[child: lslot]) + return .collisionNode(level, unsafe l[child: lslot]) } - return .childBranch(level, branch, at: bucket) + return unsafe .childBranch(level, branch, at: bucket) } return .empty(level) } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural isDisjoint.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isDisjoint.swift index 48217a8c..b015c8b5 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural isDisjoint.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isDisjoint.swift @@ -29,42 +29,42 @@ extension _HashNode { return other._isDisjointCollision(level, with: self) } - return self.read { l in - other.read { r in - let lmap = l.itemMap.union(l.childMap) - let rmap = r.itemMap.union(r.childMap) - if lmap.isDisjoint(with: rmap) { return true } + return unsafe self.read { l in + unsafe other.read { r in + let lmap = unsafe l.itemMap.union(l.childMap) + let rmap = unsafe r.itemMap.union(r.childMap) + if lmap.isDisjoint(with: rmap) { return true } - for (bucket, _) in l.itemMap.intersection(r.itemMap) { - let lslot = l.itemMap.slot(of: bucket) - let rslot = r.itemMap.slot(of: bucket) - guard l[item: lslot].key != r[item: rslot].key else { return false } + for (bucket, _) in unsafe l.itemMap.intersection(r.itemMap) { + let lslot = unsafe l.itemMap.slot(of: bucket) + let rslot = unsafe r.itemMap.slot(of: bucket) + guard unsafe l[item: lslot].key != r[item: rslot].key else { return false } } - for (bucket, _) in l.itemMap.intersection(r.childMap) { - let lslot = l.itemMap.slot(of: bucket) - let hash = _Hash(l[item: lslot].key) - let rslot = r.childMap.slot(of: bucket) - let found = r[child: rslot].containsKey( + for (bucket, _) in unsafe l.itemMap.intersection(r.childMap) { + let lslot = unsafe l.itemMap.slot(of: bucket) + let hash = unsafe _Hash(l[item: lslot].key) + let rslot = unsafe r.childMap.slot(of: bucket) + let found = unsafe r[child: rslot].containsKey( level.descend(), l[item: lslot].key, hash) if found { return false } } - for (bucket, _) in l.childMap.intersection(r.itemMap) { - let lslot = l.childMap.slot(of: bucket) - let rslot = r.itemMap.slot(of: bucket) - let hash = _Hash(r[item: rslot].key) - let found = l[child: lslot].containsKey( + for (bucket, _) in unsafe l.childMap.intersection(r.itemMap) { + let lslot = unsafe l.childMap.slot(of: bucket) + let rslot = unsafe r.itemMap.slot(of: bucket) + let hash = unsafe _Hash(r[item: rslot].key) + let found = unsafe l[child: lslot].containsKey( level.descend(), r[item: rslot].key, hash) if found { return false } } - for (bucket, _) in l.childMap.intersection(r.childMap) { - let lslot = l.childMap.slot(of: bucket) - let rslot = r.childMap.slot(of: bucket) + for (bucket, _) in unsafe l.childMap.intersection(r.childMap) { + let lslot = unsafe l.childMap.slot(of: bucket) + let rslot = unsafe r.childMap.slot(of: bucket) guard - l[child: lslot].isDisjoint(level.descend(), with: r[child: rslot]) + unsafe l[child: lslot].isDisjoint(level.descend(), with: r[child: rslot]) else { return false } } return true @@ -79,13 +79,13 @@ extension _HashNode { ) -> Bool { assert(isCollisionNode) if other.isCollisionNode { - return read { l in - other.read { r in - guard l.collisionHash == r.collisionHash else { return true } - let litems = l.reverseItems - let ritems = r.reverseItems - return litems.allSatisfy { li in - !ritems.contains { ri in li.key == ri.key } + return unsafe read { l in + unsafe other.read { r in + guard unsafe l.collisionHash == r.collisionHash else { return true } + let litems = unsafe l.reverseItems + let ritems = unsafe r.reverseItems + return unsafe litems.allSatisfy { li in + unsafe !ritems.contains { ri in li.key == ri.key } } } } @@ -93,18 +93,18 @@ extension _HashNode { // `self` is on a compressed path. Try descending down by one level. assert(!level.isAtBottom) let bucket = self.collisionHash[level] - return other.read { r in - if r.childMap.contains(bucket) { - let slot = r.childMap.slot(of: bucket) - return isDisjoint(level.descend(), with: r[child: slot]) + return unsafe other.read { r in + if unsafe r.childMap.contains(bucket) { + let slot = unsafe r.childMap.slot(of: bucket) + return unsafe isDisjoint(level.descend(), with: r[child: slot]) } - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let p = r.itemPtr(at: rslot) - let hash = _Hash(p.pointee.key) - return read { l in - guard hash == l.collisionHash else { return true } - return !l.reverseItems.contains { $0.key == p.pointee.key } + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let p = unsafe r.itemPtr(at: rslot) + let hash = unsafe _Hash(p.pointee.key) + return unsafe read { l in + guard unsafe hash == l.collisionHash else { return true } + return unsafe !l.reverseItems.contains { unsafe $0.key == p.pointee.key } } } return true diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural isEqualSet.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isEqualSet.swift index 1b6099cd..9598e6b6 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural isEqualSet.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isEqualSet.swift @@ -24,15 +24,15 @@ extension _HashNode { if self.isCollisionNode { guard other.isCollisionNode else { return false } - return self.read { lhs in - other.read { rhs in - guard lhs.collisionHash == rhs.collisionHash else { return false } - let l = lhs.reverseItems - let r = rhs.reverseItems + return unsafe self.read { lhs in + unsafe other.read { rhs in + guard unsafe lhs.collisionHash == rhs.collisionHash else { return false } + let l = unsafe lhs.reverseItems + let r = unsafe rhs.reverseItems assert(l.count == r.count) // Already checked above for i in l.indices { - let found = r.contains { - l[i].key == $0.key && areEquivalent(l[i].value, $0.value) + let found = unsafe r.contains { + unsafe l[i].key == $0.key && areEquivalent(l[i].value, $0.value) } guard found else { return false } } @@ -42,19 +42,19 @@ extension _HashNode { } guard !other.isCollisionNode else { return false } - return self.read { l in - other.read { r in - guard l.itemMap == r.itemMap else { return false } - guard l.childMap == r.childMap else { return false } + return unsafe self.read { l in + unsafe other.read { r in + guard unsafe l.itemMap == r.itemMap else { return false } + guard unsafe l.childMap == r.childMap else { return false } - guard l.reverseItems.elementsEqual( + guard unsafe l.reverseItems.elementsEqual( r.reverseItems, by: { $0.key == $1.key && areEquivalent($0.value, $1.value) }) else { return false } - let lc = l.children - let rc = r.children - return lc.elementsEqual( + let lc = unsafe l.children + let rc = unsafe r.children + return unsafe lc.elementsEqual( rc, by: { $0.isEqualSet(to: $1, by: areEquivalent) }) } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural isSubset.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isSubset.swift index 1e1291cd..7d768cb6 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural isSubset.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural isSubset.swift @@ -26,12 +26,12 @@ extension _HashNode { if self.isCollisionNode { if other.isCollisionNode { guard self.collisionHash == other.collisionHash else { return false } - return read { l in - other.read { r in - let li = l.reverseItems - let ri = r.reverseItems - return l.reverseItems.indices.allSatisfy { i in - ri.contains { $0.key == li[i].key } + return unsafe read { l in + unsafe other.read { r in + let li = unsafe l.reverseItems + let ri = unsafe r.reverseItems + return unsafe l.reverseItems.indices.allSatisfy { i in + unsafe ri.contains { unsafe $0.key == li[i].key } } } } @@ -39,39 +39,39 @@ extension _HashNode { // `self` is on a compressed path. Try to descend down by one level. assert(!level.isAtBottom) let bucket = self.collisionHash[level] - return other.read { - guard $0.childMap.contains(bucket) else { return false } - let slot = $0.childMap.slot(of: bucket) - return self.isSubset(level.descend(), of: $0[child: slot]) + return unsafe other.read { + guard unsafe $0.childMap.contains(bucket) else { return false } + let slot = unsafe $0.childMap.slot(of: bucket) + return unsafe self.isSubset(level.descend(), of: $0[child: slot]) } } if other.isCollisionNode { - return read { l in - guard level.isAtRoot, l.hasSingletonItem else { return false } + return unsafe read { l in + guard level.isAtRoot, unsafe l.hasSingletonItem else { return false } // Annoying special case: the root node may contain a single item // that matches one in the collision node. - return other.read { r in - let hash = _Hash(l[item: .zero].key) - return r.find(level, l[item: .zero].key, hash) != nil + return unsafe other.read { r in + let hash = unsafe _Hash(l[item: .zero].key) + return unsafe r.find(level, l[item: .zero].key, hash) != nil } } } - return self.read { l in - other.read { r in - guard l.childMap.isSubset(of: r.childMap) else { return false } - guard l.itemMap.isSubset(of: r.itemMap.union(r.childMap)) else { + return unsafe self.read { l in + unsafe other.read { r in + guard unsafe l.childMap.isSubset(of: r.childMap) else { return false } + guard unsafe l.itemMap.isSubset(of: r.itemMap.union(r.childMap)) else { return false } - for (bucket, lslot) in l.itemMap { - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - guard l[item: lslot].key == r[item: rslot].key else { return false } + for (bucket, lslot) in unsafe l.itemMap { + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + guard unsafe l[item: lslot].key == r[item: rslot].key else { return false } } else { - let hash = _Hash(l[item: lslot].key) - let rslot = r.childMap.slot(of: bucket) + let hash = unsafe _Hash(l[item: lslot].key) + let rslot = unsafe r.childMap.slot(of: bucket) guard - r[child: rslot].containsKey( + unsafe r[child: rslot].containsKey( level.descend(), l[item: lslot].key, hash) @@ -79,9 +79,9 @@ extension _HashNode { } } - for (bucket, lslot) in l.childMap { - let rslot = r.childMap.slot(of: bucket) - guard l[child: lslot].isSubset(level.descend(), of: r[child: rslot]) + for (bucket, lslot) in unsafe l.childMap { + let rslot = unsafe r.childMap.slot(of: bucket) + guard unsafe l[child: lslot].isSubset(level.descend(), of: r[child: rslot]) else { return false } } return true diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural mapValues.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural mapValues.swift index 53dd46e3..8f664193 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural mapValues.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural mapValues.swift @@ -21,28 +21,28 @@ extension _HashNode { _ transform: (Element) throws -> T ) rethrows -> _HashNode { let c = self.count - return try read { source in + return unsafe try read { source in var result: _HashNode if isCollisionNode { - result = _HashNode.allocateCollision( + result = unsafe _HashNode.allocateCollision( count: c, source.collisionHash, initializingWith: { _ in } ).node } else { - result = _HashNode.allocate( + result = unsafe _HashNode.allocate( itemMap: source.itemMap, childMap: source.childMap, count: c, initializingWith: { _, _ in } ).node } - try result.update { target in - let sourceItems = source.reverseItems - let targetItems = target.reverseItems + unsafe try result.update { target in + let sourceItems = unsafe source.reverseItems + let targetItems = unsafe target.reverseItems assert(sourceItems.count == targetItems.count) - let sourceChildren = source.children - let targetChildren = target.children + let sourceChildren = unsafe source.children + let targetChildren = unsafe target.children assert(sourceChildren.count == targetChildren.count) var i = 0 @@ -52,21 +52,21 @@ extension _HashNode { defer { if !success { - targetItems.prefix(i).deinitialize() - targetChildren.prefix(j).deinitialize() - target.clear() + unsafe targetItems.prefix(i).deinitialize() + unsafe targetChildren.prefix(j).deinitialize() + unsafe target.clear() } } while i < targetItems.count { - let key = sourceItems[i].key - let value = try transform(sourceItems[i]) - targetItems.initializeElement(at: i, to: (key, value)) + let key = unsafe sourceItems[i].key + let value = unsafe try transform(sourceItems[i]) + unsafe targetItems.initializeElement(at: i, to: (key, value)) i += 1 } while j < targetChildren.count { - let child = try sourceChildren[j].mapValues(transform) - targetChildren.initializeElement(at: j, to: child) + let child = unsafe try sourceChildren[j].mapValues(transform) + unsafe targetChildren.initializeElement(at: j, to: child) j += 1 } success = true @@ -81,7 +81,7 @@ extension _HashNode { copy: Bool = false, extraBytes: Int = 0 ) -> _HashNode { if Value.self == Void.self { - let node = unsafeBitCast(self, to: _HashNode.self) + let node = unsafe unsafeBitCast(self, to: _HashNode.self) guard copy || !node.hasFreeSpace(extraBytes) else { return node } return node.copy(withFreeSpace: extraBytes) } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural merge.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural merge.swift index c0e2c37f..1211a23f 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural merge.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural merge.swift @@ -29,21 +29,21 @@ extension _HashNode { // during the merge process. Prevent this from causing issues below by // handling it up front. var copy = other - let delta = try self.read { l in - let lp = l.itemPtr(at: .zero) + let delta = unsafe try self.read { l in + let lp = unsafe l.itemPtr(at: .zero) let c = copy.count - let res = copy.updateValue( + let res = unsafe copy.updateValue( level, forKey: lp.pointee.key, _Hash(lp.pointee.key) ) { - $0.initialize(to: lp.pointee) + unsafe $0.initialize(to: lp.pointee) } - if !res.inserted { - try UnsafeHandle.update(res.leaf) { - let p = $0.itemPtr(at: res.slot) - p.pointee.value = try combine(lp.pointee.value, p.pointee.value) + if unsafe !res.inserted { + unsafe try UnsafeHandle.update(res.leaf) { + let p = unsafe $0.itemPtr(at: res.slot) + unsafe p.pointee.value = try combine(lp.pointee.value, p.pointee.value) } } - return c - (res.inserted ? 0 : 1) + return unsafe c - (res.inserted ? 0 : 1) } self = copy return delta @@ -65,35 +65,35 @@ extension _HashNode { return try _merge_slow(level, other, combine) } - return try other.read { r in + return unsafe try other.read { r in var isUnique = self.isUnique() var delta = 0 - let (originalItems, originalChildren) = self.read { - ($0.itemMap, $0.childMap) + let (originalItems, originalChildren) = unsafe self.read { + unsafe ($0.itemMap, $0.childMap) } for (bucket, _) in originalItems { assert(!isCollisionNode) - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) - let lslot = self.read { $0.itemMap.slot(of: bucket) } - let conflict = self.read { $0[item: lslot].key == rp.pointee.key } + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let rp = unsafe r.itemPtr(at: rslot) + let lslot = unsafe self.read { unsafe $0.itemMap.slot(of: bucket) } + let conflict = unsafe self.read { unsafe $0[item: lslot].key == rp.pointee.key } if conflict { self.ensureUnique(isUnique: isUnique) - try self.update { - let p = $0.itemPtr(at: lslot) - p.pointee.value = try combine(p.pointee.value, rp.pointee.value) + unsafe try self.update { + let p = unsafe $0.itemPtr(at: lslot) + unsafe p.pointee.value = try combine(p.pointee.value, rp.pointee.value) } } else { - _ = self.ensureUniqueAndSpawnChild( + _ = unsafe self.ensureUniqueAndSpawnChild( isUnique: isUnique, level: level, replacing: bucket, itemSlot: lslot, newHash: _Hash(rp.pointee.key), - { $0.initialize(to: rp.pointee) }) + { unsafe $0.initialize(to: rp.pointee) }) // If we hadn't handled the singleton root node case above, // then this call would sometimes turn `self` into a collision // node on a compressed path, causing mischief. @@ -102,27 +102,27 @@ extension _HashNode { } isUnique = true } - else if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - let rp = r.childPtr(at: rslot) + else if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + let rp = unsafe r.childPtr(at: rslot) self.ensureUnique( isUnique: isUnique, withFreeSpace: _HashNode.spaceForSpawningChild) - let item = self.removeItem(at: bucket) + let item = unsafe self.removeItem(at: bucket) delta &-= 1 - var child = rp.pointee - let r = child.updateValue( + var child = unsafe rp.pointee + let r = unsafe child.updateValue( level.descend(), forKey: item.key, _Hash(item.key) ) { - $0.initialize(to: item) + unsafe $0.initialize(to: item) } - if !r.inserted { - try UnsafeHandle.update(r.leaf) { - let p = $0.itemPtr(at: r.slot) - p.pointee.value = try combine(item.value, p.pointee.value) + if unsafe !r.inserted { + try unsafe UnsafeHandle.update(r.leaf) { + let p = unsafe $0.itemPtr(at: r.slot) + unsafe p.pointee.value = try combine(item.value, p.pointee.value) } } - self.insertChild(child, bucket) + unsafe self.insertChild(child, bucket) isUnique = true delta &+= child.count } @@ -130,36 +130,36 @@ extension _HashNode { for (bucket, _) in originalChildren { assert(!isCollisionNode) - let lslot = self.read { $0.childMap.slot(of: bucket) } + let lslot = unsafe self.read { unsafe $0.childMap.slot(of: bucket) } - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let rp = unsafe r.itemPtr(at: rslot) self.ensureUnique(isUnique: isUnique) - let h = _Hash(rp.pointee.key) - let res = self.update { l in - l[child: lslot].updateValue( + let h = unsafe _Hash(rp.pointee.key) + let res = unsafe self.update { l in + unsafe l[child: lslot].updateValue( level.descend(), forKey: rp.pointee.key, h ) { - $0.initialize(to: rp.pointee) + unsafe $0.initialize(to: rp.pointee) } } - if res.inserted { + if unsafe res.inserted { self.count &+= 1 delta &+= 1 } else { - try UnsafeHandle.update(res.leaf) { - let p = $0.itemPtr(at: res.slot) - p.pointee.value = try combine(p.pointee.value, rp.pointee.value) + unsafe try UnsafeHandle.update(res.leaf) { + let p = unsafe $0.itemPtr(at: res.slot) + unsafe p.pointee.value = try combine(p.pointee.value, rp.pointee.value) } } isUnique = true } - else if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) + else if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) self.ensureUnique(isUnique: isUnique) - let d = try self.update { l in - try l[child: lslot].merge( + let d = unsafe try self.update { l in + unsafe try l[child: lslot].merge( level.descend(), r[child: rslot], combine) @@ -173,20 +173,20 @@ extension _HashNode { assert(!self.isCollisionNode) /// Add buckets in `other` that we haven't processed above. - let seen = self.read { l in l.itemMap.union(l.childMap) } - for (bucket, _) in r.itemMap.subtracting(seen) { - let rslot = r.itemMap.slot(of: bucket) - self.ensureUniqueAndInsertItem( + let seen = unsafe self.read { l in unsafe l.itemMap.union(l.childMap) } + for (bucket, _) in unsafe r.itemMap.subtracting(seen) { + let rslot = unsafe r.itemMap.slot(of: bucket) + unsafe self.ensureUniqueAndInsertItem( isUnique: isUnique, r[item: rslot], at: bucket) delta &+= 1 isUnique = true } - for (bucket, _) in r.childMap.subtracting(seen) { - let rslot = r.childMap.slot(of: bucket) + for (bucket, _) in unsafe r.childMap.subtracting(seen) { + let rslot = unsafe r.childMap.slot(of: bucket) self.ensureUnique( isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild) - self.insertChild(r[child: rslot], bucket) - delta &+= r[child: rslot].count + unsafe self.insertChild(r[child: rslot], bucket) + unsafe delta &+= r[child: rslot].count isUnique = true } @@ -211,27 +211,27 @@ extension _HashNode { child2: other, other.collisionHash) return other.count } - return try other.read { r in + return unsafe try other.read { r in var isUnique = self.isUnique() var delta = 0 let originalItemCount = self.count - for rs: _HashSlot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { - let rp = r.itemPtr(at: rs) - let lslot: _HashSlot? = self.read { l in - let litems = l.reverseItems - return litems + for rs: _HashSlot in stride(from: .zero, to: unsafe r.itemsEndSlot, by: 1) { + let rp = unsafe r.itemPtr(at: rs) + let lslot: _HashSlot? = unsafe self.read { l in + let litems = unsafe l.reverseItems + return unsafe litems .suffix(originalItemCount) - .firstIndex { $0.key == rp.pointee.key } + .firstIndex { unsafe $0.key == rp.pointee.key } .map { _HashSlot(litems.count &- 1 &- $0) } } if let lslot = lslot { self.ensureUnique(isUnique: isUnique) - try self.update { - let p = $0.itemPtr(at: lslot) - p.pointee.value = try combine(p.pointee.value, rp.pointee.value) + unsafe try self.update { + let p = unsafe $0.itemPtr(at: lslot) + unsafe p.pointee.value = try combine(p.pointee.value, rp.pointee.value) } } else { - _ = self.ensureUniqueAndAppendCollision( + _ = unsafe self.ensureUniqueAndAppendCollision( isUnique: isUnique, rp.pointee) delta &+= 1 } @@ -247,41 +247,41 @@ extension _HashNode { if lc { // `self` is a collision node on a compressed path. The other tree might // have the same set of collisions, just expanded a bit deeper. - return try other.read { r in + return unsafe try other.read { r in let bucket = self.collisionHash[level] - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let rp = unsafe r.itemPtr(at: rslot) - let h = _Hash(rp.pointee.key) - let res = self.updateValue( + let h = unsafe _Hash(rp.pointee.key) + let res = unsafe self.updateValue( level.descend(), forKey: rp.pointee.key, h ) { - $0.initialize(to: rp.pointee) + unsafe $0.initialize(to: rp.pointee) } - if !res.inserted { - try UnsafeHandle.update(res.leaf) { - let p = $0.itemPtr(at: res.slot) - p.pointee.value = try combine(p.pointee.value, rp.pointee.value) + if unsafe !res.inserted { + unsafe try UnsafeHandle.update(res.leaf) { + let p = unsafe $0.itemPtr(at: res.slot) + unsafe p.pointee.value = try combine(p.pointee.value, rp.pointee.value) } } - self = other._copyNodeAndReplaceItemWithNewChild( + self = unsafe other._copyNodeAndReplaceItemWithNewChild( level: level, self, at: bucket, itemSlot: rslot) - return other.count - (res.inserted ? 0 : 1) + return unsafe other.count - (res.inserted ? 0 : 1) } - if r.childMap.contains(bucket) { + if unsafe r.childMap.contains(bucket) { let originalCount = self.count - let rslot = r.childMap.slot(of: bucket) - _ = try self._merge(level.descend(), r[child: rslot], combine) + let rslot = unsafe r.childMap.slot(of: bucket) + _ = unsafe try self._merge(level.descend(), r[child: rslot], combine) var node = other.copy() - _ = node.replaceChild(at: bucket, rslot, with: self) + _ = unsafe node.replaceChild(at: bucket, rslot, with: self) self = node return self.count - originalCount } var node = other.copy(withFreeSpace: _HashNode.spaceForNewChild) - node.insertChild(self, bucket) + unsafe node.insertChild(self, bucket) self = node return other.count } @@ -290,33 +290,33 @@ extension _HashNode { assert(rc) let isUnique = self.isUnique() // `other` is a collision node on a compressed path. - return try other.read { r in - let bucket = r.collisionHash[level] - if self.read({ $0.itemMap.contains(bucket) }) { + return unsafe try other.read { r in + let bucket = unsafe r.collisionHash[level] + if unsafe self.read({ unsafe $0.itemMap.contains(bucket) }) { self.ensureUnique( isUnique: isUnique, withFreeSpace: _HashNode.spaceForSpawningChild) - let item = self.removeItem(at: bucket) + let item = unsafe self.removeItem(at: bucket) let h = _Hash(item.key) var copy = other - let res = copy.updateValue(level.descend(), forKey: item.key, h) { - $0.initialize(to: item) + let res = unsafe copy.updateValue(level.descend(), forKey: item.key, h) { + unsafe $0.initialize(to: item) } - if !res.inserted { - try UnsafeHandle.update(res.leaf) { - let p = $0.itemPtr(at: res.slot) - p.pointee.value = try combine(item.value, p.pointee.value) + if unsafe !res.inserted { + unsafe try UnsafeHandle.update(res.leaf) { + let p = unsafe $0.itemPtr(at: res.slot) + unsafe p.pointee.value = try combine(item.value, p.pointee.value) } } assert(self.count > 0) // Singleton case handled up front above - self.insertChild(copy, bucket) - return other.count - (res.inserted ? 0 : 1) + unsafe self.insertChild(copy, bucket) + return unsafe other.count - (res.inserted ? 0 : 1) } - if self.read({ $0.childMap.contains(bucket) }) { + if unsafe self.read({ unsafe $0.childMap.contains(bucket) }) { self.ensureUnique(isUnique: isUnique) - let delta: Int = try self.update { l in - let lslot = l.childMap.slot(of: bucket) - let lchild = l.childPtr(at: lslot) - return try lchild.pointee._merge(level.descend(), other, combine) + let delta: Int = unsafe try self.update { l in + let lslot = unsafe l.childMap.slot(of: bucket) + let lchild = unsafe l.childPtr(at: lslot) + return unsafe try lchild.pointee._merge(level.descend(), other, combine) } assert(delta >= 0) self.count &+= delta @@ -324,7 +324,7 @@ extension _HashNode { } self.ensureUnique( isUnique: isUnique, withFreeSpace: _HashNode.spaceForNewChild) - self.insertChild(other, bucket) + unsafe self.insertChild(other, bucket) return other.count } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural subtracting.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural subtracting.swift index b18b47a2..558f526f 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural subtracting.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural subtracting.swift @@ -36,22 +36,22 @@ extension _HashNode { return _subtracting_slow(level, other) } - return self.read { l in - other.read { r in + return unsafe self.read { l in + unsafe other.read { r in var result: Builder = .empty(level) var removing = false - for (bucket, lslot) in l.itemMap { - let lp = l.itemPtr(at: lslot) + for (bucket, lslot) in unsafe l.itemMap { + let lp = unsafe l.itemPtr(at: lslot) let include: Bool - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - include = (lp.pointee.key != r[item: rslot].key) + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + include = unsafe (lp.pointee.key != r[item: rslot].key) } - else if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - let h = _Hash(lp.pointee.key) - include = !r[child: rslot] + else if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + let h = unsafe _Hash(lp.pointee.key) + include = unsafe !r[child: rslot] .containsKey(level.descend(), lp.pointee.key, h) } else { @@ -59,48 +59,48 @@ extension _HashNode { } if include, removing { - result.addNewItem(level, lp.pointee, at: bucket) + unsafe result.addNewItem(level, lp.pointee, at: bucket) } else if !include, !removing { removing = true - result.copyItems(level, from: l, upTo: bucket) + unsafe result.copyItems(level, from: l, upTo: bucket) } } - for (bucket, lslot) in l.childMap { + for (bucket, lslot) in unsafe l.childMap { var done = false - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) - let h = _Hash(rp.pointee.key) - let child = l[child: lslot] + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let rp = unsafe r.itemPtr(at: rslot) + let h = unsafe _Hash(rp.pointee.key) + let child = unsafe l[child: lslot] .removing(level.descend(), rp.pointee.key, h)?.replacement if let child = child { assert(child.count < self.count) if !removing { removing = true - result.copyItemsAndChildren(level, from: l, upTo: bucket) + unsafe result.copyItemsAndChildren(level, from: l, upTo: bucket) } - result.addNewChildBranch(level, child, at: bucket) + unsafe result.addNewChildBranch(level, child, at: bucket) done = true } } - else if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - let child = l[child: lslot] + else if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + let child = unsafe l[child: lslot] ._subtracting(level.descend(), r[child: rslot]) if let child = child { assert(child.count < self.count) if !removing { removing = true - result.copyItemsAndChildren(level, from: l, upTo: bucket) + unsafe result.copyItemsAndChildren(level, from: l, upTo: bucket) } - result.addNewChildBranch(level, child, at: bucket) + unsafe result.addNewChildBranch(level, child, at: bucket) done = true } } if !done, removing { - result.addNewChildNode(level, l[child: lslot], at: bucket) + unsafe result.addNewChildNode(level, l[child: lslot], at: bucket) } } guard removing else { return nil } @@ -117,24 +117,24 @@ extension _HashNode { let lc = self.isCollisionNode let rc = other.isCollisionNode if lc && rc { - return read { l in - other.read { r in - guard l.collisionHash == r.collisionHash else { + return unsafe read { l in + unsafe other.read { r in + guard unsafe l.collisionHash == r.collisionHash else { return nil } var result: Builder = .empty(level) var removing = false - let ritems = r.reverseItems - for lslot: _HashSlot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { - let lp = l.itemPtr(at: lslot) - let include = !ritems.contains { $0.key == lp.pointee.key } + let ritems = unsafe r.reverseItems + for lslot: _HashSlot in stride(from: .zero, to: unsafe l.itemsEndSlot, by: 1) { + let lp = unsafe l.itemPtr(at: lslot) + let include = unsafe !ritems.contains { unsafe $0.key == lp.pointee.key } if include, removing { - result.addNewCollision(level, lp.pointee, l.collisionHash) + unsafe result.addNewCollision(level, lp.pointee, l.collisionHash) } else if !include, !removing { removing = true - result.copyCollisions(from: l, upTo: lslot) + unsafe result.copyCollisions(from: l, upTo: lslot) } } guard removing else { return nil } @@ -150,22 +150,22 @@ extension _HashNode { if lc { // `self` is a collision node on a compressed path. The other tree might // have the same set of collisions, just expanded a bit deeper. - return read { l in - other.read { r in - let bucket = l.collisionHash[level] - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let ritem = r.itemPtr(at: rslot) - let h = _Hash(ritem.pointee.key) - let res = l.find(level, ritem.pointee.key, h) + return unsafe read { l in + unsafe other.read { r in + let bucket = unsafe l.collisionHash[level] + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let ritem = unsafe r.itemPtr(at: rslot) + let h = unsafe _Hash(ritem.pointee.key) + let res = unsafe l.find(level, ritem.pointee.key, h) guard let res = res else { return nil } - return self._removingItemFromLeaf(level, at: bucket, res.slot) + return unsafe self._removingItemFromLeaf(level, at: bucket, res.slot) .replacement } - else if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - return _subtracting(level.descend(), r[child: rslot]) - .map { .childBranch(level, $0, at: bucket) } + else if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + return unsafe _subtracting(level.descend(), r[child: rslot]) + .map { unsafe .childBranch(level, $0, at: bucket) } } return nil } @@ -174,24 +174,24 @@ extension _HashNode { assert(rc) // `other` is a collision node on a compressed path. - return read { l in - other.read { r in - let bucket = r.collisionHash[level] - if l.itemMap.contains(bucket) { - let lslot = l.itemMap.slot(of: bucket) - let litem = l.itemPtr(at: lslot) - let h = _Hash(litem.pointee.key) - let res = r.find(level, litem.pointee.key, h) + return unsafe read { l in + unsafe other.read { r in + let bucket = unsafe r.collisionHash[level] + if unsafe l.itemMap.contains(bucket) { + let lslot = unsafe l.itemMap.slot(of: bucket) + let litem = unsafe l.itemPtr(at: lslot) + let h = unsafe _Hash(litem.pointee.key) + let res = unsafe r.find(level, litem.pointee.key, h) if res == nil { return nil } - return self._removingItemFromLeaf(level, at: bucket, lslot) + return unsafe self._removingItemFromLeaf(level, at: bucket, lslot) .replacement } - if l.childMap.contains(bucket) { - let lslot = l.childMap.slot(of: bucket) - let branch = l[child: lslot]._subtracting(level.descend(), other) + if unsafe l.childMap.contains(bucket) { + let lslot = unsafe l.childMap.slot(of: bucket) + let branch = unsafe l[child: lslot]._subtracting(level.descend(), other) guard let branch = branch else { return nil } - var result = self._removingChild(level, at: bucket, lslot) - result.addNewChildBranch(level, branch, at: bucket) + var result = unsafe self._removingChild(level, at: bucket, lslot) + unsafe result.addNewChildBranch(level, branch, at: bucket) return result } return nil diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural symmetricDifference.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural symmetricDifference.swift index 8e4626bf..72ed498c 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural symmetricDifference.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural symmetricDifference.swift @@ -40,89 +40,89 @@ extension _HashNode { return _symmetricDifference_slow(level, other) } - return self.read { l in - other.read { r in + return unsafe self.read { l in + unsafe other.read { r in var result: VoidNode.Builder = .empty(level) - for (bucket, lslot) in l.itemMap { - let lp = l.itemPtr(at: lslot) - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) - if lp.pointee.key != rp.pointee.key { - let h1 = _Hash(lp.pointee.key) - let h2 = _Hash(rp.pointee.key) - let child = VoidNode.build( + for (bucket, lslot) in unsafe l.itemMap { + let lp = unsafe l.itemPtr(at: lslot) + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let rp = unsafe r.itemPtr(at: rslot) + if unsafe lp.pointee.key != rp.pointee.key { + let h1 = unsafe _Hash(lp.pointee.key) + let h2 = unsafe _Hash(rp.pointee.key) + let child = unsafe VoidNode.build( level: level.descend(), item1: (lp.pointee.key, ()), h1, - item2: { $0.initialize(to: (rp.pointee.key, ())) }, h2) - result.addNewChildNode(level, child.top, at: bucket) + item2: { unsafe $0.initialize(to: (rp.pointee.key, ())) }, h2) + unsafe result.addNewChildNode(level, child.top, at: bucket) } } - else if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - let rp = r.childPtr(at: rslot) - let h = _Hash(lp.pointee.key) - let child = rp.pointee + else if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + let rp = unsafe r.childPtr(at: rslot) + let h = unsafe _Hash(lp.pointee.key) + let child = unsafe rp.pointee .removing(level.descend(), lp.pointee.key, h)?.replacement if let child = child { let child = child.mapValuesToVoid() - result.addNewChildBranch(level, child, at: bucket) + unsafe result.addNewChildBranch(level, child, at: bucket) } else { - var child2 = rp.pointee + var child2 = unsafe rp.pointee .mapValuesToVoid( copy: true, extraBytes: VoidNode.spaceForNewItem) - let r = child2.insert(level.descend(), (lp.pointee.key, ()), h) - assert(r.inserted) - result.addNewChildNode(level, child2, at: bucket) + let r = unsafe child2.insert(level.descend(), (lp.pointee.key, ()), h) + assert(unsafe r.inserted) + unsafe result.addNewChildNode(level, child2, at: bucket) } } else { - result.addNewItem(level, (lp.pointee.key, ()), at: bucket) + unsafe result.addNewItem(level, (lp.pointee.key, ()), at: bucket) } } - for (bucket, lslot) in l.childMap { - let lp = l.childPtr(at: lslot) - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) - let h = _Hash(rp.pointee.key) - let child = lp.pointee + for (bucket, lslot) in unsafe l.childMap { + let lp = unsafe l.childPtr(at: lslot) + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let rp = unsafe r.itemPtr(at: rslot) + let h = unsafe _Hash(rp.pointee.key) + let child = unsafe lp.pointee .mapValuesToVoid() .removing(level.descend(), rp.pointee.key, h)?.replacement if let child = child { - result.addNewChildBranch(level, child, at: bucket) + unsafe result.addNewChildBranch(level, child, at: bucket) } else { - var child2 = lp.pointee.mapValuesToVoid( + var child2 = unsafe lp.pointee.mapValuesToVoid( copy: true, extraBytes: VoidNode.spaceForNewItem) - let r2 = child2.insert(level.descend(), (rp.pointee.key, ()), h) - assert(r2.inserted) - result.addNewChildNode(level, child2, at: bucket) + let r2 = unsafe child2.insert(level.descend(), (rp.pointee.key, ()), h) + assert(unsafe r2.inserted) + unsafe result.addNewChildNode(level, child2, at: bucket) } } - else if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - let b = l[child: lslot]._symmetricDifference( + else if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + let b = unsafe l[child: lslot]._symmetricDifference( level.descend(), r[child: rslot]) - result.addNewChildBranch(level, b, at: bucket) + unsafe result.addNewChildBranch(level, b, at: bucket) } else { - result.addNewChildNode( + unsafe result.addNewChildNode( level, lp.pointee.mapValuesToVoid(), at: bucket) } } - let seen = l.itemMap.union(l.childMap) - for (bucket, rslot) in r.itemMap { + let seen = unsafe l.itemMap.union(l.childMap) + for (bucket, rslot) in unsafe r.itemMap { guard !seen.contains(bucket) else { continue } - result.addNewItem(level, (r[item: rslot].key, ()), at: bucket) + unsafe result.addNewItem(level, (r[item: rslot].key, ()), at: bucket) } - for (bucket, rslot) in r.childMap { + for (bucket, rslot) in unsafe r.childMap { guard !seen.contains(bucket) else { continue } - result.addNewChildNode( + unsafe result.addNewChildNode( level, r[child: rslot].mapValuesToVoid(), at: bucket) } return result @@ -151,32 +151,32 @@ extension _HashNode { _ other: _HashNode ) -> _HashNode.Builder { typealias VoidNode = _HashNode - return read { l in - other.read { r in - guard l.collisionHash == r.collisionHash else { - let node = VoidNode.build( + return unsafe read { l in + unsafe other.read { r in + guard unsafe l.collisionHash == r.collisionHash else { + let node = unsafe VoidNode.build( level: level, child1: self.mapValuesToVoid(), l.collisionHash, child2: other.mapValuesToVoid(), r.collisionHash) return .node(level, node) } var result: VoidNode.Builder = .empty(level) - let ritems = r.reverseItems - for ls: _HashSlot in stride(from: .zero, to: l.itemsEndSlot, by: 1) { - let lp = l.itemPtr(at: ls) - let include = !ritems.contains(where: { $0.key == lp.pointee.key }) + let ritems = unsafe r.reverseItems + for ls: _HashSlot in stride(from: .zero, to: unsafe l.itemsEndSlot, by: 1) { + let lp = unsafe l.itemPtr(at: ls) + let include = unsafe !ritems.contains(where: { unsafe $0.key == lp.pointee.key }) if include { - result.addNewCollision(level, (lp.pointee.key, ()), l.collisionHash) + unsafe result.addNewCollision(level, (lp.pointee.key, ()), l.collisionHash) } } // FIXME: Consider remembering slots of shared items in r by // caching them in a bitset. - let litems = l.reverseItems - for rs: _HashSlot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { - let rp = r.itemPtr(at: rs) - let include = !litems.contains(where: { $0.key == rp.pointee.key }) + let litems = unsafe l.reverseItems + for rs: _HashSlot in stride(from: .zero, to: unsafe r.itemsEndSlot, by: 1) { + let rp = unsafe r.itemPtr(at: rs) + let include = unsafe !litems.contains(where: { unsafe $0.key == rp.pointee.key }) if include { - result.addNewCollision(level, (rp.pointee.key, ()), r.collisionHash) + unsafe result.addNewCollision(level, (rp.pointee.key, ()), r.collisionHash) } } return result @@ -192,77 +192,77 @@ extension _HashNode { typealias VoidNode = _HashNode // `self` is a collision node on a compressed path. The other tree might // have the same set of collisions, just expanded a bit deeper. - return read { l in - other.read { r in - assert(l.isCollisionNode && !r.isCollisionNode) - let bucket = l.collisionHash[level] - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) - let rh = _Hash(rp.pointee.key) - guard rh == l.collisionHash else { + return unsafe read { l in + unsafe other.read { r in + assert(unsafe l.isCollisionNode && !r.isCollisionNode) + let bucket = unsafe l.collisionHash[level] + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let rp = unsafe r.itemPtr(at: rslot) + let rh = unsafe _Hash(rp.pointee.key) + guard unsafe rh == l.collisionHash else { var copy = other.mapValuesToVoid( copy: true, extraBytes: VoidNode.spaceForSpawningChild) - let item = copy.removeItem(at: bucket, rslot) - let child = VoidNode.build( + let item = unsafe copy.removeItem(at: bucket, rslot) + let child = unsafe VoidNode.build( level: level.descend(), - item1: { $0.initialize(to: (item.key, ())) }, rh, + item1: { unsafe $0.initialize(to: (item.key, ())) }, rh, child2: self.mapValuesToVoid(), l.collisionHash) - copy.insertChild(child.top, bucket) + unsafe copy.insertChild(child.top, bucket) return .node(level, copy) } - let litems = l.reverseItems - if let li = litems.firstIndex(where: { $0.key == rp.pointee.key }) { - if l.itemCount == 2 { + let litems = unsafe l.reverseItems + if let li = unsafe litems.firstIndex(where: { unsafe $0.key == rp.pointee.key }) { + if unsafe l.itemCount == 2 { var node = other.mapValuesToVoid(copy: true) - node.replaceItem( + unsafe node.replaceItem( at: bucket, rslot, with: (litems[1 &- li].key, ())) return .node(level, node) } let lslot = _HashSlot(litems.count &- 1 &- li) var child = self.mapValuesToVoid(copy: true) - _ = child.removeItem(at: .invalid, lslot) + _ = unsafe child.removeItem(at: .invalid, lslot) if other.hasSingletonItem { // Compression return .collisionNode(level, child) } var node = other.mapValuesToVoid( copy: true, extraBytes: VoidNode.spaceForSpawningChild) - _ = node.removeItem(at: bucket, rslot) - node.insertChild(child, bucket) + _ = unsafe node.removeItem(at: bucket, rslot) + unsafe node.insertChild(child, bucket) return .node(level, node) } if other.hasSingletonItem { // Compression var copy = self.mapValuesToVoid( copy: true, extraBytes: VoidNode.spaceForNewItem) - _ = copy.ensureUniqueAndAppendCollision( + _ = unsafe copy.ensureUniqueAndAppendCollision( isUnique: true, (r[item: .zero].key, ())) return .collisionNode(level, copy) } var node = other.mapValuesToVoid( copy: true, extraBytes: VoidNode.spaceForSpawningChild) - let item = node.removeItem(at: bucket, rslot) + let item = unsafe node.removeItem(at: bucket, rslot) var child = self.mapValuesToVoid( copy: true, extraBytes: VoidNode.spaceForNewItem) - _ = child.ensureUniqueAndAppendCollision( + _ = unsafe child.ensureUniqueAndAppendCollision( isUnique: true, (item.key, ())) - node.insertChild(child, bucket) + unsafe node.insertChild(child, bucket) return .node(level, node) } - if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - let rp = r.childPtr(at: rslot) - let child = rp.pointee._symmetricDifference(level.descend(), self) - return other + if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + let rp = unsafe r.childPtr(at: rslot) + let child = unsafe rp.pointee._symmetricDifference(level.descend(), self) + return unsafe other .mapValuesToVoid() .replacingChild(level, at: bucket, rslot, with: child) } var node = other .mapValuesToVoid(copy: true, extraBytes: VoidNode.spaceForNewChild) - node.insertChild(self.mapValuesToVoid(), bucket) + unsafe node.insertChild(self.mapValuesToVoid(), bucket) return .node(level, node) } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Structural union.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Structural union.swift index 5166610e..9635d46b 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Structural union.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Structural union.swift @@ -23,17 +23,17 @@ extension _HashNode { // In this special case, the root node may turn into a collision node // during the merge process. Prevent this from causing issues below by // handling it up front. - return self.read { l in - let lp = l.itemPtr(at: .zero) + return unsafe self.read { l in + let lp = unsafe l.itemPtr(at: .zero) var copy = other.mapValuesToVoid(copy: true) - let r = copy.updateValue( + let r = unsafe copy.updateValue( level, forKey: lp.pointee.key, _Hash(lp.pointee.key) ) { - $0.initialize(to: (lp.pointee.key, ())) + unsafe $0.initialize(to: (lp.pointee.key, ())) } - if !r.inserted { - UnsafeHandle.update(r.leaf) { - $0[item: r.slot] = lp.pointee + if unsafe !r.inserted { + unsafe UnsafeHandle.update(r.leaf) { + unsafe $0[item: r.slot] = lp.pointee } } return (true, copy) @@ -55,29 +55,29 @@ extension _HashNode { return _union_slow(level, other) } - return self.read { l in - other.read { r in + return unsafe self.read { l in + unsafe other.read { r in var node = self.mapValuesToVoid() var copied = false - for (bucket, lslot) in l.itemMap { + for (bucket, lslot) in unsafe l.itemMap { assert(!node.isCollisionNode) - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let lp = l.itemPtr(at: lslot) - let rp = r.itemPtr(at: rslot) - if lp.pointee.key != rp.pointee.key { + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let lp = unsafe l.itemPtr(at: lslot) + let rp = unsafe r.itemPtr(at: rslot) + if unsafe lp.pointee.key != rp.pointee.key { let slot = ( copied - ? node.read { $0.itemMap.slot(of: bucket) } + ? unsafe node.read { unsafe $0.itemMap.slot(of: bucket) } : lslot) - _ = node.ensureUniqueAndSpawnChild( + _ = unsafe node.ensureUniqueAndSpawnChild( isUnique: copied, level: level, replacing: bucket, itemSlot: slot, newHash: _Hash(rp.pointee.key), - { $0.initialize(to: (rp.pointee.key, ())) }) + { unsafe $0.initialize(to: (rp.pointee.key, ())) }) // If we hadn't handled the singleton root node case above, // then this call would sometimes turn `node` into a collision // node on a compressed path, causing mischief. @@ -85,46 +85,46 @@ extension _HashNode { copied = true } } - else if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - let rp = r.childPtr(at: rslot) + else if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + let rp = unsafe r.childPtr(at: rslot) node.ensureUnique( isUnique: copied, withFreeSpace: _HashNode.spaceForSpawningChild) - let item = node.removeItem(at: bucket) - let r = rp.pointee.mapValuesToVoid() + let item = unsafe node.removeItem(at: bucket) + let r = unsafe rp.pointee.mapValuesToVoid() .inserting(level.descend(), (item.key, ()), _Hash(item.key)) - node.insertChild(r.node, bucket) + unsafe node.insertChild(r.node, bucket) copied = true } } - for (bucket, lslot) in l.childMap { + for (bucket, lslot) in unsafe l.childMap { assert(!node.isCollisionNode) - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) - let h = _Hash(rp.pointee.key) - let r = l[child: lslot].mapValuesToVoid() + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let rp = unsafe r.itemPtr(at: rslot) + let h = unsafe _Hash(rp.pointee.key) + let r = unsafe l[child: lslot].mapValuesToVoid() .inserting(level.descend(), (rp.pointee.key, ()), h) - guard r.inserted else { + guard unsafe r.inserted else { // Nothing to do continue } node.ensureUnique(isUnique: copied) - let delta = node.replaceChild(at: bucket, with: r.node) + let delta = unsafe node.replaceChild(at: bucket, with: r.node) assert(delta == 1) copied = true } - else if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - let child = l[child: lslot]._union(level.descend(), r[child: rslot]) + else if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + let child = unsafe l[child: lslot]._union(level.descend(), r[child: rslot]) guard child.copied else { // Nothing to do continue } node.ensureUnique(isUnique: copied) - let delta = node.replaceChild(at: bucket, with: child.node) + let delta = unsafe node.replaceChild(at: bucket, with: child.node) assert(delta > 0) // If we didn't add an item, why did we copy? copied = true } @@ -133,20 +133,20 @@ extension _HashNode { assert(!node.isCollisionNode) /// Add buckets in `other` that we haven't processed above. - let seen = l.itemMap.union(l.childMap) + let seen = unsafe l.itemMap.union(l.childMap) - for (bucket, _) in r.itemMap.subtracting(seen) { - let rslot = r.itemMap.slot(of: bucket) - node.ensureUniqueAndInsertItem( + for (bucket, _) in unsafe r.itemMap.subtracting(seen) { + let rslot = unsafe r.itemMap.slot(of: bucket) + unsafe node.ensureUniqueAndInsertItem( isUnique: copied, (r[item: rslot].key, ()), at: bucket) copied = true } - for (bucket, _) in r.childMap.subtracting(seen) { - let rslot = r.childMap.slot(of: bucket) + for (bucket, _) in unsafe r.childMap.subtracting(seen) { + let rslot = unsafe r.childMap.slot(of: bucket) node.ensureUnique( isUnique: copied, withFreeSpace: _HashNode.spaceForNewChild) copied = true - node.insertChild(r[child: rslot].mapValuesToVoid(), bucket) + unsafe node.insertChild(r[child: rslot].mapValuesToVoid(), bucket) } return (copied, node) @@ -162,10 +162,10 @@ extension _HashNode { let lc = self.isCollisionNode let rc = other.isCollisionNode if lc && rc { - return read { l in - other.read { r in - guard l.collisionHash == r.collisionHash else { - let node = _HashNode.build( + return unsafe read { l in + unsafe other.read { r in + guard unsafe l.collisionHash == r.collisionHash else { + let node = unsafe _HashNode.build( level: level, child1: self.mapValuesToVoid(), l.collisionHash, child2: other.mapValuesToVoid(), r.collisionHash) @@ -173,11 +173,11 @@ extension _HashNode { } var copied = false var node = self.mapValuesToVoid() - let litems = l.reverseItems - for rs: _HashSlot in stride(from: .zero, to: r.itemsEndSlot, by: 1) { - let p = r.itemPtr(at: rs) - if !litems.contains(where: { $0.key == p.pointee.key }) { - _ = node.ensureUniqueAndAppendCollision( + let litems = unsafe l.reverseItems + for rs: _HashSlot in stride(from: .zero, to: unsafe r.itemsEndSlot, by: 1) { + let p = unsafe r.itemPtr(at: rs) + if unsafe !litems.contains(where: { unsafe $0.key == p.pointee.key }) { + _ = unsafe node.ensureUniqueAndAppendCollision( isUnique: copied, (p.pointee.key, ())) copied = true } @@ -193,35 +193,35 @@ extension _HashNode { if lc { // `self` is a collision node on a compressed path. The other tree might // have the same set of collisions, just expanded a bit deeper. - return read { l in - other.read { r in - let bucket = l.collisionHash[level] - if r.itemMap.contains(bucket) { - let rslot = r.itemMap.slot(of: bucket) - let rp = r.itemPtr(at: rslot) + return unsafe read { l in + unsafe other.read { r in + let bucket = unsafe l.collisionHash[level] + if unsafe r.itemMap.contains(bucket) { + let rslot = unsafe r.itemMap.slot(of: bucket) + let rp = unsafe r.itemPtr(at: rslot) if - r.hasSingletonItem - && l.reverseItems.contains(where: { $0.key == rp.pointee.key }) + unsafe r.hasSingletonItem + && l.reverseItems.contains(where: { unsafe $0.key == rp.pointee.key }) { return (false, self.mapValuesToVoid()) } - let node = other.mapValuesToVoid().copyNodeAndPushItemIntoNewChild( + let node = unsafe other.mapValuesToVoid().copyNodeAndPushItemIntoNewChild( level: level, self.mapValuesToVoid(), at: bucket, itemSlot: rslot) return (true, node) } - if r.childMap.contains(bucket) { - let rslot = r.childMap.slot(of: bucket) - let res = self._union(level.descend(), r[child: rslot]) + if unsafe r.childMap.contains(bucket) { + let rslot = unsafe r.childMap.slot(of: bucket) + let res = unsafe self._union(level.descend(), r[child: rslot]) var node = other.mapValuesToVoid(copy: true) - let delta = node.replaceChild(at: bucket, rslot, with: res.node) + let delta = unsafe node.replaceChild(at: bucket, rslot, with: res.node) assert(delta >= 0) return (true, node) } var node = other.mapValuesToVoid( copy: true, extraBytes: _HashNode.spaceForNewChild) - node.insertChild(self.mapValuesToVoid(), bucket) + unsafe node.insertChild(self.mapValuesToVoid(), bucket) return (true, node) } } @@ -229,29 +229,29 @@ extension _HashNode { assert(rc) // `other` is a collision node on a compressed path. - return read { l -> (copied: Bool, node: _HashNode) in - other.read { r -> (copied: Bool, node: _HashNode) in - let bucket = r.collisionHash[level] - if l.itemMap.contains(bucket) { - let lslot = l.itemMap.slot(of: bucket) - assert(!l.hasSingletonItem) // Handled up front above - let node = self.mapValuesToVoid().copyNodeAndPushItemIntoNewChild( + return unsafe read { l -> (copied: Bool, node: _HashNode) in + unsafe other.read { r -> (copied: Bool, node: _HashNode) in + let bucket = unsafe r.collisionHash[level] + if unsafe l.itemMap.contains(bucket) { + let lslot = unsafe l.itemMap.slot(of: bucket) + assert(unsafe !l.hasSingletonItem) // Handled up front above + let node = unsafe self.mapValuesToVoid().copyNodeAndPushItemIntoNewChild( level: level, other.mapValuesToVoid(), at: bucket, itemSlot: lslot) return (true, node) } - if l.childMap.contains(bucket) { - let lslot = l.childMap.slot(of: bucket) - let child = l[child: lslot]._union(level.descend(), other) + if unsafe l.childMap.contains(bucket) { + let lslot = unsafe l.childMap.slot(of: bucket) + let child = unsafe l[child: lslot]._union(level.descend(), other) guard child.copied else { return (false, self.mapValuesToVoid()) } var node = self.mapValuesToVoid(copy: true) - let delta = node.replaceChild(at: bucket, lslot, with: child.node) + let delta = unsafe node.replaceChild(at: bucket, lslot, with: child.node) assert(delta > 0) // If we didn't add an item, why did we copy? return (true, node) } var node = self.mapValuesToVoid( copy: true, extraBytes: _HashNode.spaceForNewChild) - node.insertChild(other.mapValuesToVoid(), bucket) + unsafe node.insertChild(other.mapValuesToVoid(), bucket) return (true, node) } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Insertions.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Insertions.swift index 6e07287d..1a7ceb4d 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Insertions.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Insertions.swift @@ -22,7 +22,7 @@ extension _HashNode { _ item: Element, _ hash: _Hash ) -> (inserted: Bool, leaf: _UnmanagedHashNode, slot: _HashSlot) { - insert(level, item.key, hash) { $0.initialize(to: item) } + unsafe insert(level, item.key, hash) { unsafe $0.initialize(to: item) } } @inlinable @@ -35,43 +35,43 @@ extension _HashNode { defer { _invariantCheck() } let isUnique = self.isUnique() if !isUnique { - let r = self.inserting(level, key, hash, inserter) - self = r.node - return (r.inserted, r.leaf, r.slot) + let r = unsafe self.inserting(level, key, hash, inserter) + self = unsafe r.node + return unsafe (r.inserted, r.leaf, r.slot) } let r = findForInsertion(level, key, hash) switch r { case .found(_, let slot): - return (false, unmanaged, slot) + return (false, unsafe unmanaged, slot) case .insert(let bucket, let slot): - ensureUniqueAndInsertItem( + unsafe ensureUniqueAndInsertItem( isUnique: true, at: bucket, itemSlot: slot, inserter) - return (true, unmanaged, slot) + return (true, unsafe unmanaged, slot) case .appendCollision: - let slot = ensureUniqueAndAppendCollision(isUnique: true, inserter) - return (true, unmanaged, slot) + let slot = unsafe ensureUniqueAndAppendCollision(isUnique: true, inserter) + return (true, unsafe unmanaged, slot) case .spawnChild(let bucket, let slot): - let r = ensureUniqueAndSpawnChild( + let r = unsafe ensureUniqueAndSpawnChild( isUnique: true, level: level, replacing: bucket, itemSlot: slot, newHash: hash, inserter) - return (true, r.leaf, r.slot) + return unsafe (true, r.leaf, r.slot) case .expansion: - let r = _HashNode.build( + let r = unsafe _HashNode.build( level: level, item1: inserter, hash, child2: self, self.collisionHash) - self = r.top - return (true, r.leaf, r.slot1) + self = unsafe r.top + return unsafe (true, r.leaf, r.slot1) case .descend(_, let slot): - let r = update { - $0[child: slot].insert(level.descend(), key, hash, inserter) + let r = unsafe update { + unsafe $0[child: slot].insert(level.descend(), key, hash, inserter) } - if r.inserted { count &+= 1 } - return r + if unsafe r.inserted { count &+= 1 } + return unsafe r } } @@ -83,7 +83,7 @@ extension _HashNode { ) -> ( inserted: Bool, node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot ) { - inserting(level, item.key, hash, { $0.initialize(to: item) }) + unsafe inserting(level, item.key, hash, { unsafe $0.initialize(to: item) }) } @inlinable @@ -99,40 +99,40 @@ extension _HashNode { let r = findForInsertion(level, key, hash) switch r { case .found(_, let slot): - return (false, self, unmanaged, slot) + return unsafe (false, self, unmanaged, slot) case .insert(let bucket, let slot): - let node = copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter) - return (true, node, node.unmanaged, slot) + let node = unsafe copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter) + return unsafe (true, node, node.unmanaged, slot) case .appendCollision: - let r = copyNodeAndAppendCollision(inserter) - return (true, r.node, r.node.unmanaged, r.slot) + let r = unsafe copyNodeAndAppendCollision(inserter) + return unsafe (true, r.node, r.node.unmanaged, r.slot) case .spawnChild(let bucket, let slot): - let existingHash = read { _Hash($0[item: slot].key) } - let r = copyNodeAndSpawnChild( + let existingHash = unsafe read { unsafe _Hash($0[item: slot].key) } + let r = unsafe copyNodeAndSpawnChild( level: level, replacing: bucket, itemSlot: slot, existingHash: existingHash, newHash: hash, inserter) - return (true, r.node, r.leaf, r.slot) + return unsafe (true, r.node, r.leaf, r.slot) case .expansion: - let r = _HashNode.build( + let r = unsafe _HashNode.build( level: level, item1: inserter, hash, child2: self, self.collisionHash) - return (true, r.top, r.leaf, r.slot1) + return unsafe (true, r.top, r.leaf, r.slot1) case .descend(_, let slot): - let r = read { - $0[child: slot].inserting(level.descend(), key, hash, inserter) + let r = unsafe read { + unsafe $0[child: slot].inserting(level.descend(), key, hash, inserter) } - guard r.inserted else { - return (false, self, r.leaf, r.slot) + guard unsafe r.inserted else { + return unsafe (false, self, r.leaf, r.slot) } var copy = self.copy() - copy.update { $0[child: slot] = r.node } + unsafe copy.update { unsafe $0[child: slot] = r.node } copy.count &+= 1 - return (true, copy, r.leaf, r.slot) + return unsafe (true, copy, r.leaf, r.slot) } } @@ -149,38 +149,38 @@ extension _HashNode { switch r { case .found(_, let slot): ensureUnique(isUnique: isUnique) - return (false, unmanaged, slot) + return unsafe (false, unmanaged, slot) case .insert(let bucket, let slot): - ensureUniqueAndInsertItem( + unsafe ensureUniqueAndInsertItem( isUnique: isUnique, at: bucket, itemSlot: slot, inserter) - return (true, unmanaged, slot) + return unsafe (true, unmanaged, slot) case .appendCollision: - let slot = ensureUniqueAndAppendCollision(isUnique: isUnique, inserter) - return (true, unmanaged, slot) + let slot = unsafe ensureUniqueAndAppendCollision(isUnique: isUnique, inserter) + return unsafe (true, unmanaged, slot) case .spawnChild(let bucket, let slot): - let r = ensureUniqueAndSpawnChild( + let r = unsafe ensureUniqueAndSpawnChild( isUnique: isUnique, level: level, replacing: bucket, itemSlot: slot, newHash: hash, inserter) - return (true, r.leaf, r.slot) + return unsafe (true, r.leaf, r.slot) case .expansion: - let r = _HashNode.build( + let r = unsafe _HashNode.build( level: level, item1: inserter, hash, child2: self, self.collisionHash) - self = r.top - return (true, r.leaf, r.slot1) + self = unsafe r.top + return unsafe (true, r.leaf, r.slot1) case .descend(_, let slot): ensureUnique(isUnique: isUnique) - let r = update { - $0[child: slot].updateValue( + let r = unsafe update { + unsafe $0[child: slot].updateValue( level.descend(), forKey: key, hash, inserter) } - if r.inserted { count &+= 1 } - return r + if unsafe r.inserted { count &+= 1 } + return unsafe r } } } @@ -192,13 +192,13 @@ extension _HashNode { _ item: Element, at bucket: _Bucket ) { - let slot = self.read { $0.itemMap.slot(of: bucket) } - ensureUniqueAndInsertItem( + let slot = unsafe self.read { unsafe $0.itemMap.slot(of: bucket) } + unsafe ensureUniqueAndInsertItem( isUnique: isUnique, at: bucket, itemSlot: slot ) { - $0.initialize(to: item) + unsafe $0.initialize(to: item) } } @@ -212,17 +212,17 @@ extension _HashNode { assert(!isCollisionNode) if !isUnique { - self = copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter) + self = unsafe copyNodeAndInsertItem(at: bucket, itemSlot: slot, inserter) return } if !hasFreeSpace(Self.spaceForNewItem) { - resizeNodeAndInsertItem(at: bucket, itemSlot: slot, inserter) + unsafe resizeNodeAndInsertItem(at: bucket, itemSlot: slot, inserter) return } // In-place insert. - update { - let p = $0._makeRoomForNewItem(at: slot, bucket) - inserter(p) + unsafe update { + let p = unsafe $0._makeRoomForNewItem(at: slot, bucket) + unsafe inserter(p) } self.count &+= 1 } @@ -235,25 +235,25 @@ extension _HashNode { ) -> _HashNode { assert(!isCollisionNode) let c = self.count - return read { src in - assert(!src.itemMap.contains(bucket)) - assert(!src.childMap.contains(bucket)) - return Self.allocate( + return unsafe read { src in + assert(unsafe !src.itemMap.contains(bucket)) + assert(unsafe !src.childMap.contains(bucket)) + return unsafe Self.allocate( itemMap: src.itemMap.inserting(bucket), childMap: src.childMap, count: c &+ 1 ) { dstChildren, dstItems in - dstChildren.initializeAll(fromContentsOf: src.children) + unsafe dstChildren.initializeAll(fromContentsOf: src.children) - let srcItems = src.reverseItems + let srcItems = unsafe src.reverseItems assert(dstItems.count == srcItems.count + 1) - dstItems.suffix(slot.value) + unsafe dstItems.suffix(slot.value) .initializeAll(fromContentsOf: srcItems.suffix(slot.value)) let rest = srcItems.count &- slot.value - dstItems.prefix(rest) + unsafe dstItems.prefix(rest) .initializeAll(fromContentsOf: srcItems.prefix(rest)) - inserter(dstItems.baseAddress! + rest) + unsafe inserter(dstItems.baseAddress! + rest) }.node } } @@ -266,27 +266,27 @@ extension _HashNode { ) { assert(!isCollisionNode) let c = self.count - self = update { src in - assert(!src.itemMap.contains(bucket)) - assert(!src.childMap.contains(bucket)) - return Self.allocate( + self = unsafe update { src in + assert(unsafe !src.itemMap.contains(bucket)) + assert(unsafe !src.childMap.contains(bucket)) + return unsafe Self.allocate( itemMap: src.itemMap.inserting(bucket), childMap: src.childMap, count: c &+ 1 ) { dstChildren, dstItems in - dstChildren.moveInitializeAll(fromContentsOf: src.children) + unsafe dstChildren.moveInitializeAll(fromContentsOf: src.children) - let srcItems = src.reverseItems + let srcItems = unsafe src.reverseItems assert(dstItems.count == srcItems.count + 1) - dstItems.suffix(slot.value) + unsafe dstItems.suffix(slot.value) .moveInitializeAll(fromContentsOf: srcItems.suffix(slot.value)) let rest = srcItems.count &- slot.value - dstItems.prefix(rest) + unsafe dstItems.prefix(rest) .moveInitializeAll(fromContentsOf: srcItems.prefix(rest)) - inserter(dstItems.baseAddress! + rest) + unsafe inserter(dstItems.baseAddress! + rest) - src.clear() + unsafe src.clear() }.node } } @@ -294,71 +294,75 @@ extension _HashNode { extension _HashNode { @inlinable + @unsafe internal mutating func ensureUniqueAndAppendCollision( isUnique: Bool, _ item: Element ) -> _HashSlot { - ensureUniqueAndAppendCollision(isUnique: isUnique) { - $0.initialize(to: item) + unsafe ensureUniqueAndAppendCollision(isUnique: isUnique) { + unsafe $0.initialize(to: item) } } @inlinable + @unsafe internal mutating func ensureUniqueAndAppendCollision( isUnique: Bool, _ inserter: (UnsafeMutablePointer) -> Void ) -> _HashSlot { assert(isCollisionNode) if !isUnique { - let r = copyNodeAndAppendCollision(inserter) + let r = unsafe copyNodeAndAppendCollision(inserter) self = r.node return r.slot } if !hasFreeSpace(Self.spaceForNewItem) { - return resizeNodeAndAppendCollision(inserter) + return unsafe resizeNodeAndAppendCollision(inserter) } // In-place insert. - update { - let p = $0._makeRoomForNewItem(at: $0.itemsEndSlot, .invalid) - inserter(p) + unsafe update { + let p = unsafe $0._makeRoomForNewItem(at: $0.itemsEndSlot, .invalid) + unsafe inserter(p) } self.count &+= 1 return _HashSlot(self.count &- 1) } @inlinable @inline(never) + @unsafe internal func copyNodeAndAppendCollision( _ inserter: (UnsafeMutablePointer) -> Void ) -> (node: _HashNode, slot: _HashSlot) { assert(isCollisionNode) - assert(self.count == read { $0.collisionCount }) + assert(unsafe self.count == read { unsafe $0.collisionCount }) let c = self.count - let node = read { src in - Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in - let srcItems = src.reverseItems + let node = unsafe read { src in + unsafe Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in + let srcItems = unsafe src.reverseItems assert(dstItems.count == srcItems.count + 1) - dstItems.dropFirst().initializeAll(fromContentsOf: srcItems) - inserter(dstItems.baseAddress!) + unsafe dstItems.dropFirst().initializeAll(fromContentsOf: srcItems) + unsafe inserter(dstItems.baseAddress!) }.node } return (node, _HashSlot(c)) } @inlinable @inline(never) + @unsafe internal mutating func resizeNodeAndAppendCollision( _ inserter: (UnsafeMutablePointer) -> Void ) -> _HashSlot { assert(isCollisionNode) - assert(self.count == read { $0.collisionCount }) + assert(unsafe self.count == read { unsafe $0.collisionCount }) let c = self.count - self = update { src in - Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in - let srcItems = src.reverseItems + self = unsafe update { src in + unsafe Self.allocateCollision(count: c &+ 1, src.collisionHash) { dstItems in + let srcItems = unsafe src.reverseItems assert(dstItems.count == srcItems.count + 1) - dstItems.dropFirst().moveInitializeAll(fromContentsOf: srcItems) - inserter(dstItems.baseAddress!) + unsafe dstItems.dropFirst().moveInitializeAll(fromContentsOf: srcItems) + unsafe inserter(dstItems.baseAddress!) - src.clear() + unsafe src.clear() }.node } return _HashSlot(c) @@ -367,6 +371,7 @@ extension _HashNode { extension _HashNode { @inlinable + @unsafe internal func _copyNodeAndReplaceItemWithNewChild( level: _HashLevel, _ newChild: __owned _HashNode, @@ -374,40 +379,40 @@ extension _HashNode { itemSlot: _HashSlot ) -> _HashNode { let c = self.count - return read { src in - assert(!src.isCollisionNode) - assert(src.itemMap.contains(bucket)) - assert(!src.childMap.contains(bucket)) - assert(src.itemMap.slot(of: bucket) == itemSlot) + return unsafe read { src in + assert(unsafe !src.isCollisionNode) + assert(unsafe src.itemMap.contains(bucket)) + assert(unsafe !src.childMap.contains(bucket)) + assert(unsafe src.itemMap.slot(of: bucket) == itemSlot) - if src.hasSingletonItem && newChild.isCollisionNode { + if unsafe src.hasSingletonItem && newChild.isCollisionNode { // Compression return newChild } - let childSlot = src.childMap.slot(of: bucket) - return Self.allocate( + let childSlot = unsafe src.childMap.slot(of: bucket) + return unsafe Self.allocate( itemMap: src.itemMap.removing(bucket), childMap: src.childMap.inserting(bucket), count: c &+ newChild.count &- 1 ) { dstChildren, dstItems in - let srcChildren = src.children - let srcItems = src.reverseItems + let srcChildren = unsafe src.children + let srcItems = unsafe src.reverseItems // Initialize children. - dstChildren.prefix(childSlot.value) + unsafe dstChildren.prefix(childSlot.value) .initializeAll(fromContentsOf: srcChildren.prefix(childSlot.value)) let rest = srcChildren.count &- childSlot.value - dstChildren.suffix(rest) + unsafe dstChildren.suffix(rest) .initializeAll(fromContentsOf: srcChildren.suffix(rest)) - dstChildren.initializeElement(at: childSlot.value, to: newChild) + unsafe dstChildren.initializeElement(at: childSlot.value, to: newChild) // Initialize items. - dstItems.suffix(itemSlot.value) + unsafe dstItems.suffix(itemSlot.value) .initializeAll(fromContentsOf: srcItems.suffix(itemSlot.value)) let rest2 = dstItems.count &- itemSlot.value - dstItems.prefix(rest2) + unsafe dstItems.prefix(rest2) .initializeAll(fromContentsOf: srcItems.prefix(rest2)) }.node } @@ -416,6 +421,7 @@ extension _HashNode { /// The item at `itemSlot` must have already been deinitialized by the time /// this function is called. @inlinable + @unsafe internal mutating func _resizeNodeAndReplaceItemWithNewChild( level: _HashLevel, _ newChild: __owned _HashNode, @@ -423,38 +429,38 @@ extension _HashNode { itemSlot: _HashSlot ) { let c = self.count - let node: _HashNode = update { src in - assert(!src.isCollisionNode) - assert(src.itemMap.contains(bucket)) - assert(!src.childMap.contains(bucket)) - assert(src.itemMap.slot(of: bucket) == itemSlot) + let node: _HashNode = unsafe update { src in + assert(unsafe !src.isCollisionNode) + assert(unsafe src.itemMap.contains(bucket)) + assert(unsafe !src.childMap.contains(bucket)) + assert(unsafe src.itemMap.slot(of: bucket) == itemSlot) - let childSlot = src.childMap.slot(of: bucket) - return Self.allocate( + let childSlot = unsafe src.childMap.slot(of: bucket) + return unsafe Self.allocate( itemMap: src.itemMap.removing(bucket), childMap: src.childMap.inserting(bucket), count: c &+ newChild.count &- 1 ) { dstChildren, dstItems in - let srcChildren = src.children - let srcItems = src.reverseItems + let srcChildren = unsafe src.children + let srcItems = unsafe src.reverseItems // Initialize children. - dstChildren.prefix(childSlot.value) + unsafe dstChildren.prefix(childSlot.value) .moveInitializeAll(fromContentsOf: srcChildren.prefix(childSlot.value)) let rest = srcChildren.count &- childSlot.value - dstChildren.suffix(rest) + unsafe dstChildren.suffix(rest) .moveInitializeAll(fromContentsOf: srcChildren.suffix(rest)) - dstChildren.initializeElement(at: childSlot.value, to: newChild) + unsafe dstChildren.initializeElement(at: childSlot.value, to: newChild) // Initialize items. - dstItems.suffix(itemSlot.value) + unsafe dstItems.suffix(itemSlot.value) .moveInitializeAll(fromContentsOf: srcItems.suffix(itemSlot.value)) let rest2 = dstItems.count &- itemSlot.value - dstItems.prefix(rest2) + unsafe dstItems.prefix(rest2) .moveInitializeAll(fromContentsOf: srcItems.prefix(rest2)) - src.clear() + unsafe src.clear() }.node } self = node @@ -463,6 +469,7 @@ extension _HashNode { extension _HashNode { @inlinable @inline(never) + @unsafe internal func copyNodeAndPushItemIntoNewChild( level: _HashLevel, _ newChild: __owned _HashNode, @@ -470,10 +477,10 @@ extension _HashNode { itemSlot: _HashSlot ) -> _HashNode { assert(!isCollisionNode) - let item = read { $0[item: itemSlot] } + let item = unsafe read { unsafe $0[item: itemSlot] } let hash = _Hash(item.key) - let r = newChild.inserting(level.descend(), item, hash) - return _copyNodeAndReplaceItemWithNewChild( + let r = unsafe newChild.inserting(level.descend(), item, hash) + return unsafe _copyNodeAndReplaceItemWithNewChild( level: level, r.node, at: bucket, @@ -483,6 +490,7 @@ extension _HashNode { extension _HashNode { @inlinable + @unsafe internal mutating func ensureUniqueAndSpawnChild( isUnique: Bool, level: _HashLevel, @@ -491,27 +499,27 @@ extension _HashNode { newHash: _Hash, _ inserter: (UnsafeMutablePointer) -> Void ) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) { - let existingHash = read { _Hash($0[item: itemSlot].key) } + let existingHash = unsafe read { unsafe _Hash($0[item: itemSlot].key) } assert(existingHash.isEqual(to: newHash, upTo: level)) if newHash == existingHash, hasSingletonItem { // Convert current node to a collision node. - self = _HashNode._collisionNode(newHash, read { $0[item: .zero] }, inserter) - return (unmanaged, _HashSlot(1)) + self = unsafe _HashNode._collisionNode(newHash, read { unsafe $0[item: .zero] }, inserter) + return unsafe (unmanaged, _HashSlot(1)) } if !isUnique { - let r = copyNodeAndSpawnChild( + let r = unsafe copyNodeAndSpawnChild( level: level, replacing: bucket, itemSlot: itemSlot, existingHash: existingHash, newHash: newHash, inserter) - self = r.node - return (r.leaf, r.slot) + self = unsafe r.node + return unsafe (r.leaf, r.slot) } if !hasFreeSpace(Self.spaceForSpawningChild) { - return resizeNodeAndSpawnChild( + return unsafe resizeNodeAndSpawnChild( level: level, replacing: bucket, itemSlot: itemSlot, @@ -520,16 +528,17 @@ extension _HashNode { inserter) } - let existing = removeItem(at: bucket, itemSlot) - let r = _HashNode.build( + let existing = unsafe removeItem(at: bucket, itemSlot) + let r = unsafe _HashNode.build( level: level.descend(), item1: existing, existingHash, item2: inserter, newHash) - insertChild(r.top, bucket) - return (r.leaf, r.slot2) + unsafe insertChild(r.top, bucket) + return unsafe (r.leaf, r.slot2) } @inlinable @inline(never) + @unsafe internal func copyNodeAndSpawnChild( level: _HashLevel, replacing bucket: _Bucket, @@ -538,22 +547,23 @@ extension _HashNode { newHash: _Hash, _ inserter: (UnsafeMutablePointer) -> Void ) -> (node: _HashNode, leaf: _UnmanagedHashNode, slot: _HashSlot) { - let r = read { - _HashNode.build( + let r = unsafe read { + unsafe _HashNode.build( level: level.descend(), item1: $0[item: itemSlot], existingHash, item2: inserter, newHash) } - let node = _copyNodeAndReplaceItemWithNewChild( + let node = unsafe _copyNodeAndReplaceItemWithNewChild( level: level, r.top, at: bucket, itemSlot: itemSlot) node._invariantCheck() - return (node, r.leaf, r.slot2) + return unsafe (node, r.leaf, r.slot2) } @inlinable @inline(never) + @unsafe internal mutating func resizeNodeAndSpawnChild( level: _HashLevel, replacing bucket: _Bucket, @@ -562,19 +572,19 @@ extension _HashNode { newHash: _Hash, _ inserter: (UnsafeMutablePointer) -> Void ) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) { - let r = update { - _HashNode.build( + let r = unsafe update { + unsafe _HashNode.build( level: level.descend(), item1: $0.itemPtr(at: itemSlot).move(), existingHash, item2: inserter, newHash) } - _resizeNodeAndReplaceItemWithNewChild( + unsafe _resizeNodeAndReplaceItemWithNewChild( level: level, r.top, at: bucket, itemSlot: itemSlot) _invariantCheck() - return (r.leaf, r.slot2) + return unsafe (r.leaf, r.slot2) } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Modify.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Modify.swift index 8ccab003..6b86e2a2 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Modify.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Modify.swift @@ -19,9 +19,9 @@ extension _HashNode { level: _HashLevel, at path: _UnsafePath ) -> (leaf: _UnmanagedHashNode, slot: _HashSlot) { ensureUnique(isUnique: isUnique()) - guard level < path.level else { return (unmanaged, path.currentItemSlot) } - return update { - $0[child: path.childSlot(at: level)] + guard level < path.level else { return unsafe (unmanaged, path.currentItemSlot) } + return unsafe update { + unsafe $0[child: path.childSlot(at: level)] .ensureUnique(level: level.descend(), at: path) } } @@ -30,20 +30,25 @@ extension _HashNode { extension _HashNode { @usableFromInline @frozen + @unsafe internal struct ValueUpdateState { @usableFromInline + @safe internal var key: Key @usableFromInline + @safe internal var value: Value? @usableFromInline + @safe internal let hash: _Hash @usableFromInline internal var path: _UnsafePath @usableFromInline + @safe internal var found: Bool @inlinable @@ -55,22 +60,24 @@ extension _HashNode { self.key = key self.value = nil self.hash = hash - self.path = path + unsafe self.path = path self.found = false } } @inlinable + @unsafe internal mutating func prepareValueUpdate( _ key: Key, _ hash: _Hash ) -> ValueUpdateState { - var state = ValueUpdateState(key, hash, _UnsafePath(root: raw)) - _prepareValueUpdate(&state) - return state + var state = unsafe ValueUpdateState(key, hash, _UnsafePath(root: raw)) + unsafe _prepareValueUpdate(&state) + return unsafe state } @inlinable + @unsafe internal mutating func _prepareValueUpdate( _ state: inout ValueUpdateState ) { @@ -81,59 +88,60 @@ extension _HashNode { // If the key already exists, we ensure uniqueness for its node and extract // its item but otherwise leave the tree as it was. let isUnique = self.isUnique() - let r = findForInsertion(state.path.level, state.key, state.hash) + let r = unsafe findForInsertion(state.path.level, state.key, state.hash) switch r { case .found(_, let slot): ensureUnique(isUnique: isUnique) - state.path.node = unmanaged - state.path.selectItem(at: slot) + unsafe state.path.node = unmanaged + unsafe state.path.selectItem(at: slot) state.found = true - (state.key, state.value) = update { $0.itemPtr(at: slot).move() } + (state.key, state.value) = unsafe update { unsafe $0.itemPtr(at: slot).move() } case .insert(_, let slot): - state.path.selectItem(at: slot) + unsafe state.path.selectItem(at: slot) case .appendCollision: - state.path.selectItem(at: _HashSlot(self.count)) + unsafe state.path.selectItem(at: _HashSlot(self.count)) case .spawnChild(_, let slot): - state.path.selectItem(at: slot) + unsafe state.path.selectItem(at: slot) case .expansion: - state.path.selectEnd() + unsafe state.path.selectEnd() case .descend(_, let slot): ensureUnique(isUnique: isUnique) - update { - let p = $0.childPtr(at: slot) - state.path.descendToChild(p.pointee.unmanaged, at: slot) - p.pointee._prepareValueUpdate(&state) + unsafe update { + let p = unsafe $0.childPtr(at: slot) + unsafe state.path.descendToChild(p.pointee.unmanaged, at: slot) + unsafe p.pointee._prepareValueUpdate(&state) } } } @inlinable + @unsafe internal mutating func finalizeValueUpdate( _ state: __owned ValueUpdateState ) { switch (state.found, state.value != nil) { case (true, true): // Fast path: updating an existing value. - UnsafeHandle.update(state.path.node) { - $0.itemPtr(at: state.path.currentItemSlot) + unsafe UnsafeHandle.update(state.path.node) { + unsafe $0.itemPtr(at: state.path.currentItemSlot) .initialize(to: (state.key, state.value.unsafelyUnwrapped)) } case (true, false): // Removal - let remainder = _finalizeRemoval(.top, state.hash, at: state.path) + let remainder = unsafe _finalizeRemoval(.top, state.hash, at: state.path) assert(remainder == nil) case (false, true): // Insertion - let r = updateValue(.top, forKey: state.key, state.hash) { - $0.initialize(to: (state.key, state.value.unsafelyUnwrapped)) + let r = unsafe updateValue(.top, forKey: state.key, state.hash) { + unsafe $0.initialize(to: (state.key, state.value.unsafelyUnwrapped)) } - assert(r.inserted) + assert(unsafe r.inserted) case (false, false): // Noop break @@ -141,20 +149,21 @@ extension _HashNode { } @inlinable + @unsafe internal mutating func _finalizeRemoval( _ level: _HashLevel, _ hash: _Hash, at path: _UnsafePath ) -> Element? { assert(isUnique()) if level == path.level { - return _removeItemFromUniqueLeafNode( + return unsafe _removeItemFromUniqueLeafNode( level, at: hash[level], path.currentItemSlot, by: { _ in } ).remainder } - let slot = path.childSlot(at: level) - let remainder = update { - $0[child: slot]._finalizeRemoval(level.descend(), hash, at: path) + let slot = unsafe path.childSlot(at: level) + let remainder = unsafe update { + unsafe $0[child: slot]._finalizeRemoval(level.descend(), hash, at: path) } - return _fixupUniqueAncestorAfterItemRemoval( + return unsafe _fixupUniqueAncestorAfterItemRemoval( level, at: { _ in hash[level] }, slot, remainder: remainder) } } @@ -162,17 +171,21 @@ extension _HashNode { extension _HashNode { @usableFromInline @frozen + @unsafe internal struct DefaultedValueUpdateState { @usableFromInline + @safe internal var item: Element @usableFromInline internal var node: _UnmanagedHashNode @usableFromInline + @safe internal var slot: _HashSlot @usableFromInline + @safe internal var inserted: Bool @inlinable @@ -183,7 +196,7 @@ extension _HashNode { inserted: Bool ) { self.item = item - self.node = node + unsafe self.node = node self.slot = slot self.inserted = inserted } @@ -201,51 +214,51 @@ extension _HashNode { switch r { case .found(_, let slot): ensureUnique(isUnique: isUnique) - return DefaultedValueUpdateState( - update { $0.itemPtr(at: slot).move() }, + return unsafe DefaultedValueUpdateState( + update { unsafe $0.itemPtr(at: slot).move() }, in: unmanaged, at: slot, inserted: false) case .insert(let bucket, let slot): - ensureUniqueAndInsertItem( + unsafe ensureUniqueAndInsertItem( isUnique: isUnique, at: bucket, itemSlot: slot ) { _ in } - return DefaultedValueUpdateState( + return unsafe DefaultedValueUpdateState( (key, defaultValue()), in: unmanaged, at: slot, inserted: true) case .appendCollision: - let slot = ensureUniqueAndAppendCollision(isUnique: isUnique) { _ in } - return DefaultedValueUpdateState( + let slot = unsafe ensureUniqueAndAppendCollision(isUnique: isUnique) { _ in } + return unsafe DefaultedValueUpdateState( (key, defaultValue()), in: unmanaged, at: slot, inserted: true) case .spawnChild(let bucket, let slot): - let r = ensureUniqueAndSpawnChild( + let r = unsafe ensureUniqueAndSpawnChild( isUnique: isUnique, level: level, replacing: bucket, itemSlot: slot, newHash: hash) { _ in } - return DefaultedValueUpdateState( + return unsafe DefaultedValueUpdateState( (key, defaultValue()), in: r.leaf, at: r.slot, inserted: true) case .expansion: - let r = _HashNode.build( + let r = unsafe _HashNode.build( level: level, item1: { _ in }, hash, child2: self, self.collisionHash ) - self = r.top - return DefaultedValueUpdateState( + self = unsafe r.top + return unsafe DefaultedValueUpdateState( (key, defaultValue()), in: r.leaf, at: r.slot1, @@ -253,12 +266,12 @@ extension _HashNode { case .descend(_, let slot): ensureUnique(isUnique: isUnique) - let res = update { - $0[child: slot].prepareDefaultedValueUpdate( + let res = unsafe update { + unsafe $0[child: slot].prepareDefaultedValueUpdate( level.descend(), key, defaultValue, hash) } if res.inserted { count &+= 1 } - return res + return unsafe res } } @@ -266,8 +279,8 @@ extension _HashNode { internal mutating func finalizeDefaultedValueUpdate( _ state: __owned DefaultedValueUpdateState ) { - UnsafeHandle.update(state.node) { - $0.itemPtr(at: state.slot).initialize(to: state.item) + unsafe UnsafeHandle.update(state.node) { + unsafe $0.itemPtr(at: state.slot).initialize(to: state.item) } } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Removals.swift b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Removals.swift index 4aebfc77..c0c40287 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Removals.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+Subtree Removals.swift @@ -20,26 +20,27 @@ extension _HashNode { /// It is up to the caller to detect this situation & correct it when needed, /// by inlining the remaining item into the parent node. @inlinable + @unsafe internal mutating func remove( _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> (removed: Element, remainder: Element?)? { guard self.isUnique() else { - guard let r = removing(level, key, hash) else { return nil } - let remainder = self.applyReplacement(level, r.replacement) + guard let r = unsafe removing(level, key, hash) else { return nil } + let remainder = unsafe self.applyReplacement(level, r.replacement) return (r.removed, remainder) } guard let r = find(level, key, hash) else { return nil } let bucket = hash[level] guard r.descend else { - let r = _removeItemFromUniqueLeafNode(level, at: bucket, r.slot) { - $0.move() + let r = unsafe _removeItemFromUniqueLeafNode(level, at: bucket, r.slot) { + unsafe $0.move() } return (r.result, r.remainder) } - let r2 = update { $0[child: r.slot].remove(level.descend(), key, hash) } + let r2 = unsafe update { unsafe $0[child: r.slot].remove(level.descend(), key, hash) } guard let r2 = r2 else { return nil } - let remainder = _fixupUniqueAncestorAfterItemRemoval( + let remainder = unsafe _fixupUniqueAncestorAfterItemRemoval( level, at: { _ in hash[level] }, r.slot, @@ -50,17 +51,18 @@ extension _HashNode { extension _HashNode { @inlinable + @unsafe internal func removing( _ level: _HashLevel, _ key: Key, _ hash: _Hash ) -> (removed: Element, replacement: Builder)? { guard let r = find(level, key, hash) else { return nil } let bucket = hash[level] guard r.descend else { - return _removingItemFromLeaf(level, at: bucket, r.slot) + return unsafe _removingItemFromLeaf(level, at: bucket, r.slot) } - let r2 = read { $0[child: r.slot].removing(level.descend(), key, hash) } + let r2 = unsafe read { unsafe $0[child: r.slot].removing(level.descend(), key, hash) } guard let r2 = r2 else { return nil } - let replacement = self.replacingChild( + let replacement = unsafe self.replacingChild( level, at: bucket, r.slot, with: r2.replacement) return (r2.removed, replacement) } @@ -68,54 +70,57 @@ extension _HashNode { extension _HashNode { @inlinable + @unsafe internal mutating func remove( _ level: _HashLevel, at path: _UnsafePath ) -> (removed: Element, remainder: Element?) { defer { _invariantCheck() } guard self.isUnique() else { - let r = removing(level, at: path) - let remainder = applyReplacement(level, r.replacement) + let r = unsafe removing(level, at: path) + let remainder = unsafe applyReplacement(level, r.replacement) return (r.removed, remainder) } if level == path.level { - let slot = path.currentItemSlot - let bucket = read { $0.itemBucket(at: slot) } - let r = _removeItemFromUniqueLeafNode( - level, at: bucket, slot, by: { $0.move() }) + let slot = unsafe path.currentItemSlot + let bucket = unsafe read { unsafe $0.itemBucket(at: slot) } + let r = unsafe _removeItemFromUniqueLeafNode( + level, at: bucket, slot, by: { unsafe $0.move() }) return (r.result, r.remainder) } - let slot = path.childSlot(at: level) - let r = update { $0[child: slot].remove(level.descend(), at: path) } - let remainder = _fixupUniqueAncestorAfterItemRemoval( + let slot = unsafe path.childSlot(at: level) + let r = unsafe update { unsafe $0[child: slot].remove(level.descend(), at: path) } + let remainder = unsafe _fixupUniqueAncestorAfterItemRemoval( level, - at: { $0.childMap.bucket(at: slot) }, + at: { unsafe $0.childMap.bucket(at: slot) }, slot, remainder: r.remainder) return (r.removed, remainder) } @inlinable + @unsafe internal func removing( _ level: _HashLevel, at path: _UnsafePath ) -> (removed: Element, replacement: Builder) { if level == path.level { - let slot = path.currentItemSlot - let bucket = read { $0.itemBucket(at: slot) } - return _removingItemFromLeaf(level, at: bucket, slot) + let slot = unsafe path.currentItemSlot + let bucket = unsafe read { unsafe $0.itemBucket(at: slot) } + return unsafe _removingItemFromLeaf(level, at: bucket, slot) } - let slot = path.childSlot(at: level) - return read { - let bucket = $0.childMap.bucket(at: slot) - let r = $0[child: slot].removing(level.descend(), at: path) + let slot = unsafe path.childSlot(at: level) + return unsafe read { + let bucket = unsafe $0.childMap.bucket(at: slot) + let r = unsafe $0[child: slot].removing(level.descend(), at: path) return ( r.removed, - self.replacingChild(level, at: bucket, slot, with: r.replacement)) + unsafe self.replacingChild(level, at: bucket, slot, with: r.replacement)) } } } extension _HashNode { @inlinable + @unsafe internal mutating func _removeItemFromUniqueLeafNode( _ level: _HashLevel, at bucket: _Bucket, @@ -123,7 +128,7 @@ extension _HashNode { by remover: (UnsafeMutablePointer) -> R ) -> (result: R, remainder: Element?) { assert(isUnique()) - let result = removeItem(at: bucket, slot, by: remover) + let result = unsafe removeItem(at: bucket, slot, by: remover) if isAtrophied { self = removeSingletonChild() } @@ -134,64 +139,65 @@ extension _HashNode { } return (result, nil) } - let item = removeSingletonItem() + let item = unsafe removeSingletonItem() return (result, item) } return (result, nil) } @inlinable + @unsafe internal func _removingItemFromLeaf( _ level: _HashLevel, at bucket: _Bucket, _ slot: _HashSlot ) -> (removed: Element, replacement: Builder) { - read { - if $0.isCollisionNode { - assert(slot.value < $0.collisionCount ) + unsafe read { + if unsafe $0.isCollisionNode { + assert(unsafe slot.value < $0.collisionCount ) - if $0.collisionCount == 2 { + if unsafe $0.collisionCount == 2 { // Node will evaporate let remainder = _HashSlot(1 &- slot.value) - let bucket = $0.collisionHash[level] + let bucket = unsafe $0.collisionHash[level] return ( - removed: $0[item: slot], - replacement: .item(level, $0[item: remainder], at: bucket)) + removed: unsafe $0[item: slot], + replacement: unsafe .item(level, $0[item: remainder], at: bucket)) } var node = self.copy() - let old = node.removeItem(at: bucket, slot) + let old = unsafe node.removeItem(at: bucket, slot) node._invariantCheck() return (old, .collisionNode(level, node)) } - assert($0.itemMap.contains(bucket)) - assert(slot == $0.itemMap.slot(of: bucket)) + assert(unsafe $0.itemMap.contains(bucket)) + assert(unsafe slot == $0.itemMap.slot(of: bucket)) let willAtrophy = ( - !$0.isCollisionNode + unsafe !$0.isCollisionNode && $0.itemMap.hasExactlyOneMember && $0.childMap.hasExactlyOneMember && $0[child: .zero].isCollisionNode) if willAtrophy { // Compression - let child = $0[child: .zero] - let old = $0[item: .zero] + let child = unsafe $0[child: .zero] + let old = unsafe $0[item: .zero] return (old, .collisionNode(level, child)) } - if $0.itemMap.count == 2 && $0.childMap.isEmpty { + if unsafe $0.itemMap.count == 2 && $0.childMap.isEmpty { // Evaporating node let remainder = _HashSlot(1 &- slot.value) - var map = $0.itemMap + var map = unsafe $0.itemMap if remainder != .zero { _ = map.popFirst() } let bucket = map.first! return ( - removed: $0[item: slot], - replacement: .item(level, $0[item: remainder], at: bucket)) + removed: unsafe $0[item: slot], + replacement: unsafe .item(level, $0[item: remainder], at: bucket)) } var node = self.copy() - let old = node.removeItem(at: bucket, slot) + let old = unsafe node.removeItem(at: bucket, slot) node._invariantCheck() return (old, .node(level, node)) } @@ -200,31 +206,32 @@ extension _HashNode { extension _HashNode { @inlinable + @unsafe internal func _removingChild( _ level: _HashLevel, at bucket: _Bucket, _ slot: _HashSlot ) -> Builder { - read { - assert(!$0.isCollisionNode && $0.childMap.contains(bucket)) - let willAtrophy = ( + unsafe read { + assert(unsafe !$0.isCollisionNode && $0.childMap.contains(bucket)) + let willAtrophy = unsafe ( $0.itemMap.isEmpty && $0.childCount == 2 && $0[child: _HashSlot(1 &- slot.value)].isCollisionNode ) if willAtrophy { // Compression - let child = $0[child: _HashSlot(1 &- slot.value)] + let child = unsafe $0[child: _HashSlot(1 &- slot.value)] return .collisionNode(level, child) } - if $0.itemMap.hasExactlyOneMember && $0.childMap.hasExactlyOneMember { - return .item(level, $0[item: .zero], at: $0.itemMap.first!) + if unsafe $0.itemMap.hasExactlyOneMember && $0.childMap.hasExactlyOneMember { + return unsafe .item(level, $0[item: .zero], at: $0.itemMap.first!) } - if $0.hasSingletonChild { + if unsafe $0.hasSingletonChild { // Evaporate node return .empty(level) } var node = self.copy() - _ = node.removeChild(at: bucket, slot) + _ = unsafe node.removeChild(at: bucket, slot) node._invariantCheck() return .node(level, node) } @@ -233,6 +240,7 @@ extension _HashNode { extension _HashNode { @inlinable + @unsafe internal mutating func _fixupUniqueAncestorAfterItemRemoval( _ level: _HashLevel, at bucket: (UnsafeHandle) -> _Bucket, @@ -248,12 +256,12 @@ extension _HashNode { } // Child to be inlined has already been cleared, so we need to adjust // the count manually. - assert(read { $0[child: childSlot].count == 0 }) + assert(unsafe read { unsafe $0[child: childSlot].count == 0 }) count &-= 1 - let bucket = read { bucket($0) } + let bucket = unsafe read { unsafe bucket($0) } ensureUnique(isUnique: true, withFreeSpace: Self.spaceForInlinedChild) - _ = self.removeChild(at: bucket, childSlot) - insertItem(remainder, at: bucket) + _ = unsafe self.removeChild(at: bucket, childSlot) + unsafe insertItem(remainder, at: bucket) return nil } if isAtrophied { @@ -268,10 +276,10 @@ extension _HashNode { internal mutating func _convertToRegularNode() { assert(isCollisionNode && hasSingletonItem) assert(isUnique()) - update { - $0.itemMap = _Bitmap($0.collisionHash[.top]) - $0.childMap = .empty - $0.bytesFree &+= MemoryLayout<_Hash>.stride + unsafe update { + unsafe $0.itemMap = _Bitmap($0.collisionHash[.top]) + unsafe $0.childMap = .empty + unsafe $0.bytesFree &+= MemoryLayout<_Hash>.stride } } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode+UnsafeHandle.swift b/Sources/HashTreeCollections/HashNode/_HashNode+UnsafeHandle.swift index 78c8d7e9..1d3ce4e2 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode+UnsafeHandle.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode+UnsafeHandle.swift @@ -24,6 +24,7 @@ extension _HashNode { /// they're called on a read-only view. @usableFromInline @frozen + @unsafe internal struct UnsafeHandle { @usableFromInline internal typealias Element = (key: Key, value: Value) @@ -36,6 +37,7 @@ extension _HashNode { #if DEBUG @usableFromInline + @safe internal let _isMutable: Bool #endif @@ -45,8 +47,8 @@ extension _HashNode { _ memory: UnsafeMutableRawPointer, isMutable: Bool ) { - self._header = header - self._memory = memory + unsafe self._header = header + unsafe self._memory = memory #if DEBUG self._isMutable = isMutable #endif @@ -57,6 +59,7 @@ extension _HashNode { extension _HashNode.UnsafeHandle { @inlinable @inline(__always) + @safe func assertMutable() { #if DEBUG assert(_isMutable) @@ -70,9 +73,9 @@ extension _HashNode.UnsafeHandle { _ node: _UnmanagedHashNode, _ body: (Self) throws -> R ) rethrows -> R { - try node.ref._withUnsafeGuaranteedRef { storage in - try storage.withUnsafeMutablePointers { header, elements in - try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: false)) + unsafe try node.ref._withUnsafeGuaranteedRef { storage in + unsafe try storage.withUnsafeMutablePointers { header, elements in + unsafe try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: false)) } } } @@ -82,8 +85,8 @@ extension _HashNode.UnsafeHandle { _ storage: _RawHashStorage, _ body: (Self) throws -> R ) rethrows -> R { - try storage.withUnsafeMutablePointers { header, elements in - try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: false)) + unsafe try storage.withUnsafeMutablePointers { header, elements in + unsafe try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: false)) } } @@ -92,9 +95,9 @@ extension _HashNode.UnsafeHandle { _ node: _UnmanagedHashNode, _ body: (Self) throws -> R ) rethrows -> R { - try node.ref._withUnsafeGuaranteedRef { storage in - try storage.withUnsafeMutablePointers { header, elements in - try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: true)) + unsafe try node.ref._withUnsafeGuaranteedRef { storage in + unsafe try storage.withUnsafeMutablePointers { header, elements in + unsafe try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: true)) } } } @@ -104,8 +107,8 @@ extension _HashNode.UnsafeHandle { _ storage: _RawHashStorage, _ body: (Self) throws -> R ) rethrows -> R { - try storage.withUnsafeMutablePointers { header, elements in - try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: true)) + unsafe try storage.withUnsafeMutablePointers { header, elements in + unsafe try body(Self(header, UnsafeMutableRawPointer(elements), isMutable: true)) } } } @@ -114,184 +117,188 @@ extension _HashNode.UnsafeHandle { @inlinable @inline(__always) internal var itemMap: _Bitmap { get { - _header.pointee.itemMap + unsafe _header.pointee.itemMap } nonmutating set { assertMutable() - _header.pointee.itemMap = newValue + unsafe _header.pointee.itemMap = newValue } } @inlinable @inline(__always) internal var childMap: _Bitmap { get { - _header.pointee.childMap + unsafe _header.pointee.childMap } nonmutating set { assertMutable() - _header.pointee.childMap = newValue + unsafe _header.pointee.childMap = newValue } } @inlinable @inline(__always) internal var byteCapacity: Int { - _header.pointee.byteCapacity + unsafe _header.pointee.byteCapacity } @inlinable @inline(__always) internal var bytesFree: Int { - get { _header.pointee.bytesFree } + get { + unsafe _header.pointee.bytesFree + } nonmutating set { assertMutable() - _header.pointee.bytesFree = newValue + unsafe _header.pointee.bytesFree = newValue } } @inlinable @inline(__always) internal var isCollisionNode: Bool { - _header.pointee.isCollisionNode + unsafe _header.pointee.isCollisionNode } @inlinable @inline(__always) internal var collisionCount: Int { - get { _header.pointee.collisionCount } + get { + unsafe _header.pointee.collisionCount + } nonmutating set { assertMutable() - _header.pointee.collisionCount = newValue + unsafe _header.pointee.collisionCount = newValue } } @inlinable @inline(__always) internal var collisionHash: _Hash { get { - assert(isCollisionNode) - return _memory.load(as: _Hash.self) + assert(unsafe isCollisionNode) + return unsafe _memory.load(as: _Hash.self) } nonmutating set { assertMutable() - assert(isCollisionNode) - _memory.storeBytes(of: newValue, as: _Hash.self) + assert(unsafe isCollisionNode) + unsafe _memory.storeBytes(of: newValue, as: _Hash.self) } } @inlinable @inline(__always) internal var _childrenStart: UnsafeMutablePointer<_HashNode> { - _memory.assumingMemoryBound(to: _HashNode.self) + unsafe _memory.assumingMemoryBound(to: _HashNode.self) } @inlinable @inline(__always) internal var hasChildren: Bool { - _header.pointee.hasChildren + unsafe _header.pointee.hasChildren } @inlinable @inline(__always) internal var childCount: Int { - _header.pointee.childCount + unsafe _header.pointee.childCount } @inlinable internal func childBucket(at slot: _HashSlot) -> _Bucket { - guard !isCollisionNode else { return .invalid } - return childMap.bucket(at: slot) + guard unsafe !isCollisionNode else { return .invalid } + return unsafe childMap.bucket(at: slot) } @inlinable @inline(__always) internal var childrenEndSlot: _HashSlot { - _header.pointee.childrenEndSlot + unsafe _header.pointee.childrenEndSlot } @inlinable internal var children: UnsafeMutableBufferPointer<_HashNode> { - UnsafeMutableBufferPointer(start: _childrenStart, count: childCount) + unsafe UnsafeMutableBufferPointer(start: _childrenStart, count: childCount) } @inlinable internal func childPtr(at slot: _HashSlot) -> UnsafeMutablePointer<_HashNode> { - assert(slot.value < childCount) - return _childrenStart + slot.value + assert(unsafe slot.value < childCount) + return unsafe _childrenStart + slot.value } @inlinable internal subscript(child slot: _HashSlot) -> _HashNode { unsafeAddress { - UnsafePointer(childPtr(at: slot)) + unsafe UnsafePointer(childPtr(at: slot)) } nonmutating unsafeMutableAddress { assertMutable() - return childPtr(at: slot) + return unsafe childPtr(at: slot) } } @inlinable internal var _itemsEnd: UnsafeMutablePointer { - (_memory + _header.pointee.byteCapacity) + unsafe (_memory + _header.pointee.byteCapacity) .assumingMemoryBound(to: Element.self) } @inlinable @inline(__always) internal var hasItems: Bool { - _header.pointee.hasItems + unsafe _header.pointee.hasItems } @inlinable @inline(__always) internal var itemCount: Int { - _header.pointee.itemCount + unsafe _header.pointee.itemCount } @inlinable internal func itemBucket(at slot: _HashSlot) -> _Bucket { - guard !isCollisionNode else { return .invalid } - return itemMap.bucket(at: slot) + guard unsafe !isCollisionNode else { return .invalid } + return unsafe itemMap.bucket(at: slot) } @inlinable @inline(__always) internal var itemsEndSlot: _HashSlot { - _header.pointee.itemsEndSlot + unsafe _header.pointee.itemsEndSlot } @inlinable internal var reverseItems: UnsafeMutableBufferPointer { - let c = itemCount - return UnsafeMutableBufferPointer(start: _itemsEnd - c, count: c) + let c = unsafe itemCount + return unsafe UnsafeMutableBufferPointer(start: _itemsEnd - c, count: c) } @inlinable internal func itemPtr(at slot: _HashSlot) -> UnsafeMutablePointer { - assert(slot.value <= itemCount) - return _itemsEnd.advanced(by: -1 &- slot.value) + assert(unsafe slot.value <= itemCount) + return unsafe _itemsEnd.advanced(by: -1 &- slot.value) } @inlinable internal subscript(item slot: _HashSlot) -> Element { unsafeAddress { - UnsafePointer(itemPtr(at: slot)) + unsafe UnsafePointer(itemPtr(at: slot)) } nonmutating unsafeMutableAddress { assertMutable() - return itemPtr(at: slot) + return unsafe itemPtr(at: slot) } } @inlinable internal func clear() { assertMutable() - _header.pointee.clear() + unsafe _header.pointee.clear() } } extension _HashNode.UnsafeHandle { @inlinable internal var hasSingletonItem: Bool { - _header.pointee.hasSingletonItem + unsafe _header.pointee.hasSingletonItem } @inlinable internal var hasSingletonChild: Bool { - _header.pointee.hasSingletonChild + unsafe _header.pointee.hasSingletonChild } @inlinable internal var isAtrophiedNode: Bool { - hasSingletonChild && self[child: .zero].isCollisionNode + unsafe hasSingletonChild && self[child: .zero].isCollisionNode } } diff --git a/Sources/HashTreeCollections/HashNode/_HashNode.swift b/Sources/HashTreeCollections/HashNode/_HashNode.swift index f7fc74f3..f02dd6e0 100644 --- a/Sources/HashTreeCollections/HashNode/_HashNode.swift +++ b/Sources/HashTreeCollections/HashNode/_HashNode.swift @@ -38,6 +38,7 @@ /// items map. @usableFromInline @frozen +@safe internal struct _HashNode { // Warning: This struct must be kept layout-compatible with _RawHashNode. // Do not add any new stored properties to this type. @@ -72,29 +73,33 @@ extension _HashNode { extension _HashNode { @inlinable @inline(__always) + @unsafe internal var unmanaged: _UnmanagedHashNode { - _UnmanagedHashNode(raw.storage) + unsafe _UnmanagedHashNode(raw.storage) } @inlinable @inline(__always) + @unsafe internal func isIdentical(to other: _UnmanagedHashNode) -> Bool { - raw.isIdentical(to: other) + unsafe raw.isIdentical(to: other) } } extension _HashNode { @inlinable @inline(__always) + @unsafe internal func read( _ body: (UnsafeHandle) throws -> R ) rethrows -> R { - try UnsafeHandle.read(raw.storage, body) + unsafe try UnsafeHandle.read(raw.storage, body) } @inlinable @inline(__always) + @unsafe internal mutating func update( _ body: (UnsafeHandle) throws -> R ) rethrows -> R { - try UnsafeHandle.update(raw.storage, body) + unsafe try UnsafeHandle.update(raw.storage, body) } } @@ -103,27 +108,27 @@ extension _HashNode { extension _HashNode { @inlinable internal var isCollisionNode: Bool { - self.read { $0.isCollisionNode } + unsafe self.read { unsafe $0.isCollisionNode } } @inlinable internal var collisionHash: _Hash { - self.read { $0.collisionHash } + unsafe self.read { unsafe $0.collisionHash } } @inlinable internal var hasSingletonItem: Bool { - self.read { $0.hasSingletonItem } + unsafe self.read { unsafe $0.hasSingletonItem } } @inlinable internal var hasSingletonChild: Bool { - self.read { $0.hasSingletonChild } + unsafe self.read { unsafe $0.hasSingletonChild } } @inlinable internal var isAtrophied: Bool { - self.read { $0.isAtrophiedNode } + unsafe self.read { unsafe $0.isAtrophiedNode } } } @@ -134,7 +139,7 @@ extension _HashNode { // memory address of the root node is a reasonable substitute. // Alternatively, we could use a per-thread counter along with a thread // id, or some sort of global banks of atomic integer counters. - let address = Unmanaged.passUnretained(raw.storage).toOpaque() + let address = unsafe Unmanaged.passUnretained(raw.storage).toOpaque() return UInt(bitPattern: address) } } diff --git a/Sources/HashTreeCollections/HashNode/_HashStack.swift b/Sources/HashTreeCollections/HashNode/_HashStack.swift index 630f99b9..258dc59b 100644 --- a/Sources/HashTreeCollections/HashNode/_HashStack.swift +++ b/Sources/HashTreeCollections/HashNode/_HashStack.swift @@ -86,16 +86,16 @@ internal struct _HashStack { assert(level < _count) return withUnsafeBytes(of: &_contents) { buffer in // Homogeneous tuples are layout compatible with their element type - let start = buffer.baseAddress!.assumingMemoryBound(to: Element.self) - return start[Int(truncatingIfNeeded: level)] + let start = unsafe buffer.baseAddress!.assumingMemoryBound(to: Element.self) + return unsafe start[Int(truncatingIfNeeded: level)] } } set { assert(level < capacity) withUnsafeMutableBytes(of: &_contents) { buffer in // Homogeneous tuples are layout compatible with their element type - let start = buffer.baseAddress!.assumingMemoryBound(to: Element.self) - start[Int(truncatingIfNeeded: level)] = newValue + let start = unsafe buffer.baseAddress!.assumingMemoryBound(to: Element.self) + unsafe start[Int(truncatingIfNeeded: level)] = newValue } } } diff --git a/Sources/HashTreeCollections/HashNode/_HashTreeIterator.swift b/Sources/HashTreeCollections/HashNode/_HashTreeIterator.swift index 8c4a4e3e..fb930e5d 100644 --- a/Sources/HashTreeCollections/HashNode/_HashTreeIterator.swift +++ b/Sources/HashTreeCollections/HashNode/_HashTreeIterator.swift @@ -13,121 +13,132 @@ @usableFromInline @frozen +@unsafe internal struct _HashTreeIterator { @usableFromInline + @unsafe internal struct _Opaque { + @safe internal var ancestorSlots: _AncestorHashSlots + @unsafe internal var ancestorNodes: _HashStack<_UnmanagedHashNode> + @safe internal var level: _HashLevel + @safe internal var isAtEnd: Bool @usableFromInline @_effects(releasenone) internal init(_ root: _UnmanagedHashNode) { self.ancestorSlots = .empty - self.ancestorNodes = _HashStack(filledWith: root) + unsafe self.ancestorNodes = _HashStack(filledWith: root) self.level = .top self.isAtEnd = false } } @usableFromInline + @unsafe internal let root: _RawHashStorage @usableFromInline + @unsafe internal var node: _UnmanagedHashNode @usableFromInline + @safe internal var slot: _HashSlot @usableFromInline + @safe internal var endSlot: _HashSlot @usableFromInline + @unsafe internal var _o: _Opaque @usableFromInline @_effects(releasenone) internal init(root: __shared _RawHashNode) { - self.root = root.storage - self.node = root.unmanaged + unsafe self.root = root.storage + unsafe self.node = root.unmanaged self.slot = .zero - self.endSlot = node.itemsEndSlot - self._o = _Opaque(self.node) + self.endSlot = unsafe node.itemsEndSlot + unsafe self._o = _Opaque(self.node) - if node.hasItems { return } - if node.hasChildren { - _descendToLeftmostItem(ofChildAtSlot: .zero) + if unsafe node.hasItems { return } + if unsafe node.hasChildren { + unsafe _descendToLeftmostItem(ofChildAtSlot: .zero) } else { - self._o.isAtEnd = true + unsafe self._o.isAtEnd = true } } } -extension _HashTreeIterator: IteratorProtocol { +extension _HashTreeIterator: @unsafe IteratorProtocol { @inlinable internal mutating func next( ) -> (node: _UnmanagedHashNode, slot: _HashSlot)? { guard slot < endSlot else { - return _next() + return unsafe _next() } defer { slot = slot.next() } - return (node, slot) + return unsafe (node, slot) } @usableFromInline @_effects(releasenone) internal mutating func _next( ) -> (node: _UnmanagedHashNode, slot: _HashSlot)? { - if _o.isAtEnd { return nil } - if node.hasChildren { - _descendToLeftmostItem(ofChildAtSlot: .zero) + if unsafe _o.isAtEnd { return nil } + if unsafe node.hasChildren { + unsafe _descendToLeftmostItem(ofChildAtSlot: .zero) slot = slot.next() - return (node, .zero) + return unsafe (node, .zero) } - while !_o.level.isAtRoot { - let nextChild = _ascend().next() - if nextChild < node.childrenEndSlot { - _descendToLeftmostItem(ofChildAtSlot: nextChild) + while unsafe !_o.level.isAtRoot { + let nextChild = unsafe _ascend().next() + if unsafe nextChild < node.childrenEndSlot { + unsafe _descendToLeftmostItem(ofChildAtSlot: nextChild) slot = slot.next() - return (node, .zero) + return unsafe (node, .zero) } } // At end - endSlot = node.itemsEndSlot + endSlot = unsafe node.itemsEndSlot slot = endSlot - _o.isAtEnd = true + unsafe _o.isAtEnd = true return nil } } extension _HashTreeIterator { internal mutating func _descend(toChildSlot childSlot: _HashSlot) { - assert(childSlot < node.childrenEndSlot) - _o.ancestorSlots[_o.level] = childSlot - _o.ancestorNodes.push(node) - _o.level = _o.level.descend() - node = node.unmanagedChild(at: childSlot) + assert(unsafe childSlot < node.childrenEndSlot) + unsafe _o.ancestorSlots[_o.level] = childSlot + unsafe _o.ancestorNodes.push(node) + unsafe _o.level = _o.level.descend() + unsafe node = node.unmanagedChild(at: childSlot) slot = .zero - endSlot = node.itemsEndSlot + unsafe endSlot = node.itemsEndSlot } internal mutating func _ascend() -> _HashSlot { - assert(!_o.level.isAtRoot) - node = _o.ancestorNodes.pop() - _o.level = _o.level.ascend() - let childSlot = _o.ancestorSlots[_o.level] - _o.ancestorSlots.clear(_o.level) + assert(unsafe !_o.level.isAtRoot) + unsafe node = _o.ancestorNodes.pop() + unsafe _o.level = _o.level.ascend() + let childSlot = unsafe _o.ancestorSlots[_o.level] + unsafe _o.ancestorSlots.clear(_o.level) return childSlot } internal mutating func _descendToLeftmostItem( ofChildAtSlot childSlot: _HashSlot ) { - _descend(toChildSlot: childSlot) + unsafe _descend(toChildSlot: childSlot) while endSlot == .zero { - assert(node.hasChildren) - _descend(toChildSlot: .zero) + assert(unsafe node.hasChildren) + unsafe _descend(toChildSlot: .zero) } } } diff --git a/Sources/HashTreeCollections/HashNode/_HashTreeStatistics.swift b/Sources/HashTreeCollections/HashNode/_HashTreeStatistics.swift index d17987ea..4d918179 100644 --- a/Sources/HashTreeCollections/HashNode/_HashTreeStatistics.swift +++ b/Sources/HashTreeCollections/HashNode/_HashTreeStatistics.swift @@ -95,35 +95,35 @@ extension _HashNode { // The empty singleton does not count as a node and occupies no space. if self.raw.storage === _emptySingleton { return } - read { + unsafe read { stats.nodeCount += 1 - stats.itemCount += $0.itemCount + stats.itemCount += unsafe $0.itemCount if isCollisionNode { stats.collisionNodeCount += 1 - stats.collisionCount += $0.itemCount - stats._collisionChainCount += $0.itemCount * ($0.itemCount - 1) / 2 + stats.collisionCount += unsafe $0.itemCount + stats._collisionChainCount += unsafe $0.itemCount * ($0.itemCount - 1) / 2 } let keyStride = MemoryLayout.stride let valueStride = MemoryLayout.stride stats.maxItemDepth = Swift.max(stats.maxItemDepth, level.depth) - stats._sumItemDepth += (level.depth + 1) * $0.itemCount - stats.capacityBytes += $0.byteCapacity - stats.freeBytes += $0.bytesFree - stats.itemBytes += $0.itemCount * (keyStride + valueStride) - stats.childBytes += $0.childCount * MemoryLayout<_RawHashNode>.stride + stats._sumItemDepth += unsafe (level.depth + 1) * $0.itemCount + stats.capacityBytes += unsafe $0.byteCapacity + stats.freeBytes += unsafe $0.bytesFree + stats.itemBytes += unsafe $0.itemCount * (keyStride + valueStride) + stats.childBytes += unsafe $0.childCount * MemoryLayout<_RawHashNode>.stride let objectHeaderSize = 2 * MemoryLayout.stride // Note: for simplicity, we assume that there is no padding between // the object header and the storage header. - let start = _getUnsafePointerToStoredProperties(self.raw.storage) - let end = $0._memory + $0.byteCapacity - stats.grossBytes += objectHeaderSize + (end - start) + let start = unsafe _getUnsafePointerToStoredProperties(self.raw.storage) + let end = unsafe $0._memory + $0.byteCapacity + stats.grossBytes += unsafe objectHeaderSize + (end - start) - for child in $0.children { + for unsafe child in unsafe $0.children { child.gatherStatistics(level.descend(), &stats) } } diff --git a/Sources/HashTreeCollections/HashNode/_RawHashNode+UnsafeHandle.swift b/Sources/HashTreeCollections/HashNode/_RawHashNode+UnsafeHandle.swift index 624f9bc4..bf34b255 100644 --- a/Sources/HashTreeCollections/HashNode/_RawHashNode+UnsafeHandle.swift +++ b/Sources/HashTreeCollections/HashNode/_RawHashNode+UnsafeHandle.swift @@ -26,6 +26,7 @@ extension _RawHashNode { /// by them) do not escape the closure call that received them. @usableFromInline @frozen + @unsafe internal struct UnsafeHandle { @usableFromInline internal let _header: UnsafePointer<_HashNodeHeader> @@ -38,8 +39,8 @@ extension _RawHashNode { _ header: UnsafePointer<_HashNodeHeader>, _ memory: UnsafeRawPointer ) { - self._header = header - self._memory = memory + unsafe self._header = header + unsafe self._memory = memory } } } @@ -50,9 +51,9 @@ extension _RawHashNode.UnsafeHandle { _ node: _UnmanagedHashNode, _ body: (Self) throws -> R ) rethrows -> R { - try node.ref._withUnsafeGuaranteedRef { storage in - try storage.withUnsafeMutablePointers { header, elements in - try body(Self(header, UnsafeRawPointer(elements))) + unsafe try node.ref._withUnsafeGuaranteedRef { storage in + unsafe try storage.withUnsafeMutablePointers { header, elements in + unsafe try body(Self(header, UnsafeRawPointer(elements))) } } } @@ -61,58 +62,58 @@ extension _RawHashNode.UnsafeHandle { extension _RawHashNode.UnsafeHandle { @inline(__always) internal var isCollisionNode: Bool { - _header.pointee.isCollisionNode + unsafe _header.pointee.isCollisionNode } @inline(__always) internal var collisionHash: _Hash { - assert(isCollisionNode) - return _memory.load(as: _Hash.self) + assert(unsafe isCollisionNode) + return unsafe _memory.load(as: _Hash.self) } @inline(__always) internal var hasChildren: Bool { - _header.pointee.hasChildren + unsafe _header.pointee.hasChildren } @inline(__always) internal var childCount: Int { - _header.pointee.childCount + unsafe _header.pointee.childCount } @inline(__always) internal var childrenEndSlot: _HashSlot { - _header.pointee.childrenEndSlot + unsafe _header.pointee.childrenEndSlot } @inline(__always) internal var hasItems: Bool { - _header.pointee.hasItems + unsafe _header.pointee.hasItems } @inline(__always) internal var itemCount: Int { - _header.pointee.itemCount + unsafe _header.pointee.itemCount } @inline(__always) internal var itemsEndSlot: _HashSlot { - _header.pointee.itemsEndSlot + unsafe _header.pointee.itemsEndSlot } @inline(__always) internal var _childrenStart: UnsafePointer<_RawHashNode> { - _memory.assumingMemoryBound(to: _RawHashNode.self) + unsafe _memory.assumingMemoryBound(to: _RawHashNode.self) } internal subscript(child slot: _HashSlot) -> _RawHashNode { unsafeAddress { - assert(slot < childrenEndSlot) - return _childrenStart + slot.value + assert(unsafe slot < childrenEndSlot) + return unsafe _childrenStart + slot.value } } internal var children: UnsafeBufferPointer<_RawHashNode> { - UnsafeBufferPointer(start: _childrenStart, count: childCount) + unsafe UnsafeBufferPointer(start: _childrenStart, count: childCount) } } diff --git a/Sources/HashTreeCollections/HashNode/_RawHashNode.swift b/Sources/HashTreeCollections/HashNode/_RawHashNode.swift index 99755e53..fb1c43a9 100644 --- a/Sources/HashTreeCollections/HashNode/_RawHashNode.swift +++ b/Sources/HashTreeCollections/HashNode/_RawHashNode.swift @@ -19,6 +19,7 @@ /// `distance(from:to:)`, `index(_:offsetBy:)` in non-generic code. @usableFromInline @frozen +@safe internal struct _RawHashNode { @usableFromInline internal var storage: _RawHashStorage @@ -35,22 +36,24 @@ internal struct _RawHashNode { extension _RawHashNode { @inline(__always) + @unsafe internal func read(_ body: (UnsafeHandle) -> R) -> R { - storage.withUnsafeMutablePointers { header, elements in - body(UnsafeHandle(header, UnsafeRawPointer(elements))) + unsafe storage.withUnsafeMutablePointers { header, elements in + unsafe body(UnsafeHandle(header, UnsafeRawPointer(elements))) } } } extension _RawHashNode { @inlinable @inline(__always) + @unsafe internal var unmanaged: _UnmanagedHashNode { - _UnmanagedHashNode(storage) + unsafe _UnmanagedHashNode(storage) } @inlinable @inline(__always) internal func isIdentical(to other: _UnmanagedHashNode) -> Bool { - other.ref.toOpaque() == Unmanaged.passUnretained(storage).toOpaque() + unsafe other.ref.toOpaque() == Unmanaged.passUnretained(storage).toOpaque() } } @@ -58,18 +61,18 @@ extension _RawHashNode { @usableFromInline internal func validatePath(_ path: _UnsafePath) { var l = _HashLevel.top - var n = self.unmanaged + var n = unsafe self.unmanaged while l < path.level { let slot = path.ancestors[l] - precondition(slot < n.childrenEndSlot) - n = n.unmanagedChild(at: slot) + precondition(unsafe slot < n.childrenEndSlot) + unsafe n = n.unmanagedChild(at: slot) l = l.descend() } - precondition(n == path.node) + precondition(unsafe n == path.node) if path._isItem { - precondition(path.nodeSlot < n.itemsEndSlot) + precondition(unsafe path.nodeSlot < n.itemsEndSlot) } else { - precondition(path.nodeSlot <= n.childrenEndSlot) + precondition(unsafe path.nodeSlot <= n.childrenEndSlot) } } } diff --git a/Sources/HashTreeCollections/HashNode/_UnmanagedHashNode.swift b/Sources/HashTreeCollections/HashNode/_UnmanagedHashNode.swift index 9bc617dc..f28f14de 100644 --- a/Sources/HashTreeCollections/HashNode/_UnmanagedHashNode.swift +++ b/Sources/HashTreeCollections/HashNode/_UnmanagedHashNode.swift @@ -23,13 +23,14 @@ import InternalCollectionsUtilities /// `_UnmanagedHashNode`. Doing so results in undefined behavior. @usableFromInline @frozen +@unsafe internal struct _UnmanagedHashNode { @usableFromInline internal var ref: Unmanaged<_RawHashStorage> @inlinable @inline(__always) internal init(_ storage: _RawHashStorage) { - self.ref = .passUnretained(storage) + unsafe self.ref = .passUnretained(storage) } } @@ -42,68 +43,69 @@ extension _UnmanagedHashNode: Equatable { /// a newly created node.) @inlinable internal static func ==(left: Self, right: Self) -> Bool { - left.ref.toOpaque() == right.ref.toOpaque() + unsafe left.ref.toOpaque() == right.ref.toOpaque() } } extension _UnmanagedHashNode: CustomStringConvertible { @usableFromInline internal var description: String { - _addressString(for: ref.toOpaque()) + _addressString(for: unsafe ref.toOpaque()) } } extension _UnmanagedHashNode { @inlinable @inline(__always) + @unsafe internal func withRaw(_ body: (_RawHashStorage) -> R) -> R { - ref._withUnsafeGuaranteedRef(body) + unsafe ref._withUnsafeGuaranteedRef(body) } @inline(__always) internal func read(_ body: (_RawHashNode.UnsafeHandle) -> R) -> R { - ref._withUnsafeGuaranteedRef { storage in - storage.withUnsafeMutablePointers { header, elements in - body(_RawHashNode.UnsafeHandle(header, UnsafeRawPointer(elements))) + unsafe ref._withUnsafeGuaranteedRef { storage in + unsafe storage.withUnsafeMutablePointers { header, elements in + unsafe body(_RawHashNode.UnsafeHandle(header, UnsafeRawPointer(elements))) } } } @inlinable internal var hasItems: Bool { - withRaw { $0.header.hasItems } + unsafe withRaw { $0.header.hasItems } } @inlinable internal var hasChildren: Bool { - withRaw { $0.header.hasChildren } + unsafe withRaw { $0.header.hasChildren } } @inlinable internal var itemCount: Int { - withRaw { $0.header.itemCount } + unsafe withRaw { $0.header.itemCount } } @inlinable internal var childCount: Int { - withRaw { $0.header.childCount } + unsafe withRaw { $0.header.childCount } } @inlinable internal var itemsEndSlot: _HashSlot { - withRaw { _HashSlot($0.header.itemCount) } + unsafe withRaw { _HashSlot($0.header.itemCount) } } @inlinable internal var childrenEndSlot: _HashSlot { - withRaw { _HashSlot($0.header.childCount) } + unsafe withRaw { _HashSlot($0.header.childCount) } } @inlinable internal func unmanagedChild(at slot: _HashSlot) -> Self { - withRaw { raw in + unsafe withRaw { raw in assert(slot.value < raw.header.childCount) - return raw.withUnsafeMutablePointerToElements { p in - Self(p[slot.value].storage) + return unsafe raw.withUnsafeMutablePointerToElements { p in + unsafe Self(p[slot.value].storage) } } } diff --git a/Sources/HashTreeCollections/HashNode/_UnsafePath.swift b/Sources/HashTreeCollections/HashNode/_UnsafePath.swift index a31faf0c..f8abca82 100644 --- a/Sources/HashTreeCollections/HashNode/_UnsafePath.swift +++ b/Sources/HashTreeCollections/HashNode/_UnsafePath.swift @@ -37,27 +37,32 @@ /// would considerably embiggen the size of the path construct.) @usableFromInline @frozen +@unsafe internal struct _UnsafePath { @usableFromInline + @safe internal var ancestors: _AncestorHashSlots @usableFromInline internal var node: _UnmanagedHashNode @usableFromInline + @safe internal var nodeSlot: _HashSlot @usableFromInline + @safe internal var level: _HashLevel @usableFromInline + @safe internal var _isItem: Bool @inlinable internal init(root: __shared _RawHashNode) { self.level = .top self.ancestors = .empty - self.node = root.unmanaged + unsafe self.node = root.unmanaged self.nodeSlot = .zero self._isItem = root.storage.header.hasItems } @@ -70,10 +75,10 @@ extension _UnsafePath { _ node: _UnmanagedHashNode, childSlot: _HashSlot ) { - assert(childSlot < node.childrenEndSlot) + assert(unsafe childSlot < node.childrenEndSlot) self.level = level self.ancestors = ancestors - self.node = node + unsafe self.node = node self.nodeSlot = childSlot self._isItem = false } @@ -85,10 +90,10 @@ extension _UnsafePath { _ node: _UnmanagedHashNode, itemSlot: _HashSlot ) { - assert(itemSlot < node.itemsEndSlot) + assert(unsafe itemSlot < node.itemsEndSlot) self.level = level self.ancestors = ancestors - self.node = node + unsafe self.node = node self.nodeSlot = itemSlot self._isItem = true } @@ -163,13 +168,13 @@ extension _UnsafePath: CustomStringConvertible { d += ".\(self.ancestors[l])" l = l.descend() } - if isPlaceholder { + if unsafe isPlaceholder { d += ".end[\(self.nodeSlot)]" } else if isOnItem { d += "[\(self.nodeSlot)]" - } else if isOnChild { + } else if unsafe isOnChild { d += ".\(self.nodeSlot)" - } else if isOnNodeEnd { + } else if unsafe isOnNodeEnd { d += ".end(\(self.nodeSlot))" } return d @@ -183,6 +188,7 @@ extension _UnsafePath { /// - Note: It is undefined behavior to call this on a path that is no longer /// valid. @inlinable @inline(__always) + @safe internal var isOnItem: Bool { // Note: this may be true even if nodeSlot == itemCount (insertion paths). _isItem @@ -197,7 +203,7 @@ extension _UnsafePath { /// valid. @inlinable internal var isPlaceholder: Bool { - _isItem && nodeSlot.value == node.itemCount + unsafe _isItem && nodeSlot.value == node.itemCount } /// Returns true if this path addresses a node in the tree; otherwise returns @@ -207,7 +213,7 @@ extension _UnsafePath { /// valid. @inlinable internal var isOnChild: Bool { - !_isItem && nodeSlot.value < node.childCount + unsafe !_isItem && nodeSlot.value < node.childCount } /// Returns true if this path addresses an empty slot within a node in a tree; @@ -217,7 +223,7 @@ extension _UnsafePath { /// valid. @inlinable internal var isOnNodeEnd: Bool { - !_isItem && nodeSlot.value == node.childCount + unsafe !_isItem && nodeSlot.value == node.childCount } } @@ -229,8 +235,8 @@ extension _UnsafePath { /// valid. @inlinable internal var currentChild: _UnmanagedHashNode { - assert(isOnChild) - return node.unmanagedChild(at: nodeSlot) + assert(unsafe isOnChild) + return unsafe node.unmanagedChild(at: nodeSlot) } /// Returns the chid slot in this path corresponding to the specified level. @@ -264,7 +270,7 @@ extension _UnsafePath { // As a special exception, this allows slot to equal the item count. // This can happen for paths that address the position a new item might be // inserted later. - assert(slot <= node.itemsEndSlot) + assert(unsafe slot <= node.itemsEndSlot) nodeSlot = slot _isItem = true } @@ -278,7 +284,7 @@ extension _UnsafePath { internal mutating func selectChild(at slot: _HashSlot) { // As a special exception, this allows slot to equal the child count. // This is equivalent to a call to `selectEnd()`. - assert(slot <= node.childrenEndSlot) + assert(unsafe slot <= node.childrenEndSlot) nodeSlot = slot _isItem = false } @@ -290,7 +296,7 @@ extension _UnsafePath { @usableFromInline @_effects(releasenone) internal mutating func selectEnd() { - nodeSlot = node.childrenEndSlot + nodeSlot = unsafe node.childrenEndSlot _isItem = false } @@ -303,10 +309,10 @@ extension _UnsafePath { /// valid. @inlinable internal mutating func descend() { - self.node = currentChild + unsafe self.node = currentChild self.ancestors[level] = nodeSlot self.nodeSlot = .zero - self._isItem = node.hasItems + self._isItem = unsafe node.hasItems self.level = level.descend() } @@ -321,12 +327,12 @@ extension _UnsafePath { internal mutating func descendToChild( _ child: _UnmanagedHashNode, at slot: _HashSlot ) { - assert(slot < node.childrenEndSlot) - assert(child == node.unmanagedChild(at: slot)) - self.node = child + assert(unsafe slot < node.childrenEndSlot) + assert(unsafe child == node.unmanagedChild(at: slot)) + unsafe self.node = child self.ancestors[level] = slot self.nodeSlot = .zero - self._isItem = node.hasItems + self._isItem = unsafe node.hasItems self.level = level.descend() } @@ -336,7 +342,7 @@ extension _UnsafePath { guard level != self.level else { return } assert(level < self.level) self.level = level - self.node = ancestor + unsafe self.node = ancestor self.nodeSlot = ancestors[level] self.ancestors.clear(atOrBelow: level) self._isItem = false @@ -356,19 +362,19 @@ extension _UnsafePath { ) -> Bool { if self.level.isAtRoot { return false } var best: _UnsafePath? = nil - var n = root.unmanaged + var n = unsafe root.unmanaged var l: _HashLevel = .top while l < self.level { let slot = self.ancestors[l] - if test(n, slot) { - best = _UnsafePath( + if unsafe test(n, slot) { + unsafe best = _UnsafePath( l, self.ancestors.truncating(to: l), n, childSlot: slot) } - n = n.unmanagedChild(at: slot) + unsafe n = n.unmanagedChild(at: slot) l = l.descend() } - guard let best = best else { return false } - self = best + guard let best = unsafe best else { return false } + unsafe self = best return true } } @@ -384,7 +390,7 @@ extension _UnsafePath { mutating func selectNextItem() -> Bool { assert(isOnItem) nodeSlot = nodeSlot.next() - if nodeSlot < node.itemsEndSlot { return true } + if unsafe nodeSlot < node.itemsEndSlot { return true } nodeSlot = .zero _isItem = false return false @@ -398,7 +404,7 @@ extension _UnsafePath { /// valid. mutating func selectNextChild() -> Bool { assert(!isOnItem) - let childrenEndSlot = node.childrenEndSlot + let childrenEndSlot = unsafe node.childrenEndSlot guard nodeSlot < childrenEndSlot else { return false } nodeSlot = nodeSlot.next() return nodeSlot < childrenEndSlot @@ -416,8 +422,8 @@ extension _UnsafePath { @usableFromInline @_effects(releasenone) internal mutating func descendToLeftMostItem() { - while isOnChild { - descend() + while unsafe isOnChild { + unsafe descend() } } @@ -429,16 +435,16 @@ extension _UnsafePath { /// - Note: It is undefined behavior to call this on a path that is no longer /// valid. internal mutating func descendToRightMostItem() { - assert(isOnChild) + assert(unsafe isOnChild) while true { - descend() - let childrenEndSlot = node.childrenEndSlot + unsafe descend() + let childrenEndSlot = unsafe node.childrenEndSlot guard childrenEndSlot > .zero else { break } - selectChild(at: childrenEndSlot.previous()) + unsafe selectChild(at: childrenEndSlot.previous()) } - let itemsEndSlot = node.itemsEndSlot + let itemsEndSlot = unsafe node.itemsEndSlot assert(itemsEndSlot > .zero) - selectItem(at: itemsEndSlot.previous()) + unsafe selectItem(at: itemsEndSlot.previous()) } /// Find the next item in a preorder walk in the tree following the currently @@ -448,23 +454,23 @@ extension _UnsafePath { @_effects(releasenone) internal mutating func findSuccessorItem(under root: _RawHashNode) -> Bool { guard isOnItem else { return false } - if selectNextItem() { return true } - if node.hasChildren { - descendToLeftMostItem() + if unsafe selectNextItem() { return true } + if unsafe node.hasChildren { + unsafe descendToLeftMostItem() assert(isOnItem) return true } - if ascendToNearestAncestor( - under: root, where: { $1.next() < $0.childrenEndSlot } + if unsafe ascendToNearestAncestor( + under: root, where: { unsafe $1.next() < $0.childrenEndSlot } ) { - let r = selectNextChild() + let r = unsafe selectNextChild() assert(r) - descendToLeftMostItem() + unsafe descendToLeftMostItem() assert(isOnItem) return true } - self = _UnsafePath(root: root) - self.selectEnd() + unsafe self = _UnsafePath(root: root) + unsafe self.selectEnd() return true } @@ -476,33 +482,33 @@ extension _UnsafePath { internal mutating func findPredecessorItem(under root: _RawHashNode) -> Bool { switch (isOnItem, nodeSlot > .zero) { case (true, true): - selectItem(at: nodeSlot.previous()) + unsafe selectItem(at: nodeSlot.previous()) return true case (false, true): - selectChild(at: nodeSlot.previous()) - descendToRightMostItem() + unsafe selectChild(at: nodeSlot.previous()) + unsafe descendToRightMostItem() return true case (false, false): - if node.hasItems { - selectItem(at: node.itemsEndSlot.previous()) + if unsafe node.hasItems { + unsafe selectItem(at: node.itemsEndSlot.previous()) return true } case (true, false): break } guard - ascendToNearestAncestor( + unsafe ascendToNearestAncestor( under: root, - where: { $0.hasItems || $1 > .zero }) + where: { unsafe $0.hasItems || $1 > .zero }) else { return false } if nodeSlot > .zero { - selectChild(at: nodeSlot.previous()) - descendToRightMostItem() + unsafe selectChild(at: nodeSlot.previous()) + unsafe descendToRightMostItem() return true } - if node.hasItems { - selectItem(at: node.itemsEndSlot.previous()) + if unsafe node.hasItems { + unsafe selectItem(at: node.itemsEndSlot.previous()) return true } return false @@ -518,14 +524,14 @@ extension _RawHashNode { internal func preorderPosition( _ level: _HashLevel, of path: _UnsafePath ) -> Int { - if path.isOnNodeEnd { return count } + if unsafe path.isOnNodeEnd { return count } assert(path.isOnItem) if level < path.level { - let childSlot = path.childSlot(at: level) - return read { - let prefix = $0.children[.. (found: Bool, remaining: Int) { assert(position >= 0) - let top = node + let top = unsafe node let topLevel = level var stop = false var remaining = position while !stop { - let itemCount = node.itemCount + let itemCount = unsafe node.itemCount if remaining < itemCount { - selectItem(at: _HashSlot(remaining)) + unsafe selectItem(at: _HashSlot(remaining)) return (true, 0) } remaining -= itemCount - node.read { - let children = $0.children + unsafe node.read { + let children = unsafe $0.children for i in children.indices { - let c = children[i].count + let c = unsafe children[i].count if remaining < c { - descendToChild(children[i].unmanaged, at: _HashSlot(i)) + unsafe descendToChild(children[i].unmanaged, at: _HashSlot(i)) return } remaining &-= c @@ -572,8 +578,8 @@ extension _UnsafePath { stop = true } } - ascend(to: top, at: topLevel) - selectEnd() + unsafe ascend(to: top, at: topLevel) + unsafe selectEnd() return (false, remaining) } } @@ -589,65 +595,65 @@ extension _RawHashNode { _ level: _HashLevel, from start: _UnsafePath, to end: _UnsafePath ) -> Int { assert(level.isAtRoot) - if start.isOnNodeEnd { + if unsafe start.isOnNodeEnd { // Shortcut: distance from end. - return preorderPosition(level, of: end) - count + return unsafe preorderPosition(level, of: end) - count } - if end.isOnNodeEnd { + if unsafe end.isOnNodeEnd { // Shortcut: distance to end. - return count - preorderPosition(level, of: start) + return unsafe count - preorderPosition(level, of: start) } assert(start.isOnItem) assert(end.isOnItem) if start.level == end.level, start.ancestors == end.ancestors { // Shortcut: the paths are under the same node. - precondition(start.node == end.node, "Internal index validation error") - return start.currentItemSlot.distance(to: end.currentItemSlot) + precondition(unsafe start.node == end.node, "Internal index validation error") + return unsafe start.currentItemSlot.distance(to: end.currentItemSlot) } if start.level < end.level, start.ancestors.isEqual(to: end.ancestors, upTo: start.level) { // Shortcut: start's node is an ancestor of end's position. - return start.node._distance( + return unsafe start.node._distance( start.level, fromItemAt: start.currentItemSlot, to: end) } if start.ancestors.isEqual(to: end.ancestors, upTo: end.level) { // Shortcut: end's node is an ancestor of start's position. - return -end.node._distance( + return unsafe -end.node._distance( end.level, fromItemAt: end.currentItemSlot, to: start) } // No shortcuts -- the two paths are in different subtrees. // Start descending from the root to look for the closest common // ancestor. - if start < end { - return _distance(level, from: start, to: end) + if unsafe start < end { + return unsafe _distance(level, from: start, to: end) } - return -_distance(level, from: end, to: start) + return unsafe -_distance(level, from: end, to: start) } internal func _distance( _ level: _HashLevel, from start: _UnsafePath, to end: _UnsafePath ) -> Int { - assert(start < end) + assert(unsafe start < end) assert(level < start.level) assert(level < end.level) - let slot1 = start.childSlot(at: level) - let slot2 = end.childSlot(at: level) + let slot1 = unsafe start.childSlot(at: level) + let slot2 = unsafe end.childSlot(at: level) if slot1 == slot2 { - return read { - $0[child: slot1]._distance(level.descend(), from: start, to: end) + return unsafe read { + unsafe $0[child: slot1]._distance(level.descend(), from: start, to: end) } } - return read { - let children = $0.children - let d1 = children[slot1.value] + return unsafe read { + let children = unsafe $0.children + let d1 = unsafe children[slot1.value] .preorderPosition(level.descend(), of: start) - let d2 = children[slot1.value &+ 1 ..< slot2.value] + let d2 = unsafe children[slot1.value &+ 1 ..< slot2.value] .reduce(0) { $0 + $1.count } - let d3 = children[slot2.value] + let d3 = unsafe children[slot2.value] .preorderPosition(level.descend(), of: end) - return (children[slot1.value].count - d1) + d2 + d3 + return unsafe (children[slot1.value].count - d1) + d2 + d3 } } } @@ -656,14 +662,14 @@ extension _UnmanagedHashNode { internal func _distance( _ level: _HashLevel, fromItemAt start: _HashSlot, to end: _UnsafePath ) -> Int { - read { - assert(start < $0.itemsEndSlot) + unsafe read { + assert(unsafe start < $0.itemsEndSlot) assert(level < end.level) - let childSlot = end.childSlot(at: level) - let children = $0.children - let prefix = children[.. _UnsafePath? { - var node = unmanaged + var node = unsafe unmanaged var level: _HashLevel = .top var ancestors: _AncestorHashSlots = .empty while true { - let r = UnsafeHandle.read(node) { $0.find(level, key, hash) } + let r = unsafe UnsafeHandle.read(node) { unsafe $0.find(level, key, hash) } guard let r = r else { break } guard r.descend else { - return _UnsafePath(level, ancestors, node, itemSlot: r.slot) + return unsafe _UnsafePath(level, ancestors, node, itemSlot: r.slot) } - node = node.unmanagedChild(at: r.slot) + unsafe node = node.unmanagedChild(at: r.slot) ancestors[level] = r.slot level = level.descend() } @@ -704,15 +710,15 @@ extension _RawHashNode { limitedBy limit: _UnsafePath ) -> (found: Bool, limited: Bool) { assert(level.isAtRoot) - if (distance > 0 && limit < path) || (distance < 0 && limit > path) { - return (seek(level, &path, offsetBy: distance), false) + if unsafe (distance > 0 && limit < path) || (distance < 0 && limit > path) { + return unsafe (seek(level, &path, offsetBy: distance), false) } var d = distance - guard self._seek(level, &path, offsetBy: &d) else { - path = limit - return (distance >= 0 && d == 0 && limit.isOnNodeEnd, true) + guard unsafe self._seek(level, &path, offsetBy: &d) else { + unsafe path = limit + return unsafe (distance >= 0 && d == 0 && limit.isOnNodeEnd, true) } - let found = ( + let found = unsafe ( distance == 0 || (distance > 0 && path <= limit) || (distance < 0 && path >= limit)) @@ -727,7 +733,7 @@ extension _RawHashNode { offsetBy distance: Int ) -> Bool { var d = distance - if self._seek(level, &path, offsetBy: &d) { + if unsafe self._seek(level, &path, offsetBy: &d) { return true } if distance > 0, d == 0 { // endIndex @@ -747,13 +753,13 @@ extension _RawHashNode { // subtree. So we first figure out the subtree situation, and only start the // recursion if the target is outside of it. assert(level.isAtRoot) - assert(path.isOnItem || path.isOnNodeEnd) + assert(unsafe path.isOnItem || path.isOnNodeEnd) guard distance != 0 else { return true } if distance > 0 { if !path.isOnItem { return false } // Try a local search within the subtree starting at the current node. - let slot = path.currentItemSlot - let r = path.findItemAtPreorderPosition(distance &+ slot.value) + let slot = unsafe path.currentItemSlot + let r = unsafe path.findItemAtPreorderPosition(distance &+ slot.value) if r.found { assert(r.remaining == 0) return true @@ -762,17 +768,17 @@ extension _RawHashNode { distance = r.remaining // Fall back to recursively descending from the root. - return _seekForward(level, by: &distance, fromSubtree: &path) + return unsafe _seekForward(level, by: &distance, fromSubtree: &path) } // distance < 0 - if !path.isOnNodeEnd { + if unsafe !path.isOnNodeEnd { // Shortcut: see if the destination item is within the same node. // (Doing this here allows us to avoid having to descend from the root // down only to figure this out.) let slot = path.nodeSlot distance &+= slot.value if distance >= 0 { - path.selectItem(at: _HashSlot(distance)) + unsafe path.selectItem(at: _HashSlot(distance)) distance = 0 return true } @@ -780,7 +786,7 @@ extension _RawHashNode { // Otherwise we need to visit ancestor nodes to find the item at the right // position. We also do this when we start from the end index -- there // will be no recursion in that case anyway. - return _seekBackward(level, by: &distance, fromSubtree: &path) + return unsafe _seekBackward(level, by: &distance, fromSubtree: &path) } /// Find the item at the given positive distance from the last item within the @@ -793,25 +799,25 @@ extension _RawHashNode { assert(distance >= 0) assert(level <= path.level) guard level < path.level else { - path.selectEnd() + unsafe path.selectEnd() return false } - return read { - let children = $0.children - var i = path.childSlot(at: level).value - if children[i]._seekForward( + return unsafe read { + let children = unsafe $0.children + var i = unsafe path.childSlot(at: level).value + if unsafe children[i]._seekForward( level.descend(), by: &distance, fromSubtree: &path ) { assert(distance == 0) return true } - path.ascend(to: unmanaged, at: level) + unsafe path.ascend(to: unmanaged, at: level) i &+= 1 while i < children.endIndex { - let c = children[i].count + let c = unsafe children[i].count if distance < c { - path.descendToChild(children[i].unmanaged, at: _HashSlot(i)) - let r = path.findItemAtPreorderPosition(distance) + unsafe path.descendToChild(children[i].unmanaged, at: _HashSlot(i)) + let r = unsafe path.findItemAtPreorderPosition(distance) precondition(r.found, "Internal inconsistency: invalid node counts") assert(r.remaining == 0) distance = 0 @@ -820,7 +826,7 @@ extension _RawHashNode { distance &-= c i &+= 1 } - path.selectEnd() + unsafe path.selectEnd() return false } } @@ -835,14 +841,14 @@ extension _RawHashNode { assert(distance < 0) assert(level <= path.level) - return read { - let children = $0.children + return unsafe read { + let children = unsafe $0.children var slot: _HashSlot if level < path.level { // We need to descend to the end of the path before we can start the // search for real. - slot = path.childSlot(at: level) - if children[slot.value]._seekBackward( + slot = unsafe path.childSlot(at: level) + if unsafe children[slot.value]._seekBackward( level.descend(), by: &distance, fromSubtree: &path ) { // A deeper level has found the target item. @@ -850,12 +856,12 @@ extension _RawHashNode { return true } // No luck yet -- ascend to this node and look through preceding data. - path.ascend(to: unmanaged, at: level) - } else if path.isOnNodeEnd { + unsafe path.ascend(to: unmanaged, at: level) + } else if unsafe path.isOnNodeEnd { // When we start from the root's end (the end index), we don't need // to descend before starting to look at previous children. - assert(level.isAtRoot && path.node == self.unmanaged) - slot = path.node.childrenEndSlot + assert(unsafe level.isAtRoot && path.node == self.unmanaged) + slot = unsafe path.node.childrenEndSlot } else { // level == path.level // The outermost caller has already gone as far back as possible // within the original subtree. Return a level higher to actually @@ -866,10 +872,10 @@ extension _RawHashNode { // Look through all preceding children for the target item. while slot > .zero { slot = slot.previous() - let c = children[slot.value].count + let c = unsafe children[slot.value].count if c + distance >= 0 { - path.descendToChild(children[slot.value].unmanaged, at: slot) - let r = path.findItemAtPreorderPosition(c + distance) + unsafe path.descendToChild(children[slot.value].unmanaged, at: slot) + let r = unsafe path.findItemAtPreorderPosition(c + distance) precondition(r.found, "Internal inconsistency: invalid node counts") distance = 0 return true @@ -877,9 +883,9 @@ extension _RawHashNode { distance += c } // See if the target is hiding somewhere in our immediate items. - distance &+= $0.itemCount + distance &+= unsafe $0.itemCount if distance >= 0 { - path.selectItem(at: _HashSlot(distance)) + unsafe path.selectItem(at: _HashSlot(distance)) distance = 0 return true } diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift index 836b9152..01e6537e 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Collection.swift @@ -19,23 +19,27 @@ extension TreeDictionary { /// structure is changed; hence, indices are usually invalidated every time /// the dictionary gets mutated. @frozen + @safe public struct Index { @usableFromInline + @unsafe internal let _root: _UnmanagedHashNode @usableFromInline internal var _version: UInt @usableFromInline + @unsafe internal var _path: _UnsafePath @inlinable @inline(__always) + @unsafe internal init( _root: _UnmanagedHashNode, version: UInt, path: _UnsafePath ) { - self._root = _root + unsafe self._root = _root self._version = version - self._path = path + unsafe self._path = path } } } @@ -53,9 +57,9 @@ extension TreeDictionary.Index: Equatable { @inlinable public static func ==(left: Self, right: Self) -> Bool { precondition( - left._root == right._root && left._version == right._version, + unsafe left._root == right._root && left._version == right._version, "Indices from different dictionary values aren't comparable") - return left._path == right._path + return unsafe left._path == right._path } } @@ -69,9 +73,9 @@ extension TreeDictionary.Index: Comparable { /// - Complexity: O(1) public static func <(left: Self, right: Self) -> Bool { precondition( - left._root == right._root && left._version == right._version, + unsafe left._root == right._root && left._version == right._version, "Indices from different dictionary values aren't comparable") - return left._path < right._path + return unsafe left._path < right._path } } @@ -82,7 +86,7 @@ extension TreeDictionary.Index: Hashable { /// - Complexity: O(1) @inlinable public func hash(into hasher: inout Hasher) { - hasher.combine(_path) + unsafe hasher.combine(_path) } } @@ -90,7 +94,7 @@ extension TreeDictionary.Index: Hashable { extension TreeDictionary.Index: CustomStringConvertible { // A textual representation of this instance. public var description: String { - _path.description + unsafe _path.description } } @@ -125,9 +129,9 @@ extension TreeDictionary: Collection { /// - Complexity: O(1) @inlinable public var startIndex: Index { - var path = _UnsafePath(root: _root.raw) - path.descendToLeftMostItem() - return Index(_root: _root.unmanaged, version: _version, path: path) + var path = unsafe _UnsafePath(root: _root.raw) + unsafe path.descendToLeftMostItem() + return unsafe Index(_root: _root.unmanaged, version: _version, path: path) } /// The collection's "past the end" position—that is, the position one greater @@ -136,14 +140,14 @@ extension TreeDictionary: Collection { /// - Complexity: O(1) @inlinable public var endIndex: Index { - var path = _UnsafePath(root: _root.raw) - path.selectEnd() - return Index(_root: _root.unmanaged, version: _version, path: path) + var path = unsafe _UnsafePath(root: _root.raw) + unsafe path.selectEnd() + return unsafe Index(_root: _root.unmanaged, version: _version, path: path) } @inlinable @inline(__always) internal func _isValid(_ i: Index) -> Bool { - _root.isIdentical(to: i._root) && i._version == self._version + unsafe _root.isIdentical(to: i._root) && i._version == self._version } @inlinable @inline(__always) @@ -161,9 +165,9 @@ extension TreeDictionary: Collection { @inlinable public subscript(position: Index) -> Element { precondition(_isValid(position), "Invalid index") - precondition(position._path.isOnItem, "Cannot get element at endIndex") - return _UnsafeHandle.read(position._path.node) { - $0[item: position._path.currentItemSlot] + precondition(unsafe position._path.isOnItem, "Cannot get element at endIndex") + return unsafe _UnsafeHandle.read(position._path.node) { + unsafe $0[item: position._path.currentItemSlot] } } @@ -176,7 +180,7 @@ extension TreeDictionary: Collection { @inlinable public func formIndex(after i: inout Index) { precondition(_isValid(i), "Invalid index") - guard i._path.findSuccessorItem(under: _root.raw) else { + guard unsafe i._path.findSuccessorItem(under: _root.raw) else { preconditionFailure("The end index has no successor") } } @@ -206,7 +210,7 @@ extension TreeDictionary: Collection { @inlinable public func distance(from start: Index, to end: Index) -> Int { precondition(_isValid(start) && _isValid(end), "Invalid index") - return _root.raw.distance(.top, from: start._path, to: end._path) + return unsafe _root.raw.distance(.top, from: start._path, to: end._path) } /// Returns an index that is the specified distance from the given index. @@ -230,7 +234,7 @@ extension TreeDictionary: Collection { public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(_isValid(i), "Invalid index") var i = i - let r = _root.raw.seek(.top, &i._path, offsetBy: distance) + let r = unsafe _root.raw.seek(.top, &i._path, offsetBy: distance) precondition(r, "Index offset out of bounds") return i } @@ -263,7 +267,7 @@ extension TreeDictionary: Collection { precondition(_isValid(i), "Invalid index") precondition(_isValid(limit), "Invalid limit index") var i = i - let (found, limited) = _root.raw.seek( + let (found, limited) = unsafe _root.raw.seek( .top, &i._path, offsetBy: distance, limitedBy: limit._path ) if found { return i } diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Initializers.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Initializers.swift index 2738fa80..b7510934 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Initializers.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Initializers.swift @@ -84,8 +84,8 @@ extension TreeDictionary { self.init() for item in keysAndValues { let hash = _Hash(item.0) - let r = _root.insert(.top, item, hash) - precondition(r.inserted, "Duplicate key: '\(item.0)'") + let r = unsafe _root.insert(.top, item, hash) + precondition(unsafe r.inserted, "Duplicate key: '\(item.0)'") } _invariantCheck() } @@ -133,8 +133,8 @@ extension TreeDictionary { self.init() for item in keysAndValues { let hash = _Hash(item.key) - let r = _root.insert(.top, item, hash) - precondition(r.inserted, "Duplicate key: '\(item.key)'") + let r = unsafe _root.insert(.top, item, hash) + precondition(unsafe r.inserted, "Duplicate key: '\(item.key)'") } _invariantCheck() } diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift index 30da91c1..eb123071 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary+Sequence.swift @@ -18,6 +18,7 @@ extension TreeDictionary: Sequence { /// The type that allows iteration over a persistent dictionary's elements. @frozen + @safe public struct Iterator { // Fixed-stack iterator for traversing a hash tree. // The iterator performs a pre-order traversal, with items at a node visited @@ -27,11 +28,12 @@ extension TreeDictionary: Sequence { internal typealias _UnsafeHandle = _Node.UnsafeHandle @usableFromInline + @unsafe internal var _it: _HashTreeIterator @inlinable internal init(_root: _RawHashNode) { - self._it = _HashTreeIterator(root: _root) + unsafe self._it = _HashTreeIterator(root: _root) } } @@ -69,7 +71,7 @@ extension TreeDictionary.Iterator: IteratorProtocol { /// - Complexity: O(1) @inlinable public mutating func next() -> Element? { - guard let (node, slot) = _it.next() else { return nil } - return _UnsafeHandle.read(node) { $0[item: slot] } + guard let (node, slot) = unsafe _it.next() else { return nil } + return unsafe _UnsafeHandle.read(node) { unsafe $0[item: slot] } } } diff --git a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift index 76f3cd04..b7360f0a 100644 --- a/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift +++ b/Sources/HashTreeCollections/TreeDictionary/TreeDictionary.swift @@ -172,9 +172,9 @@ extension TreeDictionary { @inline(__always) // https://github.com/apple/swift-collections/issues/164 _modify { _invalidateIndices() - var state = _root.prepareValueUpdate(key, _Hash(key)) + var state = unsafe _root.prepareValueUpdate(key, _Hash(key)) defer { - _root.finalizeValueUpdate(state) + unsafe _root.finalizeValueUpdate(state) } yield &state.value } @@ -263,10 +263,10 @@ extension TreeDictionary { @inline(__always) // https://github.com/apple/swift-collections/issues/164 _modify { _invalidateIndices() - var state = _root.prepareDefaultedValueUpdate( + var state = unsafe _root.prepareDefaultedValueUpdate( .top, key, defaultValue, _Hash(key)) defer { - _root.finalizeDefaultedValueUpdate(state) + unsafe _root.finalizeDefaultedValueUpdate(state) } yield &state.item.value } @@ -288,9 +288,9 @@ extension TreeDictionary { /// high-quality hashing. @inlinable public func index(forKey key: Key) -> Index? { - guard let path = _root.path(to: key, _Hash(key)) + guard let path = unsafe _root.path(to: key, _Hash(key)) else { return nil } - return Index(_root: _root.unmanaged, version: _version, path: path) + return unsafe Index(_root: _root.unmanaged, version: _version, path: path) } /// Updates the value stored in the dictionary for the given key, or appends a @@ -349,15 +349,15 @@ extension TreeDictionary { ) -> Value? { defer { _fixLifetime(self) } let hash = _Hash(key) - let r = _root.updateValue(.top, forKey: key, hash) { - $0.initialize(to: (key, value)) + let r = unsafe _root.updateValue(.top, forKey: key, hash) { + unsafe $0.initialize(to: (key, value)) } _invalidateIndices() - if r.inserted { return nil } - return _UnsafeHandle.update(r.leaf) { - let p = $0.itemPtr(at: r.slot) - let old = p.pointee.value - p.pointee.value = value + if unsafe r.inserted { return nil } + return unsafe _UnsafeHandle.update(r.leaf) { + let p = unsafe $0.itemPtr(at: r.slot) + let old = unsafe p.pointee.value + unsafe p.pointee.value = value return old } } @@ -369,12 +369,12 @@ extension TreeDictionary { ) -> Bool { defer { _fixLifetime(self) } let hash = _Hash(key) - let r = _root.updateValue(.top, forKey: key, hash) { - $0.initialize(to: (key, value)) + let r = unsafe _root.updateValue(.top, forKey: key, hash) { + unsafe $0.initialize(to: (key, value)) } - if r.inserted { return true } - _UnsafeHandle.update(r.leaf) { - $0[item: r.slot].value = value + if unsafe r.inserted { return true } + unsafe _UnsafeHandle.update(r.leaf) { + unsafe $0[item: r.slot].value = value } return false } @@ -476,11 +476,11 @@ extension TreeDictionary { ) rethrows -> R { defer { _fixLifetime(self) } let hash = _Hash(key) - let r = _root.updateValue(.top, forKey: key, hash) { - $0.initialize(to: (key, defaultValue())) + let r = unsafe _root.updateValue(.top, forKey: key, hash) { + unsafe $0.initialize(to: (key, defaultValue())) } - return try _UnsafeHandle.update(r.leaf) { - try body(&$0[item: r.slot].value) + return unsafe try _UnsafeHandle.update(r.leaf) { + unsafe try body(&$0[item: r.slot].value) } } @@ -521,7 +521,7 @@ extension TreeDictionary { @inlinable @discardableResult public mutating func removeValue(forKey key: Key) -> Value? { - guard let r = _root.remove(.top, key, _Hash(key)) else { return nil } + guard let r = unsafe _root.remove(.top, key, _Hash(key)) else { return nil } _invalidateIndices() assert(r.remainder == nil) _invariantCheck() @@ -544,9 +544,9 @@ extension TreeDictionary { @inlinable public mutating func remove(at index: Index) -> Element { precondition(_isValid(index), "Invalid index") - precondition(index._path._isItem, "Cannot remove item at end index") + precondition(unsafe index._path._isItem, "Cannot remove item at end index") _invalidateIndices() - let r = _root.remove(.top, at: index._path) + let r = unsafe _root.remove(.top, at: index._path) assert(r.remainder == nil) return r.removed } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift index eb9249ef..04db2a71 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Collection.swift @@ -19,23 +19,26 @@ extension TreeSet { /// is changed; hence, indices are usually invalidated every time the set /// gets mutated. @frozen + @safe public struct Index { @usableFromInline + @unsafe internal let _root: _UnmanagedHashNode @usableFromInline internal var _version: UInt @usableFromInline + @unsafe internal var _path: _UnsafePath @inlinable @inline(__always) internal init( _root: _UnmanagedHashNode, version: UInt, path: _UnsafePath ) { - self._root = _root + unsafe self._root = _root self._version = version - self._path = path + unsafe self._path = path } } } @@ -53,9 +56,9 @@ extension TreeSet.Index: Equatable { @inlinable public static func ==(left: Self, right: Self) -> Bool { precondition( - left._root == right._root && left._version == right._version, + unsafe left._root == right._root && left._version == right._version, "Indices from different set values aren't comparable") - return left._path == right._path + return unsafe left._path == right._path } } @@ -70,9 +73,9 @@ extension TreeSet.Index: Comparable { @inlinable public static func <(left: Self, right: Self) -> Bool { precondition( - left._root == right._root && left._version == right._version, + unsafe left._root == right._root && left._version == right._version, "Indices from different set values aren't comparable") - return left._path < right._path + return unsafe left._path < right._path } } @@ -83,7 +86,7 @@ extension TreeSet.Index: Hashable { /// - Complexity: O(1) @inlinable public func hash(into hasher: inout Hasher) { - hasher.combine(_path) + unsafe hasher.combine(_path) } } @@ -91,7 +94,7 @@ extension TreeSet.Index: Hashable { extension TreeSet.Index: CustomStringConvertible { // A textual representation of this instance. public var description: String { - _path.description + unsafe _path.description } } @@ -125,9 +128,9 @@ extension TreeSet: Collection { /// /// - Complexity: O(1) public var startIndex: Index { - var path = _UnsafePath(root: _root.raw) - path.descendToLeftMostItem() - return Index(_root: _root.unmanaged, version: _version, path: path) + var path = unsafe _UnsafePath(root: _root.raw) + unsafe path.descendToLeftMostItem() + return unsafe Index(_root: _root.unmanaged, version: _version, path: path) } /// The collection's "past the end" position—that is, the position one greater @@ -136,14 +139,14 @@ extension TreeSet: Collection { /// - Complexity: O(1) @inlinable public var endIndex: Index { - var path = _UnsafePath(root: _root.raw) - path.selectEnd() - return Index(_root: _root.unmanaged, version: _version, path: path) + var path = unsafe _UnsafePath(root: _root.raw) + unsafe path.selectEnd() + return unsafe Index(_root: _root.unmanaged, version: _version, path: path) } @inlinable @inline(__always) internal func _isValid(_ i: Index) -> Bool { - _root.isIdentical(to: i._root) && i._version == self._version + unsafe _root.isIdentical(to: i._root) && i._version == self._version } @inlinable @inline(__always) @@ -161,9 +164,9 @@ extension TreeSet: Collection { @inlinable public subscript(position: Index) -> Element { precondition(_isValid(position), "Invalid index") - precondition(position._path.isOnItem, "Cannot get element at endIndex") - return _UnsafeHandle.read(position._path.node) { - $0[item: position._path.currentItemSlot].key + precondition(unsafe position._path.isOnItem, "Cannot get element at endIndex") + return unsafe _UnsafeHandle.read(position._path.node) { + unsafe $0[item: position._path.currentItemSlot].key } } @@ -176,7 +179,7 @@ extension TreeSet: Collection { @inlinable public func formIndex(after i: inout Index) { precondition(_isValid(i), "Invalid index") - guard i._path.findSuccessorItem(under: _root.raw) else { + guard unsafe i._path.findSuccessorItem(under: _root.raw) else { preconditionFailure("The end index has no successor") } } @@ -206,7 +209,7 @@ extension TreeSet: Collection { @inlinable public func distance(from start: Index, to end: Index) -> Int { precondition(_isValid(start) && _isValid(end), "Invalid index") - return _root.raw.distance(.top, from: start._path, to: end._path) + return unsafe _root.raw.distance(.top, from: start._path, to: end._path) } /// Returns an index that is the specified distance from the given index. @@ -230,7 +233,7 @@ extension TreeSet: Collection { public func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(_isValid(i), "Invalid index") var i = i - let r = _root.raw.seek(.top, &i._path, offsetBy: distance) + let r = unsafe _root.raw.seek(.top, &i._path, offsetBy: distance) precondition(r, "Index offset out of bounds") return i } @@ -263,7 +266,7 @@ extension TreeSet: Collection { precondition(_isValid(i), "Invalid index") precondition(_isValid(limit), "Invalid limit index") var i = i - let (found, limited) = _root.raw.seek( + let (found, limited) = unsafe _root.raw.seek( .top, &i._path, offsetBy: distance, limitedBy: limit._path ) if found { return i } @@ -316,8 +319,8 @@ extension TreeSet: Collection { @inlinable internal func _index(of element: Element) -> Index? { let hash = _Hash(element) - guard let path = _root.path(to: element, hash) else { return nil } - return Index(_root: _root.unmanaged, version: _version, path: path) + guard let path = unsafe _root.path(to: element, hash) else { return nil } + return unsafe Index(_root: _root.unmanaged, version: _version, path: path) } public func _failEarlyRangeCheck( diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift index 448ae5dd..fe2735d5 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Extras.swift @@ -32,7 +32,7 @@ extension TreeSet { public mutating func remove(at position: Index) -> Element { precondition(_isValid(position)) _invalidateIndices() - let r = _root.remove(.top, at: position._path) + let r = unsafe _root.remove(.top, at: position._path) precondition(r.remainder == nil) return r.removed.key } @@ -58,15 +58,15 @@ extension TreeSet { public mutating func update(_ member: Element, at index: Index) -> Element { defer { _fixLifetime(self) } precondition(_isValid(index), "Invalid index") - precondition(index._path.isOnItem, "Cannot get element at endIndex") + precondition(unsafe index._path.isOnItem, "Cannot get element at endIndex") _invalidateIndices() - return _UnsafeHandle.update(index._path.node) { - let p = $0.itemPtr(at: index._path.currentItemSlot) + return unsafe _UnsafeHandle.update(index._path.node) { + let p = unsafe $0.itemPtr(at: index._path.currentItemSlot) var old = member precondition( - member == p.pointee.key, + unsafe member == p.pointee.key, "The replacement item must compare equal to the original") - swap(&p.pointee.key, &old) + unsafe swap(&p.pointee.key, &old) return old } } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift index c482126c..77422288 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+Sequence.swift @@ -14,16 +14,18 @@ extension TreeSet: Sequence { /// An iterator over the members of a `TreeSet`. @frozen + @safe public struct Iterator: IteratorProtocol { @usableFromInline internal typealias _UnsafeHandle = _Node.UnsafeHandle @usableFromInline + @unsafe internal var _it: _HashTreeIterator @inlinable internal init(_root: _RawHashNode) { - _it = _HashTreeIterator(root: _root) + unsafe _it = _HashTreeIterator(root: _root) } /// Advances to the next element and returns it, or `nil` if no next element @@ -34,8 +36,8 @@ extension TreeSet: Sequence { /// - Complexity: O(1) @inlinable public mutating func next() -> Element? { - guard let (node, slot) = _it.next() else { return nil } - return _UnsafeHandle.read(node) { $0[item: slot].key } + guard let (node, slot) = unsafe _it.next() else { return nil } + return unsafe _UnsafeHandle.read(node) { unsafe $0[item: slot].key } } } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift index 12cd03d8..7504261a 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra basics.swift @@ -55,13 +55,13 @@ extension TreeSet: SetAlgebra { ) -> (inserted: Bool, memberAfterInsert: Element) { defer { _fixLifetime(self) } let hash = _Hash(newMember) - let r = _root.insert(.top, (newMember, ()), hash) - if r.inserted { + let r = unsafe _root.insert(.top, (newMember, ()), hash) + if unsafe r.inserted { _invalidateIndices() return (true, newMember) } - return _UnsafeHandle.read(r.leaf) { - (false, $0[item: r.slot].key) + return unsafe _UnsafeHandle.read(r.leaf) { + unsafe (false, $0[item: r.slot].key) } } @@ -69,8 +69,8 @@ extension TreeSet: SetAlgebra { @inlinable internal mutating func _insert(_ newMember: __owned Element) -> Bool { let hash = _Hash(newMember) - let r = _root.insert(.top, (newMember, ()), hash) - return r.inserted + let r = unsafe _root.insert(.top, (newMember, ()), hash) + return unsafe r.inserted } /// Removes the given element from the set. @@ -93,7 +93,7 @@ extension TreeSet: SetAlgebra { @inlinable public mutating func remove(_ member: Element) -> Element? { let hash = _Hash(member) - guard let r = _root.remove(.top, member, hash) else { return nil } + guard let r = unsafe _root.remove(.top, member, hash) else { return nil } _invalidateIndices() assert(r.remainder == nil) return r.removed.key @@ -122,14 +122,14 @@ extension TreeSet: SetAlgebra { public mutating func update(with newMember: __owned Element) -> Element? { defer { _fixLifetime(self) } let hash = _Hash(newMember) - let r = _root.updateValue(.top, forKey: newMember, hash) { - $0.initialize(to: (newMember, ())) + let r = unsafe _root.updateValue(.top, forKey: newMember, hash) { + unsafe $0.initialize(to: (newMember, ())) } - if r.inserted { return nil } - return _UnsafeHandle.update(r.leaf) { - let p = $0.itemPtr(at: r.slot) - let old = p.move().key - p.initialize(to: (newMember, ())) + if unsafe r.inserted { return nil } + return unsafe _UnsafeHandle.update(r.leaf) { + let p = unsafe $0.itemPtr(at: r.slot) + let old = unsafe p.move().key + unsafe p.initialize(to: (newMember, ())) return old } } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift index 7d4e232d..28bc9ee6 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra intersection.swift @@ -103,10 +103,10 @@ extension TreeSet { var result: _Node = ._emptyNode() for item in other { let hash = _Hash(item) - if let r = self._root.lookup(.top, item, hash) { - let itemInSelf = _UnsafeHandle.read(r.node) { $0[item: r.slot] } - _ = result.updateValue(.top, forKey: itemInSelf.key, hash) { - $0.initialize(to: itemInSelf) + if let r = unsafe self._root.lookup(.top, item, hash) { + let itemInSelf = unsafe _UnsafeHandle.read(r.node) { unsafe $0[item: r.slot] } + _ = unsafe result.updateValue(.top, forKey: itemInSelf.key, hash) { + unsafe $0.initialize(to: itemInSelf) } } } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift index 3237f5f3..a0ac008b 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isEqualSet.swift @@ -111,7 +111,7 @@ extension TreeSet { while let item = it.next() { let hash = _Hash(item) guard self._root.containsKey(.top, item, hash) else { return false } - _ = seen!.insert(.top, (item, ()), hash) // Ignore dupes + _ = unsafe seen!.insert(.top, (item, ()), hash) // Ignore dupes if seen!.count == self.count { // We've seen them all. Stop further accounting. seen = nil diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift index 48be46a9..fc3d6115 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSubset.swift @@ -122,7 +122,7 @@ extension TreeSet { if self._root.containsKey(.top, item, hash) { if !doneCollecting, - seen.insert(.top, (item, ()), hash).inserted, + unsafe seen.insert(.top, (item, ()), hash).inserted, seen.count == self.count { if isStrict { return true } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift index 420b4f06..6acf9831 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isStrictSuperset.swift @@ -115,7 +115,7 @@ extension TreeSet { let hash = _Hash(item) guard self._root.containsKey(.top, item, hash) else { return false } if - seen.insert(.top, (item, ()), hash).inserted, + unsafe seen.insert(.top, (item, ()), hash).inserted, seen.count == self.count { return false diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift index fbd53aa1..48384fd7 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra isSubset.swift @@ -105,7 +105,7 @@ extension TreeSet { for item in other { let hash = _Hash(item) guard _root.containsKey(.top, item, hash) else { continue } - guard seen.insert(.top, (item, ()), hash).inserted else { continue } + guard unsafe seen.insert(.top, (item, ()), hash).inserted else { continue } if seen.count == self.count { return true } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift index f9eecd52..232ea552 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra subtracting.swift @@ -95,7 +95,7 @@ extension TreeSet { var root = self._root for item in other { let hash = _Hash(item) - _ = root.remove(.top, item, hash) + _ = unsafe root.remove(.top, item, hash) } return Self(_new: root) } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra symmetricDifference.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra symmetricDifference.swift index aa9090a1..2f4f9a87 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra symmetricDifference.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra symmetricDifference.swift @@ -99,13 +99,13 @@ extension TreeSet { var root = self._root for item in other { let hash = _Hash(item) - var state = root.prepareValueUpdate(item, hash) + var state = unsafe root.prepareValueUpdate(item, hash) if state.found { state.value = nil } else { state.value = () } - root.finalizeValueUpdate(state) + unsafe root.finalizeValueUpdate(state) } return Self(_new: root) } diff --git a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra union.swift b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra union.swift index 22a6cf32..8567285b 100644 --- a/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra union.swift +++ b/Sources/HashTreeCollections/TreeSet/TreeSet+SetAlgebra union.swift @@ -105,7 +105,7 @@ extension TreeSet { var root = self._root for item in other { let hash = _Hash(item) - _ = root.insert(.top, (item, ()), hash) + _ = unsafe root.insert(.top, (item, ()), hash) } return Self(_new: root) } diff --git a/Sources/HeapModule/Heap+UnsafeHandle.swift b/Sources/HeapModule/Heap+UnsafeHandle.swift index b1f13fbb..66e80552 100644 --- a/Sources/HeapModule/Heap+UnsafeHandle.swift +++ b/Sources/HeapModule/Heap+UnsafeHandle.swift @@ -13,72 +13,74 @@ extension Heap { @usableFromInline @frozen - struct _UnsafeHandle { + @unsafe + internal struct _UnsafeHandle { @usableFromInline - var buffer: UnsafeMutableBufferPointer + internal var buffer: UnsafeMutableBufferPointer @inlinable @inline(__always) - init(_ buffer: UnsafeMutableBufferPointer) { - self.buffer = buffer + internal init(_ buffer: UnsafeMutableBufferPointer) { + unsafe self.buffer = buffer } } @inlinable @inline(__always) - mutating func _update(_ body: (_UnsafeHandle) -> R) -> R { + internal mutating func _update(_ body: (_UnsafeHandle) -> R) -> R { _storage.withUnsafeMutableBufferPointer { buffer in - body(_UnsafeHandle(buffer)) + unsafe body(_UnsafeHandle(buffer)) } } } extension Heap._UnsafeHandle { @inlinable @inline(__always) + @safe internal var count: Int { - buffer.count + unsafe buffer.count } @inlinable - subscript(node: _HeapNode) -> Element { + internal subscript(node: _HeapNode) -> Element { @inline(__always) get { - buffer[node.offset] + unsafe buffer[node.offset] } @inline(__always) nonmutating _modify { - yield &buffer[node.offset] + yield unsafe &buffer[node.offset] } } @inlinable @inline(__always) internal func ptr(to node: _HeapNode) -> UnsafeMutablePointer { assert(node.offset < count) - return buffer.baseAddress! + node.offset + return unsafe buffer.baseAddress! + node.offset } /// Move the value at the specified node out of the buffer, leaving it /// uninitialized. @inlinable @inline(__always) internal func extract(_ node: _HeapNode) -> Element { - ptr(to: node).move() + unsafe ptr(to: node).move() } @inlinable @inline(__always) internal func initialize(_ node: _HeapNode, to value: __owned Element) { - ptr(to: node).initialize(to: value) + unsafe ptr(to: node).initialize(to: value) } /// Swaps the elements in the heap at the given indices. @inlinable @inline(__always) internal func swapAt(_ i: _HeapNode, _ j: _HeapNode) { - buffer.swapAt(i.offset, j.offset) + unsafe buffer.swapAt(i.offset, j.offset) } /// Swaps the element at the given node with the supplied value. @inlinable @inline(__always) internal func swapAt(_ i: _HeapNode, with value: inout Element) { assert(i.offset < count) - let p = buffer.baseAddress.unsafelyUnwrapped + i.offset - swap(&p.pointee, &value) + let p = unsafe buffer.baseAddress.unsafelyUnwrapped + i.offset + unsafe swap(&p.pointee, &value) } @@ -88,13 +90,13 @@ extension Heap._UnsafeHandle { // standard `Swift.min(_:_:)` function. This attempts to // preserve any pre-existing order in case `T` has identity. // `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`. - self[b] < self[a] ? b : a + unsafe self[b] < self[a] ? b : a } @inlinable @inline(__always) internal func maxValue(_ a: _HeapNode, _ b: _HeapNode) -> _HeapNode { // In case `a` and `b` match, we need to pick `b`. See `minValue(_:_:)`. - self[b] >= self[a] ? b : a + unsafe self[b] >= self[a] ? b : a } } @@ -106,22 +108,22 @@ extension Heap._UnsafeHandle { let parent = node.parent() var node = node - if (node.isMinLevel && self[node] > self[parent]) + if unsafe (node.isMinLevel && self[node] > self[parent]) || (!node.isMinLevel && self[node] < self[parent]){ - swapAt(node, parent) + unsafe swapAt(node, parent) node = parent } if node.isMinLevel { while let grandparent = node.grandParent(), - self[node] < self[grandparent] { - swapAt(node, grandparent) + unsafe self[node] < self[grandparent] { + unsafe swapAt(node, grandparent) node = grandparent } } else { while let grandparent = node.grandParent(), - self[node] > self[grandparent] { - swapAt(node, grandparent) + unsafe self[node] > self[grandparent] { + unsafe swapAt(node, grandparent) node = grandparent } } @@ -135,9 +137,9 @@ extension Heap._UnsafeHandle { internal func trickleDownMin(_ node: _HeapNode) { assert(node.isMinLevel) var node = node - var value = extract(node) - _trickleDownMin(node: &node, value: &value) - initialize(node, to: value) + var value = unsafe extract(node) + unsafe _trickleDownMin(node: &node, value: &value) + unsafe initialize(node, to: value) } @inlinable @inline(__always) @@ -156,24 +158,24 @@ extension Heap._UnsafeHandle { // We have four grandchildren, so we don't need to compare children. let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) - let minA = minValue(gc0, gc1) + let minA = unsafe minValue(gc0, gc1) let gc2 = _HeapNode(offset: gc0.offset &+ 2, level: gc0.level) let gc3 = _HeapNode(offset: gc0.offset &+ 3, level: gc0.level) - let minB = minValue(gc2, gc3) + let minB = unsafe minValue(gc2, gc3) - let min = minValue(minA, minB) - guard self[min] < value else { + let min = unsafe minValue(minA, minB) + guard unsafe self[min] < value else { return // We're done -- `node` is a good place for `value`. } - initialize(node, to: extract(min)) + unsafe initialize(node, to: extract(min)) node = min gc0 = node.firstGrandchild() let parent = min.parent() - if self[parent] < value { - swapAt(parent, with: &value) + if unsafe self[parent] < value { + unsafe swapAt(parent, with: &value) } } @@ -184,20 +186,20 @@ extension Heap._UnsafeHandle { if c0.offset >= count { return // No more descendants to consider. } - let min = _minDescendant(c0: c0, gc0: gc0) - guard self[min] < value else { + let min = unsafe _minDescendant(c0: c0, gc0: gc0) + guard unsafe self[min] < value else { return // We're done. } - initialize(node, to: extract(min)) + unsafe initialize(node, to: extract(min)) node = min if min < gc0 { return } // If `min` was a grandchild, check the parent. let parent = min.parent() - if self[parent] < value { - initialize(node, to: extract(parent)) + if unsafe self[parent] < value { + unsafe initialize(node, to: extract(parent)) node = parent } } @@ -222,15 +224,15 @@ extension Heap._UnsafeHandle { // We have three grandchildren. We don't need to compare direct children. let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) let gc2 = _HeapNode(offset: gc0.offset &+ 2, level: gc0.level) - return minValue(minValue(gc0, gc1), gc2) + return unsafe minValue(minValue(gc0, gc1), gc2) } let c1 = _HeapNode(offset: c0.offset &+ 1, level: c0.level) - let m = minValue(c1, gc0) + let m = unsafe minValue(c1, gc0) if gc0.offset &+ 1 < count { // Two grandchildren. let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) - return minValue(m, gc1) + return unsafe minValue(m, gc1) } // One grandchild. @@ -239,7 +241,7 @@ extension Heap._UnsafeHandle { let c1 = _HeapNode(offset: c0.offset &+ 1, level: c0.level) if c1.offset < count { - return minValue(c0, c1) + return unsafe minValue(c0, c1) } return c0 @@ -251,10 +253,10 @@ extension Heap._UnsafeHandle { internal func trickleDownMax(_ node: _HeapNode) { assert(!node.isMinLevel) var node = node - var value = extract(node) + var value = unsafe extract(node) - _trickleDownMax(node: &node, value: &value) - initialize(node, to: value) + unsafe _trickleDownMax(node: &node, value: &value) + unsafe initialize(node, to: value) } @inlinable @inline(__always) @@ -267,24 +269,24 @@ extension Heap._UnsafeHandle { // We have four grandchildren, so we don't need to compare children. let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) - let maxA = maxValue(gc0, gc1) + let maxA = unsafe maxValue(gc0, gc1) let gc2 = _HeapNode(offset: gc0.offset &+ 2, level: gc0.level) let gc3 = _HeapNode(offset: gc0.offset &+ 3, level: gc0.level) - let maxB = maxValue(gc2, gc3) + let maxB = unsafe maxValue(gc2, gc3) - let max = maxValue(maxA, maxB) - guard value < self[max] else { + let max = unsafe maxValue(maxA, maxB) + guard unsafe value < self[max] else { return // We're done -- `node` is a good place for `value`. } - initialize(node, to: extract(max)) + unsafe initialize(node, to: extract(max)) node = max gc0 = node.firstGrandchild() let parent = max.parent() - if value < self[parent] { - swapAt(parent, with: &value) + if unsafe value < self[parent] { + unsafe swapAt(parent, with: &value) } } @@ -295,20 +297,20 @@ extension Heap._UnsafeHandle { if c0.offset >= count { return // No more descendants to consider. } - let max = _maxDescendant(c0: c0, gc0: gc0) - guard value < self[max] else { + let max = unsafe _maxDescendant(c0: c0, gc0: gc0) + guard unsafe value < self[max] else { return // We're done. } - initialize(node, to: extract(max)) + unsafe initialize(node, to: extract(max)) node = max if max < gc0 { return } // If `max` was a grandchild, check the parent. let parent = max.parent() - if value < self[parent] { - initialize(node, to: extract(parent)) + if unsafe value < self[parent] { + unsafe initialize(node, to: extract(parent)) node = parent } } @@ -333,15 +335,15 @@ extension Heap._UnsafeHandle { // We have three grandchildren. We don't need to compare direct children. let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) let gc2 = _HeapNode(offset: gc0.offset &+ 2, level: gc0.level) - return maxValue(maxValue(gc0, gc1), gc2) + return unsafe maxValue(maxValue(gc0, gc1), gc2) } let c1 = _HeapNode(offset: c0.offset &+ 1, level: c0.level) - let m = maxValue(c1, gc0) + let m = unsafe maxValue(c1, gc0) if gc0.offset &+ 1 < count { // Two grandchildren. let gc1 = _HeapNode(offset: gc0.offset &+ 1, level: gc0.level) - return maxValue(m, gc1) + return unsafe maxValue(m, gc1) } // One grandchild. @@ -350,7 +352,7 @@ extension Heap._UnsafeHandle { let c1 = _HeapNode(offset: c0.offset &+ 1, level: c0.level) if c1.offset < count { - return maxValue(c0, c1) + return unsafe maxValue(c0, c1) } return c0 @@ -369,7 +371,7 @@ extension Heap._UnsafeHandle { var level = _HeapNode.level(forOffset: limit &- 1) while level >= 0 { let nodes = _HeapNode.allNodes(onLevel: level, limit: limit) - _heapify(level, nodes) + unsafe _heapify(level, nodes) level &-= 1 } } @@ -379,11 +381,11 @@ extension Heap._UnsafeHandle { guard let nodes = nodes else { return } if _HeapNode.isMinLevel(level) { nodes._forEach { node in - trickleDownMin(node) + unsafe trickleDownMin(node) } } else { nodes._forEach { node in - trickleDownMax(node) + unsafe trickleDownMax(node) } } } diff --git a/Sources/HeapModule/Heap.swift b/Sources/HeapModule/Heap.swift index d0b2a808..a1b0cd2b 100644 --- a/Sources/HeapModule/Heap.swift +++ b/Sources/HeapModule/Heap.swift @@ -145,8 +145,8 @@ extension Heap { public mutating func insert(_ element: Element) { _storage.append(element) - _update { handle in - handle.bubbleUp(_HeapNode(offset: handle.count - 1)) + unsafe _update { handle in + unsafe handle.bubbleUp(_HeapNode(offset: handle.count - 1)) } _checkInvariants() } @@ -170,11 +170,11 @@ extension Heap { // If count is 1, the last (and only) item is the max // If count is 2, the last item is the max (as it's the only item in the // first max level) - return buffer.last + return unsafe buffer.last } // We have at least 3 items -- return the larger of the two in the first // max level - return Swift.max(buffer[1], buffer[2]) + return unsafe Swift.max(buffer[1], buffer[2]) } } @@ -188,10 +188,10 @@ extension Heap { var removed = _storage.removeLast() if _storage.count > 0 { - _update { handle in + unsafe _update { handle in let minNode = _HeapNode.root - handle.swapAt(minNode, with: &removed) - handle.trickleDownMin(minNode) + unsafe handle.swapAt(minNode, with: &removed) + unsafe handle.trickleDownMin(minNode) } } @@ -208,15 +208,15 @@ extension Heap { var removed = _storage.removeLast() - _update { handle in + unsafe _update { handle in if handle.count == 2 { - if handle[.leftMax] > removed { - handle.swapAt(.leftMax, with: &removed) + if unsafe handle[.leftMax] > removed { + unsafe handle.swapAt(.leftMax, with: &removed) } } else { - let maxNode = handle.maxValue(.leftMax, .rightMax) - handle.swapAt(maxNode, with: &removed) - handle.trickleDownMax(maxNode) + let maxNode = unsafe handle.maxValue(.leftMax, .rightMax) + unsafe handle.swapAt(maxNode, with: &removed) + unsafe handle.trickleDownMax(maxNode) } } @@ -262,10 +262,10 @@ extension Heap { precondition(!isEmpty, "No element to replace") var removed = replacement - _update { handle in + unsafe _update { handle in let minNode = _HeapNode.root - handle.swapAt(minNode, with: &removed) - handle.trickleDownMin(minNode) + unsafe handle.swapAt(minNode, with: &removed) + unsafe handle.trickleDownMin(minNode) } _checkInvariants() return removed @@ -284,8 +284,8 @@ extension Heap { ) rethrows { defer { if _storage.count > 1 { - _update { handle in - handle.heapify() + unsafe _update { handle in + unsafe handle.heapify() } } _checkInvariants() @@ -309,18 +309,18 @@ extension Heap { precondition(!isEmpty, "No element to replace") var removed = replacement - _update { handle in + unsafe _update { handle in switch handle.count { case 1: - handle.swapAt(.root, with: &removed) + unsafe handle.swapAt(.root, with: &removed) case 2: - handle.swapAt(.leftMax, with: &removed) - handle.bubbleUp(.leftMax) + unsafe handle.swapAt(.leftMax, with: &removed) + unsafe handle.bubbleUp(.leftMax) default: - let maxNode = handle.maxValue(.leftMax, .rightMax) - handle.swapAt(maxNode, with: &removed) - handle.bubbleUp(maxNode) // This must happen first - handle.trickleDownMax(maxNode) // Either new element or dethroned min + let maxNode = unsafe handle.maxValue(.leftMax, .rightMax) + unsafe handle.swapAt(maxNode, with: &removed) + unsafe handle.bubbleUp(maxNode) // This must happen first + unsafe handle.trickleDownMax(maxNode) // Either new element or dethroned min } } _checkInvariants() @@ -339,8 +339,8 @@ extension Heap { _storage = ContiguousArray(elements) guard _storage.count > 1 else { return } - _update { handle in - handle.heapify() + unsafe _update { handle in + unsafe handle.heapify() } _checkInvariants() } @@ -384,12 +384,12 @@ extension Heap { // FIXME: Write a benchmark to verify this heuristic. let heuristicLimit = 2 &* newCount / newCount._binaryLogarithm() let useFloyd = (newCount - origCount) > heuristicLimit - _update { handle in + unsafe _update { handle in if useFloyd { - handle.heapify() + unsafe handle.heapify() } else { for offset in origCount ..< handle.count { - handle.bubbleUp(_HeapNode(offset: offset)) + unsafe handle.bubbleUp(_HeapNode(offset: offset)) } } } diff --git a/Sources/HeapModule/_HeapNode.swift b/Sources/HeapModule/_HeapNode.swift index 686473e7..91d5e4de 100644 --- a/Sources/HeapModule/_HeapNode.swift +++ b/Sources/HeapModule/_HeapNode.swift @@ -158,7 +158,7 @@ extension _HeapNode { if last.offset >= limit { last.offset = limit &- 1 } - return ClosedRange(uncheckedBounds: (first, last)) + return unsafe ClosedRange(uncheckedBounds: (first, last)) } } diff --git a/Sources/InternalCollectionsUtilities/BorrowingIteratorProtocol+Equality.swift b/Sources/InternalCollectionsUtilities/BorrowingIteratorProtocol+Equality.swift index 2e82b2ac..53bccfd9 100644 --- a/Sources/InternalCollectionsUtilities/BorrowingIteratorProtocol+Equality.swift +++ b/Sources/InternalCollectionsUtilities/BorrowingIteratorProtocol+Equality.swift @@ -47,7 +47,7 @@ where var j = 0 while j < b.count { - guard a[unchecked: i] == b[unchecked: j] else { return false } + guard unsafe a[unchecked: i] == b[unchecked: j] else { return false } i &+= 1 j &+= 1 } @@ -129,7 +129,7 @@ where var j = 0 while j < b.count { - guard try areEquivalent(a[unchecked: i], b[unchecked: j]) + guard unsafe try areEquivalent(a[unchecked: i], b[unchecked: j]) else { return false } i &+= 1 j &+= 1 diff --git a/Sources/InternalCollectionsUtilities/BorrowingIteratorProtocol+Extras.swift b/Sources/InternalCollectionsUtilities/BorrowingIteratorProtocol+Extras.swift index 6a3c67c5..cb067458 100644 --- a/Sources/InternalCollectionsUtilities/BorrowingIteratorProtocol+Extras.swift +++ b/Sources/InternalCollectionsUtilities/BorrowingIteratorProtocol+Extras.swift @@ -37,12 +37,12 @@ extension BorrowingIteratorProtocol @inlinable @_transparent package mutating func _copyContents(into target: inout OutputSpan) throws(Failure) { - try target.withUnsafeMutableBufferPointer { (dst, dstCount) throws(Failure) -> Void in - var tail = dst._extracting(droppingFirst: dstCount) + unsafe try target.withUnsafeMutableBufferPointer { (dst, dstCount) throws(Failure) -> Void in + var tail = unsafe dst._extracting(droppingFirst: dstCount) while !tail.isEmpty { let src = try nextSpan(maxCount: tail.count) if src.isEmpty { break } - tail._initializeAndDropPrefix(copying: src) + unsafe tail._initializeAndDropPrefix(copying: src) dstCount += src.count } } diff --git a/Sources/InternalCollectionsUtilities/Descriptions.swift b/Sources/InternalCollectionsUtilities/Descriptions.swift index 7ac7eb3a..21e5249f 100644 --- a/Sources/InternalCollectionsUtilities/Descriptions.swift +++ b/Sources/InternalCollectionsUtilities/Descriptions.swift @@ -12,19 +12,22 @@ //===----------------------------------------------------------------------===// @usableFromInline +@safe package func _addressString(for pointer: UnsafeRawPointer) -> String { let address = UInt(bitPattern: pointer) return "0x\(String(address, radix: 16))" } @usableFromInline +@safe package func _addressString(for object: AnyObject) -> String { - _addressString(for: Unmanaged.passUnretained(object).toOpaque()) + unsafe _addressString(for: Unmanaged.passUnretained(object).toOpaque()) } @usableFromInline +@safe package func _addressString(for object: Unmanaged) -> String { - _addressString(for: object.toOpaque()) + unsafe _addressString(for: object.toOpaque()) } #if !$Embedded diff --git a/Sources/InternalCollectionsUtilities/Iterable+CopyContents.swift b/Sources/InternalCollectionsUtilities/Iterable+CopyContents.swift index 873c22a3..37e2d5ab 100644 --- a/Sources/InternalCollectionsUtilities/Iterable+CopyContents.swift +++ b/Sources/InternalCollectionsUtilities/Iterable+CopyContents.swift @@ -16,17 +16,18 @@ @available(SwiftStdlib 6.4, *) extension Iterable where Self: ~Copyable & ~Escapable, Element: Copyable { @inlinable + @unsafe package func _copyContents( intoPrefixOf buffer: UnsafeMutableBufferPointer ) throws(Failure) -> Int { - var target = buffer + var target = unsafe buffer var it = self.makeBorrowingIterator() while target.count != 0 { let span = try it.nextSpan(maxCount: target.count) if span.isEmpty { return buffer.count - target.count } - target._initializeAndDropPrefix(copying: span) + unsafe target._initializeAndDropPrefix(copying: span) } let test = try it.nextSpan() precondition(test.isEmpty, "Contents do not fit in target buffer") diff --git a/Sources/InternalCollectionsUtilities/LifetimeOverride.swift b/Sources/InternalCollectionsUtilities/LifetimeOverride.swift index f9ad6aff..1297b0c6 100644 --- a/Sources/InternalCollectionsUtilities/LifetimeOverride.swift +++ b/Sources/InternalCollectionsUtilities/LifetimeOverride.swift @@ -13,10 +13,10 @@ /// Unsafely discard any lifetime dependency on the `dependent` argument. /// Return a value identical to `dependent` with an immortal lifetime. -@unsafe @_unsafeNonescapableResult @_alwaysEmitIntoClient @_transparent +@unsafe @_lifetime(immortal) package func _unsafeImmortalize( _ dependent: consuming T @@ -27,10 +27,10 @@ package func _unsafeImmortalize( /// Unsafely discard any lifetime dependency on the `dependent` argument. /// Return a value identical to `dependent` with a lifetime dependency /// on the caller's borrow scope of the `source` argument. -@unsafe @_unsafeNonescapableResult @_alwaysEmitIntoClient @_transparent +@unsafe @_lifetime(borrow source) package func _overrideLifetime< T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable @@ -43,10 +43,10 @@ package func _overrideLifetime< /// Unsafely discard any lifetime dependency on the `dependent` argument. /// Return a value identical to `dependent` that inherits /// all lifetime dependencies from the `source` argument. -@unsafe @_unsafeNonescapableResult @_alwaysEmitIntoClient @_transparent +@unsafe @_lifetime(copy source) package func _overrideLifetime< T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable @@ -59,10 +59,10 @@ package func _overrideLifetime< /// Unsafely discard any lifetime dependency on the `dependent` argument. /// Return a value identical to `dependent` with a lifetime dependency /// on the caller's exclusive borrow scope of the `source` argument. -@unsafe @_unsafeNonescapableResult @_alwaysEmitIntoClient @_transparent +@unsafe @_lifetime(&source) package func _overrideLifetime< T: ~Copyable & ~Escapable, @@ -79,10 +79,10 @@ package func _overrideLifetime< /// Unsafely discard any lifetime dependency on the `dependent` inout /// argument, replacing it with a lifetime dependency on the caller's borrow /// scope of the `source` argument. -@unsafe @_unsafeNonescapableResult @_alwaysEmitIntoClient @_transparent +@unsafe @_lifetime(dependent: borrow source) public func _overrideLifetime< T: ~Copyable & ~Escapable, U: ~Copyable & ~Escapable diff --git a/Sources/InternalCollectionsUtilities/MutableSpan+Extras.swift b/Sources/InternalCollectionsUtilities/MutableSpan+Extras.swift index e5b440d3..d87d365d 100644 --- a/Sources/InternalCollectionsUtilities/MutableSpan+Extras.swift +++ b/Sources/InternalCollectionsUtilities/MutableSpan+Extras.swift @@ -48,20 +48,20 @@ extension MutableSpan where Element: ~Copyable { "updateSubrange source count doesn't match target") guard !subrange.isEmpty else { return } self.withUnsafeMutableBufferPointer { dst in - source.withUnsafeMutableBufferPointer { src, c in + unsafe source.withUnsafeMutableBufferPointer { src, c in // FIXME: Make sure this calls memcpy when Element is bitwise movable. #if false // FIXME: UMBP.moveUpdate(fromContentsOf:) is broken as of 2026-09-17 (rdar://187733648) - let i = dst + let i = unsafe dst ._extracting(unchecked: subrange) .moveUpdate(fromContentsOf: src._extracting(first: c)) precondition(i == subrange.count) #else - var d = dst._ptr(at: subrange.lowerBound) - var s = src._ptr(at: 0) + var d = unsafe dst._ptr(at: subrange.lowerBound) + var s = unsafe src._ptr(at: 0) for i in 0 ..< c { - d.pointee = s.move() - d += 1 - s += 1 + unsafe d.pointee = s.move() + unsafe d += 1 + unsafe s += 1 } #endif c = 0 @@ -82,18 +82,18 @@ extension MutableSpan where Element: ~Copyable { "updateSubrange source count doesn't match target") guard !self.isEmpty else { return } self.withUnsafeMutableBufferPointer { dst in - source.withUnsafeMutableBufferPointer { src, c in + unsafe source.withUnsafeMutableBufferPointer { src, c in // FIXME: Make sure this calls memcpy when Element is bitwise movable. #if false // FIXME: UMBP.moveUpdate(fromContentsOf:) is broken as of 2026-09-17 (rdar://187733648) - let i = dst.moveUpdate(fromContentsOf: src._extracting(first: c)) + let i = unsafe dst.moveUpdate(fromContentsOf: src._extracting(first: c)) assert(i == count) #else - var d = dst._ptr(at: 0) - var s = src._ptr(at: 0) + var d = unsafe dst._ptr(at: 0) + var s = unsafe src._ptr(at: 0) for i in 0 ..< c { - d.pointee = s.move() - d += 1 - s += 1 + unsafe d.pointee = s.move() + unsafe d += 1 + unsafe s += 1 } #endif c = 0 @@ -120,7 +120,7 @@ extension MutableSpan /* where Element: Copyable */ { self.withUnsafeMutableBufferPointer { dst in source.withUnsafeBufferPointer { src in // FIXME: Make sure this calls memcpy when Element is BitwiseCopyable. - let i = dst._extracting(unchecked: subrange).update(fromContentsOf: src) + let i = unsafe dst._extracting(unchecked: subrange).update(fromContentsOf: src) precondition(i == subrange.count) } } @@ -138,7 +138,7 @@ extension MutableSpan /* where Element: Copyable */ { let i = self.withUnsafeMutableBufferPointer { dst in source.withUnsafeBufferPointer { src in // FIXME: Make sure this calls memcpy when Element is BitwiseCopyable. - dst.update(fromContentsOf: src) + unsafe dst.update(fromContentsOf: src) } } precondition(i == self.count) diff --git a/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift index 0eb01bed..69dc9712 100644 --- a/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift +++ b/Sources/InternalCollectionsUtilities/OutputSpan+Extras.swift @@ -18,10 +18,10 @@ package func withTemporaryOutputSpan capacity: Int, _ body: (inout OutputSpan) throws(E) -> R ) throws(E) -> R { - try _withUnsafeTemporaryAllocation( + unsafe try _withUnsafeTemporaryAllocation( of: Element.self, capacity: capacity ) { buffer throws(E) in - var span = OutputSpan(buffer: buffer, initializedCount: 0) + var span = unsafe OutputSpan(buffer: buffer, initializedCount: 0) return try body(&span) } } @@ -37,10 +37,10 @@ extension OutputSpan where Element: ~Copyable { @inlinable package mutating func _popLast() -> Element? { // FIXME: This needs to be in the stdlib. - withUnsafeMutableBufferPointer { buffer, count in + unsafe withUnsafeMutableBufferPointer { buffer, count in guard count > 0 else { return nil } count &-= 1 - return buffer.moveElement(from: count) + return unsafe buffer.moveElement(from: count) } } } @@ -50,15 +50,16 @@ extension OutputSpan where Element: ~Copyable { @inlinable @inline(__always) @_lifetime(self: copy self) + @unsafe package mutating func _append( moving source: UnsafeMutableBufferPointer ) { // FIXME: This needs to be in the stdlib. guard source.count > 0 else { return } - self.withUnsafeMutableBufferPointer { dst, dstCount in + unsafe self.withUnsafeMutableBufferPointer { dst, dstCount in let dstEnd = dstCount + source.count precondition(dstEnd <= dst.count, "OutputSpan capacity overflow") - dst + unsafe dst ._extracting(uncheckedFrom: dstCount, to: dstEnd) .moveInitializeAll(fromContentsOf: source) dstCount &+= source.count @@ -71,9 +72,9 @@ extension OutputSpan where Element: ~Copyable { @_lifetime(self: copy self) package mutating func _append(moving source: inout OutputSpan) { // FIXME: This needs to be in the stdlib. - source.withUnsafeMutableBufferPointer { src, srcCount in - let items = src._extracting(uncheckedFrom: 0, to: srcCount) - self._append(moving: items) + unsafe source.withUnsafeMutableBufferPointer { src, srcCount in + let items = unsafe src._extracting(uncheckedFrom: 0, to: srcCount) + unsafe self._append(moving: items) srcCount = 0 } } @@ -83,12 +84,13 @@ extension OutputSpan where Element: ~Copyable { extension OutputSpan /*where Element: Copyable*/ { @inlinable @_lifetime(self: copy self) + @unsafe package mutating func _append(copying source: UnsafeBufferPointer) { // FIXME: This needs to be in the stdlib. - self.withUnsafeMutableBufferPointer { dst, dstCount in + unsafe self.withUnsafeMutableBufferPointer { dst, dstCount in let dstEnd = dstCount + source.count precondition(dstEnd <= dst.count, "OutputSpan capacity overflow") - dst + unsafe dst ._extracting(uncheckedFrom: dstCount, to: dstEnd) .initializeAll(fromContentsOf: source) dstCount &+= source.count @@ -100,7 +102,7 @@ extension OutputSpan /*where Element: Copyable*/ { package mutating func _append(copying source: Span) { // FIXME: This needs to be in the stdlib. source.withUnsafeBufferPointer { buffer in - self._append(copying: buffer) + unsafe self._append(copying: buffer) } } } @@ -115,17 +117,17 @@ extension OutputSpan where Element: ~Copyable { ) { // FIXME: This needs to be in the stdlib. precondition(index >= 0 && index <= count, "Index out of bounds") - self.withUnsafeMutableBufferPointer { buffer, count in + unsafe self.withUnsafeMutableBufferPointer { buffer, count in var i = index var j = i // Invariant: i ..< j is uninitialized while j < count { - if shouldBeRemoved(buffer[j]) { - buffer.deinitializeElement(at: j) + if shouldBeRemoved(unsafe buffer[j]) { + unsafe buffer.deinitializeElement(at: j) j &+= 1 } else { if i != j { - buffer.initializeElement(at: i, to: buffer.moveElement(from: j)) + unsafe buffer.initializeElement(at: i, to: buffer.moveElement(from: j)) } i &+= 1 j &+= 1 @@ -153,13 +155,13 @@ extension OutputSpan where Element: ~Copyable { // the closure is quite important for usability. We can't name them both // `append(addingCount:initializingWith:)` though! precondition(newItemCount >= 0, "Cannot add a negative number of items") - return try withUnsafeMutableBufferPointer { buf, c throws(E) in + return unsafe try withUnsafeMutableBufferPointer { buf, c throws(E) in precondition(newItemCount <= buf.count - c, "OutputSpan capacity overflow") - let dst = buf._extracting(unchecked: Range( + let dst = unsafe buf._extracting(unchecked: Range( uncheckedBounds: (c, c &+ newItemCount))) - var span = OutputSpan(buffer: dst, initializedCount: 0) + var span = unsafe OutputSpan(buffer: dst, initializedCount: 0) defer { - c &+= span.finalize(for: dst) + c &+= unsafe span.finalize(for: dst) span = OutputSpan() } return try initializer(&span) diff --git a/Sources/InternalCollectionsUtilities/Span+Extras.swift b/Sources/InternalCollectionsUtilities/Span+Extras.swift index cb59b9f3..1ecef92a 100644 --- a/Sources/InternalCollectionsUtilities/Span+Extras.swift +++ b/Sources/InternalCollectionsUtilities/Span+Extras.swift @@ -13,6 +13,7 @@ @_frozen @usableFromInline +@unsafe package struct _ShamSpanIterator { // FIXME: Remove this when `Span.BorrowingIterator` becomes actually usable. // (I.e., when it exposes this data in a usable way.) @@ -37,10 +38,10 @@ extension Span.BorrowingIterator where Element: ~Copyable { _ body: (borrowing _ShamSpanIterator) -> R ) -> R { precondition( - MemoryLayout.stride == MemoryLayout<_ShamSpanIterator>.stride) + unsafe MemoryLayout.stride == MemoryLayout<_ShamSpanIterator>.stride) return Swift.withUnsafeBytes(of: &self) { buffer in - buffer.withMemoryRebound(to: _ShamSpanIterator.self) { shamBuffer in - return body(shamBuffer[0]) + unsafe buffer.withMemoryRebound(to: _ShamSpanIterator.self) { shamBuffer in + return unsafe body(shamBuffer[0]) } } } @@ -91,7 +92,7 @@ extension Span where Element: ~Copyable { if limit >= index, limit < end { end = limit } - let r = self.extracting(unchecked: Range(uncheckedBounds: (index, end))) + let r = unsafe self.extracting(unchecked: Range(uncheckedBounds: (index, end))) index = end return r } @@ -142,10 +143,10 @@ extension Span where Element: Equatable & ~Copyable { return self.withUnsafeBufferPointer { a in other.withUnsafeBufferPointer { b in guard a.count == b.count else { return false } - guard a.baseAddress != b.baseAddress else { return true } + guard unsafe a.baseAddress != b.baseAddress else { return true } var i = 0 while i < self.count { - guard a[i] == b[i] else { return false } + guard unsafe a[i] == b[i] else { return false } i &+= 1 } return true @@ -161,10 +162,10 @@ extension Span where Element: Equatable /* & ~Copyable */ { return self.withUnsafeBufferPointer { a in other.withUnsafeBufferPointer { b in guard a.count == b.count else { return false } - guard a.baseAddress != b.baseAddress else { return true } + guard unsafe a.baseAddress != b.baseAddress else { return true } var i = 0 while i < self.count { - guard a[i] == b[i] else { return false } + guard unsafe a[i] == b[i] else { return false } i &+= 1 } return true @@ -183,7 +184,7 @@ extension Span where Element: Hashable & ~Copyable { // separately when needed. var i = 0 while i < self.count { - hasher.combine(self[unchecked: i]) + hasher.combine(unsafe self[unchecked: i]) i &+= 1 } @@ -198,7 +199,7 @@ extension Span where Element: Hashable /* & ~Copyable */ { // separately when needed. var i = 0 while i < self.count { - hasher.combine(self[unchecked: i]) + hasher.combine(unsafe self[unchecked: i]) i &+= 1 } @@ -216,23 +217,23 @@ extension Span where Element: ~Copyable { let buffer = self.withUnsafeBufferPointer { buffer in limits.withUnsafeBufferPointer { limits in let start = buffer.baseAddress! - let end = start + buffer.count + let end = unsafe start + buffer.count let limitStart = limits.baseAddress! - let limitEnd = limitStart + limits.count + let limitEnd = unsafe limitStart + limits.count - let clampedStart = ( + let clampedStart = unsafe ( limitStart > start ? limitStart : limitEnd < start ? limitEnd : start) - let clampedEnd = ( + let clampedEnd = unsafe ( limitEnd < end ? limitEnd : limitStart > end ? limitStart : end) - let count = clampedEnd.distance(to: clampedStart) - return UnsafeBufferPointer(start: clampedStart, count: count) + let count = unsafe clampedEnd.distance(to: clampedStart) + return unsafe UnsafeBufferPointer(start: clampedStart, count: count) } } - return _overrideLifetime(Span(_unsafeElements: buffer), copying: self) + return unsafe _overrideLifetime(Span(_unsafeElements: buffer), copying: self) } } #endif diff --git a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift index e950f232..81c0965d 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet+Index.swift @@ -14,6 +14,7 @@ extension _UnsafeBitSet { @frozen @usableFromInline + @safe package struct Index: Comparable, Hashable { @usableFromInline internal typealias _Word = _UnsafeBitSet._Word diff --git a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift index 9044d407..faf6feff 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeBitSet/_UnsafeBitSet.swift @@ -15,6 +15,7 @@ /// primitives. @frozen @usableFromInline +@unsafe package struct _UnsafeBitSet { /// An unsafe-unowned storage view. @usableFromInline @@ -24,11 +25,13 @@ package struct _UnsafeBitSet { /// True when this handle does not support table mutations. /// (This is only checked in debug builds.) @usableFromInline + @safe internal let _mutable: Bool #endif @inlinable @inline(__always) + @safe package func ensureMutable() { #if DEBUG assert(_mutable) @@ -39,7 +42,7 @@ package struct _UnsafeBitSet { @inline(__always) package var _mutableWords: UnsafeMutableBufferPointer<_Word> { ensureMutable() - return UnsafeMutableBufferPointer(mutating: _words) + return unsafe UnsafeMutableBufferPointer(mutating: _words) } @inlinable @@ -48,8 +51,8 @@ package struct _UnsafeBitSet { words: UnsafeBufferPointer<_Word>, mutable: Bool ) { - assert(words.baseAddress != nil) - self._words = words + assert(unsafe words.baseAddress != nil) + unsafe self._words = words #if DEBUG self._mutable = mutable #endif @@ -61,15 +64,16 @@ package struct _UnsafeBitSet { words: UnsafeMutableBufferPointer<_Word>, mutable: Bool ) { - self.init(words: UnsafeBufferPointer(words), mutable: mutable) + unsafe self.init(words: UnsafeBufferPointer(words), mutable: mutable) } } extension _UnsafeBitSet { @inlinable @inline(__always) + @safe package var wordCount: Int { - _words.count + unsafe _words.count } } @@ -81,7 +85,7 @@ extension _UnsafeBitSet { run body: (inout _UnsafeBitSet) throws -> R ) rethrows -> R { let wordCount = _UnsafeBitSet.wordCount(forCapacity: UInt(capacity)) - return try withTemporaryBitSet(wordCount: wordCount, run: body) + return unsafe try withTemporaryBitSet(wordCount: wordCount, run: body) } @inlinable @@ -91,8 +95,8 @@ extension _UnsafeBitSet { run body: (inout Self) throws -> R ) rethrows -> R { var result: R? - try _withTemporaryBitSet(wordCount: wordCount) { bitset in - result = try body(&bitset) + unsafe try _withTemporaryBitSet(wordCount: wordCount) { bitset in + result = unsafe try body(&bitset) } return result! } @@ -103,9 +107,9 @@ extension _UnsafeBitSet { wordCount: Int, run body: (inout Self) throws -> Void ) rethrows { - try _withTemporaryUninitializedBitSet(wordCount: wordCount) { handle in - handle._mutableWords.initialize(repeating: .empty) - try body(&handle) + unsafe try _withTemporaryUninitializedBitSet(wordCount: wordCount) { handle in + unsafe handle._mutableWords.initialize(repeating: .empty) + unsafe try body(&handle) } } @@ -117,8 +121,8 @@ extension _UnsafeBitSet { return try withUnsafeTemporaryAllocation( of: _Word.self, capacity: wordCount ) { words in - var bitset = Self(words: words, mutable: true) - return try body(&bitset) + var bitset = unsafe Self(words: words, mutable: true) + return unsafe try body(&bitset) } } } @@ -126,16 +130,19 @@ extension _UnsafeBitSet { extension _UnsafeBitSet { @_effects(readnone) @inlinable @inline(__always) + @safe package static func wordCount(forCapacity capacity: UInt) -> Int { _Word.wordCount(forBitCount: capacity) } @inlinable @inline(__always) + @safe package var capacity: UInt { UInt(wordCount &* _Word.capacity) } @inlinable @inline(__always) + @safe internal func isWithinBounds(_ element: UInt) -> Bool { element < capacity } @@ -146,7 +153,7 @@ extension _UnsafeBitSet { package func contains(_ element: UInt) -> Bool { let (word, bit) = Index(element).split guard word < wordCount else { return false } - return _words[word].contains(bit) + return unsafe _words[word].contains(bit) } @_effects(releasenone) @@ -156,7 +163,7 @@ extension _UnsafeBitSet { ensureMutable() assert(isWithinBounds(element)) let index = Index(element) - return _mutableWords[index.word].insert(index.bit) + return unsafe _mutableWords[index.word].insert(index.bit) } @_effects(releasenone) @@ -165,8 +172,8 @@ extension _UnsafeBitSet { package mutating func remove(_ element: UInt) -> Bool { ensureMutable() let index = Index(element) - if index.word >= _words.count { return false } - return _mutableWords[index.word].remove(index.bit) + if unsafe index.word >= _words.count { return false } + return unsafe _mutableWords[index.word].remove(index.bit) } @_effects(releasenone) @@ -174,8 +181,8 @@ extension _UnsafeBitSet { package mutating func update(_ member: UInt, to newValue: Bool) -> Bool { ensureMutable() let (w, b) = Index(member).split - _mutableWords[w].update(b, to: newValue) - return w == _words.count &- 1 + unsafe _mutableWords[w].update(b, to: newValue) + return w == wordCount &- 1 } @_effects(releasenone) @@ -185,10 +192,10 @@ extension _UnsafeBitSet { guard max > 0 else { return } let (w, b) = Index(max).split for i in 0 ..< w { - _mutableWords[i] = .allBits + unsafe _mutableWords[i] = .allBits } if b > 0 { - _mutableWords[w].insertAll(upTo: b) + unsafe _mutableWords[w].insertAll(upTo: b) } } @@ -198,7 +205,7 @@ extension _UnsafeBitSet { @discardableResult package mutating func insert(_ element: Int) -> Bool { precondition(element >= 0) - return insert(UInt(bitPattern: element)) + return unsafe insert(UInt(bitPattern: element)) } @_alwaysEmitIntoClient @@ -207,7 +214,7 @@ extension _UnsafeBitSet { @discardableResult package mutating func remove(_ element: Int) -> Bool { guard element >= 0 else { return false } - return remove(UInt(bitPattern: element)) + return unsafe remove(UInt(bitPattern: element)) } @_alwaysEmitIntoClient @@ -215,28 +222,29 @@ extension _UnsafeBitSet { @inline(__always) package mutating func insertAll(upTo max: Int) { precondition(max >= 0) - return insertAll(upTo: UInt(bitPattern: max)) + return unsafe insertAll(upTo: UInt(bitPattern: max)) } } -extension _UnsafeBitSet: Sequence { +extension _UnsafeBitSet: @unsafe Sequence { @usableFromInline package typealias Element = UInt @inlinable @inline(__always) package var underestimatedCount: Int { - count // FIXME: really? + unsafe count // FIXME: really? } @inlinable @inline(__always) package func makeIterator() -> Iterator { - return Iterator(self) + return unsafe Iterator(self) } @frozen @usableFromInline + @unsafe package struct Iterator: IteratorProtocol { @usableFromInline internal let _bitset: _UnsafeBitSet @@ -245,26 +253,27 @@ extension _UnsafeBitSet: Sequence { internal var _index: Int @usableFromInline + @safe internal var _word: _Word @inlinable internal init(_ bitset: _UnsafeBitSet) { - self._bitset = bitset - self._index = 0 - self._word = bitset.wordCount > 0 ? bitset._words[0] : .empty + unsafe self._bitset = bitset + unsafe self._index = 0 + unsafe self._word = bitset.wordCount > 0 ? bitset._words[0] : .empty } @_effects(releasenone) @usableFromInline package mutating func next() -> UInt? { if let bit = _word.next() { - return Index(word: _index, bit: bit).value + return unsafe Index(word: _index, bit: bit).value } - while (_index + 1) < _bitset.wordCount { - _index += 1 - _word = _bitset._words[_index] + while unsafe (_index + 1) < _bitset.wordCount { + unsafe _index += 1 + unsafe _word = _bitset._words[_index] if let bit = _word.next() { - return Index(word: _index, bit: bit).value + return unsafe Index(word: _index, bit: bit).value } } return nil @@ -272,27 +281,28 @@ extension _UnsafeBitSet: Sequence { } } -extension _UnsafeBitSet: BidirectionalCollection { +extension _UnsafeBitSet: @unsafe BidirectionalCollection { @inlinable package var count: Int { - assert(_words.count <= Int.max / _Word.capacity) - return _words.reduce(0) { $0 &+ $1.count } + assert(unsafe _words.count <= Int.max / _Word.capacity) + return unsafe _words.reduce(0) { $0 &+ $1.count } } @inlinable @inline(__always) package var isEmpty: Bool { - _words.firstIndex(where: { !$0.isEmpty }) == nil + unsafe _words.firstIndex(where: { !$0.isEmpty }) == nil } @inlinable package var startIndex: Index { - let word = _words.firstIndex { !$0.isEmpty } + let word = unsafe _words.firstIndex { !$0.isEmpty } guard let word = word else { return endIndex } - return Index(word: word, bit: _words[word].firstMember!) + return unsafe Index(word: word, bit: _words[word].firstMember!) } @inlinable + @safe package var endIndex: Index { Index(word: wordCount, bit: 0) } @@ -307,14 +317,14 @@ extension _UnsafeBitSet: BidirectionalCollection { package func index(after index: Index) -> Index { precondition(index < endIndex, "Index out of bounds") var word = index.word - var w = _words[word] + var w = unsafe _words[word] w.removeAll(through: index.bit) while w.isEmpty { word += 1 guard word < wordCount else { return Index(word: wordCount, bit: 0) } - w = _words[word] + w = unsafe _words[word] } return Index(word: word, bit: w.firstMember!) } @@ -326,7 +336,7 @@ extension _UnsafeBitSet: BidirectionalCollection { var word = index.word var w: _Word if index.bit > 0 { - w = _words[word] + w = unsafe _words[word] w.removeAll(from: index.bit) } else { w = .empty @@ -334,7 +344,7 @@ extension _UnsafeBitSet: BidirectionalCollection { while w.isEmpty { word -= 1 precondition(word >= 0, "Cannot advance below startIndex") - w = _words[word] + w = unsafe _words[word] } return Index(word: word, bit: w.lastMember!) } @@ -352,7 +362,7 @@ extension _UnsafeBitSet: BidirectionalCollection { if w1 == w2 { guard w1 < wordCount else { return 0 } let mask = _Word(from: b1, to: b2) - let c = _words[w1].intersection(mask).count + let c = unsafe _words[w1].intersection(mask).count return isNegative ? -c : c } @@ -360,14 +370,14 @@ extension _UnsafeBitSet: BidirectionalCollection { var w = w1 guard w < wordCount else { return 0 } - c &+= _words[w].subtracting(_Word(upTo: b1)).count + c &+= unsafe _words[w].subtracting(_Word(upTo: b1)).count w &+= 1 while w < w2 { - c &+= _words[w].count + c &+= unsafe _words[w].count w &+= 1 } guard w < wordCount else { return isNegative ? -c : c } - c &+= _words[w].intersection(_Word(upTo: b2)).count + c &+= unsafe _words[w].intersection(_Word(upTo: b2)).count return isNegative ? -c : c } @@ -375,19 +385,19 @@ extension _UnsafeBitSet: BidirectionalCollection { @usableFromInline package func index(_ i: Index, offsetBy distance: Int) -> Index { precondition(i <= endIndex, "Index out of bounds") - precondition(i == endIndex || contains(i.value), "Invalid index") + precondition(unsafe i == endIndex || contains(i.value), "Invalid index") guard distance != 0 else { return i } var remaining = distance.magnitude if distance > 0 { var (w, b) = i.split precondition(w < wordCount, "Index out of bounds") - if let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) { + if let v = unsafe _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) { return Index(word: w, bit: v) } while true { w &+= 1 guard w < wordCount else { break } - if let v = _words[w].nthElement(&remaining) { + if let v = unsafe _words[w].nthElement(&remaining) { return Index(word: w, bit: v) } } @@ -399,14 +409,14 @@ extension _UnsafeBitSet: BidirectionalCollection { remaining -= 1 var (w, b) = i.endSplit if w < wordCount { - if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) { + if let v = unsafe _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) { return Index(word: w, bit: v) } } while true { precondition(w > 0, "Index out of bounds") w &-= 1 - if let v = _words[w].nthElementFromEnd(&remaining) { + if let v = unsafe _words[w].nthElementFromEnd(&remaining) { return Index(word: w, bit: v) } } @@ -418,16 +428,16 @@ extension _UnsafeBitSet: BidirectionalCollection { _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { precondition(i <= endIndex && limit <= endIndex, "Index out of bounds") - precondition(i == endIndex || contains(i.value), "Invalid index") + precondition(unsafe i == endIndex || contains(i.value), "Invalid index") guard distance != 0 else { return i } var remaining = distance.magnitude if distance > 0 { guard i <= limit else { - return self.index(i, offsetBy: distance) + return unsafe self.index(i, offsetBy: distance) } var (w, b) = i.split if w < wordCount, - let v = _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) + let v = unsafe _words[w].subtracting(_Word(upTo: b)).nthElement(&remaining) { let r = Index(word: w, bit: v) return r <= limit ? r : nil @@ -435,7 +445,7 @@ extension _UnsafeBitSet: BidirectionalCollection { let maxWord = Swift.min(wordCount - 1, limit.word) while w < maxWord { w &+= 1 - if let v = _words[w].nthElement(&remaining) { + if let v = unsafe _words[w].nthElement(&remaining) { let r = Index(word: w, bit: v) return r <= limit ? r : nil } @@ -445,12 +455,12 @@ extension _UnsafeBitSet: BidirectionalCollection { // distance < 0 guard i >= limit else { - return self.index(i, offsetBy: distance) + return unsafe self.index(i, offsetBy: distance) } remaining &-= 1 var (w, b) = i.endSplit if w < wordCount { - if let v = _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) { + if let v = unsafe _words[w].intersection(_Word(upTo: b)).nthElementFromEnd(&remaining) { let r = Index(word: w, bit: v) return r >= limit ? r : nil } @@ -458,7 +468,7 @@ extension _UnsafeBitSet: BidirectionalCollection { let minWord = limit.word while w > minWord { w &-= 1 - if let v = _words[w].nthElementFromEnd(&remaining) { + if let v = unsafe _words[w].nthElementFromEnd(&remaining) { let r = Index(word: w, bit: v) return r >= limit ? r : nil } diff --git a/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift index c9c49bb6..667b0de8 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeBufferPointer+Extras.swift @@ -14,9 +14,10 @@ extension UnsafeBufferPointer where Element: ~Copyable{ @inlinable @inline(__always) + @unsafe package func _ptr(at index: Int) -> UnsafePointer { assert(index >= 0 && index < count) - return baseAddress.unsafelyUnwrapped + index + return unsafe baseAddress.unsafelyUnwrapped + index } } @@ -24,24 +25,27 @@ extension UnsafeBufferPointer where Element: ~Copyable { /// Returns a Boolean value indicating whether two `UnsafeBufferPointer` /// instances refer to the same region in memory. @inlinable @inline(__always) + @safe package func _isIdentical(to other: Self) -> Bool { - (self.baseAddress == other.baseAddress) && (self.count == other.count) + unsafe (self.baseAddress == other.baseAddress) && (self.count == other.count) } @inlinable @inline(__always) + @safe package static var _empty: Self { - .init(start: nil, count: 0) + unsafe .init(start: nil, count: 0) } } extension UnsafeBufferPointer where Element: ~Copyable { @_alwaysEmitIntoClient + @unsafe package func _extracting(uncheckedFrom start: Int, to end: Int) -> Self { guard let base = self.baseAddress else { return Self(_empty: ()) } - return Self(start: base + start, count: end - start) + return unsafe Self(start: base + start, count: end - start) } /// Returns a buffer pointer containing the initial elements of this buffer, @@ -61,10 +65,11 @@ extension UnsafeBufferPointer where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient @inline(__always) + @safe package func _extracting(first maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a prefix of negative length") let newCount = Swift.min(maxLength, count) - return Self(start: baseAddress, count: newCount) + return unsafe Self(start: baseAddress, count: newCount) } /// Returns a buffer pointer containing all but the given number of initial @@ -84,10 +89,11 @@ extension UnsafeBufferPointer where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient @inline(__always) + @safe package func _extracting(droppingFirst maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a prefix of negative length") let cut = Swift.min(maxLength, count) - return Self(start: baseAddress?.advanced(by: cut), count: count &- cut) + return unsafe Self(start: baseAddress?.advanced(by: cut), count: count &- cut) } /// Returns a buffer pointer containing the final elements of this buffer, @@ -107,10 +113,11 @@ extension UnsafeBufferPointer where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient @inline(__always) + @safe package func _extracting(last maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a suffix of negative length") let newCount = Swift.min(maxLength, count) - return extracting(Range(uncheckedBounds: (count - newCount, count))) + return unsafe extracting(Range(uncheckedBounds: (count - newCount, count))) } /// Returns a buffer pointer containing all but the given number of trailing @@ -130,33 +137,36 @@ extension UnsafeBufferPointer where Element: ~Copyable { /// - Complexity: O(1) @_alwaysEmitIntoClient @inline(__always) + @safe package func _extracting(droppingLast maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a prefix of negative length") let newCount = count &- Swift.min(maxLength, count) - return Self(start: baseAddress, count: newCount) + return unsafe Self(start: baseAddress, count: newCount) } } extension UnsafeBufferPointer where Element: ~Copyable { @_alwaysEmitIntoClient + @safe package mutating func _trim(first maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a prefix of negative length") let cut = Swift.min(maxLength, count) - guard cut > 0 else { return .init(start: nil, count: 0) } - let oldStart = baseAddress.unsafelyUnwrapped - self = Self(start: oldStart + cut, count: count - cut) - return Self(start: oldStart, count: cut) + guard cut > 0 else { return unsafe .init(start: nil, count: 0) } + let oldStart = unsafe baseAddress.unsafelyUnwrapped + unsafe self = Self(start: oldStart + cut, count: count - cut) + return unsafe Self(start: oldStart, count: cut) } @_alwaysEmitIntoClient + @safe package mutating func _trim(last maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a suffix of negative length") let cut = Swift.min(maxLength, count) - guard cut > 0 else { return .init(start: nil, count: 0) } - let oldStart = baseAddress.unsafelyUnwrapped + guard cut > 0 else { return unsafe .init(start: nil, count: 0) } + let oldStart = unsafe baseAddress.unsafelyUnwrapped let newCount = count &- cut - self = .init(start: oldStart, count: newCount) - return Self(start: oldStart + newCount, count: cut) + unsafe self = .init(start: oldStart, count: newCount) + return unsafe Self(start: oldStart + newCount, count: cut) } } diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift index 61ea9fbb..dc634d5b 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeMutableBufferPointer+Extras.swift @@ -14,9 +14,10 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { @inlinable @inline(__always) + @unsafe package func _ptr(at index: Int) -> UnsafeMutablePointer { assert(index >= 0 && index < count) - return baseAddress.unsafelyUnwrapped + index + return unsafe baseAddress.unsafelyUnwrapped + index } } @@ -25,35 +26,39 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { /// `UnsafeMutableBufferPointer` instances refer to the same region in /// memory. @inlinable @inline(__always) + @safe package func _isIdentical(to other: Self) -> Bool { - (self.baseAddress == other.baseAddress) && (self.count == other.count) + unsafe (self.baseAddress == other.baseAddress) && (self.count == other.count) } @inlinable @inline(__always) + @safe package static var _empty: Self { - .init(start: nil, count: 0) + unsafe .init(start: nil, count: 0) } } extension UnsafeMutableBufferPointer where Element: ~Copyable { @_alwaysEmitIntoClient @inline(__always) + @unsafe package func _extracting(unchecked bounds: Range) -> Self { assert(bounds.lowerBound >= 0 && bounds.upperBound <= count, "Index out of range") guard let start = self.baseAddress else { - return Self(start: nil, count: 0) + return unsafe Self(start: nil, count: 0) } - return Self(start: start + bounds.lowerBound, count: bounds.count) + return unsafe Self(start: start + bounds.lowerBound, count: bounds.count) } @_alwaysEmitIntoClient + @unsafe package func _extracting(uncheckedFrom start: Int, to end: Int) -> Self { guard let base = self.baseAddress else { return Self(_empty: ()) } - return Self(start: base + start, count: end - start) + return unsafe Self(start: base + start, count: end - start) } /// Returns a buffer pointer containing the initial elements of this buffer, @@ -76,7 +81,7 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { package func _extracting(first maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a prefix of negative length") let newCount = Swift.min(maxLength, count) - return Self(start: baseAddress, count: newCount) + return unsafe Self(start: baseAddress, count: newCount) } /// Returns a buffer pointer containing all but the given number of initial @@ -99,7 +104,7 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { package func _extracting(droppingFirst maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a prefix of negative length") let cut = Swift.min(maxLength, count) - return Self(start: baseAddress?.advanced(by: cut), count: count &- cut) + return unsafe Self(start: baseAddress?.advanced(by: cut), count: count &- cut) } /// Returns a buffer pointer containing the final elements of this buffer, @@ -122,7 +127,7 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { package func _extracting(last maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a suffix of negative length") let newCount = Swift.min(maxLength, count) - return extracting(Range(uncheckedBounds: (count - newCount, count))) + return unsafe extracting(Range(uncheckedBounds: (count - newCount, count))) } /// Returns a buffer pointer containing all but the given number of trailing @@ -145,7 +150,7 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { package func _extracting(droppingLast maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a prefix of negative length") let newCount = count &- Swift.min(maxLength, count) - return Self(start: baseAddress, count: newCount) + return unsafe Self(start: baseAddress, count: newCount) } } @@ -155,10 +160,10 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { package mutating func _trim(first maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a prefix of negative length") let cut = Swift.min(maxLength, count) - guard cut > 0 else { return .init(start: nil, count: 0) } - let oldStart = baseAddress.unsafelyUnwrapped - self = Self(start: oldStart + cut, count: count - cut) - return Self(start: oldStart, count: cut) + guard cut > 0 else { return unsafe .init(start: nil, count: 0) } + let oldStart = unsafe baseAddress.unsafelyUnwrapped + unsafe self = Self(start: oldStart + cut, count: count - cut) + return unsafe Self(start: oldStart, count: cut) } @_alwaysEmitIntoClient @@ -166,11 +171,11 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { package mutating func _trim(last maxLength: Int) -> Self { precondition(maxLength >= 0, "Cannot have a suffix of negative length") let cut = Swift.min(maxLength, count) - guard cut > 0 else { return .init(start: nil, count: 0) } - let oldStart = baseAddress.unsafelyUnwrapped + guard cut > 0 else { return unsafe .init(start: nil, count: 0) } + let oldStart = unsafe baseAddress.unsafelyUnwrapped let newCount = count &- cut - self = .init(start: oldStart, count: newCount) - return Self(start: oldStart + newCount, count: cut) + unsafe self = .init(start: oldStart, count: newCount) + return unsafe Self(start: oldStart + newCount, count: cut) } } @@ -181,7 +186,7 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { ) -> Int { if source.isEmpty { return 0 } precondition(source.count <= self.count) - self.baseAddress.unsafelyUnwrapped.moveInitialize( + unsafe self.baseAddress.unsafelyUnwrapped.moveInitialize( from: source.baseAddress.unsafelyUnwrapped, count: source.count) return source.count } @@ -202,7 +207,7 @@ extension UnsafeMutableBufferPointer { ) -> Int { if source.isEmpty { return 0 } precondition(source.count <= self.count) - self.baseAddress.unsafelyUnwrapped.initialize( + unsafe self.baseAddress.unsafelyUnwrapped.initialize( from: source.baseAddress.unsafelyUnwrapped, count: source.count) return source.count } @@ -211,7 +216,7 @@ extension UnsafeMutableBufferPointer { package func _initializePrefix( copying source: UnsafeMutableBufferPointer ) -> Int { - _initializePrefix(copying: UnsafeBufferPointer(source)) + unsafe _initializePrefix(copying: UnsafeBufferPointer(source)) } /// Initialize slots at the start of this buffer by copying data from `source`. @@ -225,7 +230,9 @@ extension UnsafeMutableBufferPointer { @available(SwiftStdlib 5.0, *) @inlinable package func _initializePrefix(copying source: Span) -> Int { - source.withUnsafeBufferPointer { self._initializePrefix(copying: $0) } + source.withUnsafeBufferPointer { + unsafe self._initializePrefix(copying: $0) + } } /// Initialize slots at the start of this buffer by copying data from `buffer`, then @@ -238,8 +245,8 @@ extension UnsafeMutableBufferPointer { /// The count of `buffer` must not be greater than `self.count`. @inlinable package mutating func _initializeAndDropPrefix(copying source: UnsafeBufferPointer) { - let i = _initializePrefix(copying: source) - self = self.extracting(i...) + let i = unsafe _initializePrefix(copying: source) + unsafe self = self.extracting(i...) } /// Initialize slots at the start of this buffer by copying data from `span`, then @@ -254,7 +261,7 @@ extension UnsafeMutableBufferPointer { @inlinable package mutating func _initializeAndDropPrefix(copying span: Span) { span.withUnsafeBufferPointer { buffer in - self._initializeAndDropPrefix(copying: buffer) + unsafe self._initializeAndDropPrefix(copying: buffer) } } } @@ -265,8 +272,8 @@ extension UnsafeMutableBufferPointer { guard source.count > 0 else { return 0 } precondition( source.count <= self.count, - "buffer cannot contain every element from source.") - baseAddress.unsafelyUnwrapped.initialize( + "buffer cannot contain every element from source") + unsafe baseAddress.unsafelyUnwrapped.initialize( from: source.baseAddress.unsafelyUnwrapped, count: source.count) return source.count @@ -274,12 +281,12 @@ extension UnsafeMutableBufferPointer { @inlinable package func initialize(fromContentsOf source: Slice) -> Index { - let sourceCount = source.count + let sourceCount = unsafe source.count guard sourceCount > 0 else { return 0 } precondition( sourceCount <= self.count, - "buffer cannot contain every element from source.") - baseAddress.unsafelyUnwrapped.initialize( + "buffer cannot contain every element from source") + unsafe baseAddress.unsafelyUnwrapped.initialize( from: source.base.baseAddress.unsafelyUnwrapped + source.startIndex, count: sourceCount) return sourceCount @@ -293,9 +300,9 @@ extension Slice { ) -> Index where Base == UnsafeMutableBufferPointer { - let target = UnsafeMutableBufferPointer(rebasing: self) - let i = target.initialize(fromContentsOf: source) - return self.startIndex + i + let target = unsafe UnsafeMutableBufferPointer(rebasing: self) + let i = unsafe target.initialize(fromContentsOf: source) + return unsafe self.startIndex + i } @inlinable @inline(__always) @@ -304,9 +311,9 @@ extension Slice { ) -> Index where Base == UnsafeMutableBufferPointer { - let target = UnsafeMutableBufferPointer(rebasing: self) - let i = target.initialize(fromContentsOf: source) - return self.startIndex + i + let target = unsafe UnsafeMutableBufferPointer(rebasing: self) + let i = unsafe target.initialize(fromContentsOf: source) + return unsafe self.startIndex + i } } @@ -315,19 +322,19 @@ extension UnsafeMutableBufferPointer { package func initializeAll( fromContentsOf source: C ) where C.Element == Element { - let i = self.initialize(fromContentsOf: source) + let i = unsafe self.initialize(fromContentsOf: source) assert(i == self.endIndex) } @inlinable @inline(__always) package func initializeAll(fromContentsOf source: Self) { - let i = self.initialize(fromContentsOf: source) + let i = unsafe self.initialize(fromContentsOf: source) assert(i == self.endIndex) } @inlinable @inline(__always) package func initializeAll(fromContentsOf source: Slice) { - let i = self.initialize(fromContentsOf: source) + let i = unsafe self.initialize(fromContentsOf: source) assert(i == self.endIndex) } } @@ -335,7 +342,7 @@ extension UnsafeMutableBufferPointer { extension UnsafeMutableBufferPointer where Element: ~Copyable { @inlinable @inline(__always) package func moveInitializeAll(fromContentsOf source: Self) { - let i = self.moveInitialize(fromContentsOf: source) + let i = unsafe self.moveInitialize(fromContentsOf: source) assert(i == self.endIndex) } } @@ -343,7 +350,7 @@ extension UnsafeMutableBufferPointer where Element: ~Copyable { extension UnsafeMutableBufferPointer { @inlinable @inline(__always) package func moveInitializeAll(fromContentsOf source: Slice) { - let i = self.moveInitialize(fromContentsOf: source) + let i = unsafe self.moveInitialize(fromContentsOf: source) assert(i == self.endIndex) } } @@ -353,39 +360,39 @@ extension Slice { package func initializeAll( fromContentsOf source: C ) where Base == UnsafeMutableBufferPointer { - let i = self.initialize(fromContentsOf: source) - assert(i == self.endIndex) + let i = unsafe self.initialize(fromContentsOf: source) + assert(unsafe i == self.endIndex) } @inlinable @inline(__always) package func initializeAll( fromContentsOf source: UnsafeMutableBufferPointer ) where Base == UnsafeMutableBufferPointer { - let target = UnsafeMutableBufferPointer(rebasing: self) - target.initializeAll(fromContentsOf: source) + let target = unsafe UnsafeMutableBufferPointer(rebasing: self) + unsafe target.initializeAll(fromContentsOf: source) } @inlinable @inline(__always) package func initializeAll( fromContentsOf source: Slice> ) where Base == UnsafeMutableBufferPointer { - let target = UnsafeMutableBufferPointer(rebasing: self) - target.initializeAll(fromContentsOf: source) + let target = unsafe UnsafeMutableBufferPointer(rebasing: self) + unsafe target.initializeAll(fromContentsOf: source) } @inlinable @inline(__always) package func moveInitializeAll( fromContentsOf source: UnsafeMutableBufferPointer ) where Base == UnsafeMutableBufferPointer { - let target = UnsafeMutableBufferPointer(rebasing: self) - target.moveInitializeAll(fromContentsOf: source) + let target = unsafe UnsafeMutableBufferPointer(rebasing: self) + unsafe target.moveInitializeAll(fromContentsOf: source) } @inlinable @inline(__always) package func moveInitializeAll( fromContentsOf source: Slice> ) where Base == UnsafeMutableBufferPointer { - let target = UnsafeMutableBufferPointer(rebasing: self) - target.moveInitializeAll(fromContentsOf: source) + let target = unsafe UnsafeMutableBufferPointer(rebasing: self) + unsafe target.moveInitializeAll(fromContentsOf: source) } } diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutablePointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeMutablePointer+Extras.swift index e29177da..ac7e56a0 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeMutablePointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeMutablePointer+Extras.swift @@ -37,6 +37,6 @@ extension UnsafeMutablePointer where Pointee: ~Copyable { @_alwaysEmitIntoClient @_transparent package static func _dangling() -> Self { - return Self(mutating: ._dangling()) + return unsafe Self(mutating: ._dangling()) } } diff --git a/Sources/InternalCollectionsUtilities/UnsafeMutableRawBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeMutableRawBufferPointer+Extras.swift index f468b380..1caa19b8 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeMutableRawBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeMutableRawBufferPointer+Extras.swift @@ -16,8 +16,9 @@ extension UnsafeMutableRawBufferPointer { /// `UnsafeMutableRawBufferPointer` instances refer to the same region in /// memory. @inlinable @inline(__always) + @safe package func _isIdentical(to other: Self) -> Bool { - (self.baseAddress == other.baseAddress) && (self.count == other.count) + unsafe (self.baseAddress == other.baseAddress) && (self.count == other.count) } } diff --git a/Sources/InternalCollectionsUtilities/UnsafePointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafePointer+Extras.swift index 32c6b8bd..b7a9c74c 100644 --- a/Sources/InternalCollectionsUtilities/UnsafePointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafePointer+Extras.swift @@ -33,6 +33,6 @@ extension UnsafePointer where Pointee: ~Copyable { @_transparent package static func _dangling() -> Self { let align = MemoryLayout.alignment - return Self(bitPattern: align).unsafelyUnwrapped + return unsafe Self(bitPattern: align).unsafelyUnwrapped } } diff --git a/Sources/InternalCollectionsUtilities/UnsafeRawBufferPointer+Extras.swift b/Sources/InternalCollectionsUtilities/UnsafeRawBufferPointer+Extras.swift index f4d25ccf..5fd4b549 100644 --- a/Sources/InternalCollectionsUtilities/UnsafeRawBufferPointer+Extras.swift +++ b/Sources/InternalCollectionsUtilities/UnsafeRawBufferPointer+Extras.swift @@ -15,7 +15,8 @@ extension UnsafeRawBufferPointer { /// Returns a Boolean value indicating whether two `UnsafeRawBufferPointer` /// instances refer to the same region in memory. @inlinable @inline(__always) - package func _isIdentical(to other: Self) -> Bool { - (self.baseAddress == other.baseAddress) && (self.count == other.count) + @safe + package func _isIdentical(to other: Self) -> Bool { + unsafe (self.baseAddress == other.baseAddress) && (self.count == other.count) } } diff --git a/Sources/OrderedCollections/HashTable/_HashTable+BucketIterator.swift b/Sources/OrderedCollections/HashTable/_HashTable+BucketIterator.swift index 9b6e7631..259296ef 100644 --- a/Sources/OrderedCollections/HashTable/_HashTable+BucketIterator.swift +++ b/Sources/OrderedCollections/HashTable/_HashTable+BucketIterator.swift @@ -29,6 +29,7 @@ extension _HashTable { /// iterator values outside the closure call that produced the original /// hash table. @usableFromInline + @unsafe package struct BucketIterator { @usableFromInline package typealias Bucket = _HashTable.Bucket @@ -38,29 +39,34 @@ extension _HashTable { /// The current position within the hash table. @usableFromInline + @safe package var _currentBucket: Bucket /// The raw bucket value corresponding to `_currentBucket`. + @safe internal var _currentRawValue: UInt64 /// Remaining bits not yet processed from the last word read. + @safe internal var _nextBits: UInt64 /// Count of usable bits in `_nextBits`. (They start at bit 0.) + @safe internal var _remainingBitCount: Int + @safe internal var _wrappedAround = false /// Create a new iterator starting at the specified bucket. @_effects(releasenone) @usableFromInline package init(hashTable: _UnsafeHashTable, startingAt bucket: Bucket) { - assert(hashTable.scale >= _HashTable.minimumScale) - assert(bucket.offset >= 0 && bucket.offset < hashTable.bucketCount) - self._hashTable = hashTable + assert(unsafe hashTable.scale >= _HashTable.minimumScale) + assert(unsafe bucket.offset >= 0 && bucket.offset < hashTable.bucketCount) + unsafe self._hashTable = hashTable self._currentBucket = bucket (self._currentRawValue, self._nextBits, self._remainingBitCount) - = hashTable._startIterator(bucket: bucket) + = unsafe hashTable._startIterator(bucket: bucket) } } } @@ -73,14 +79,14 @@ extension _HashTable.UnsafeHandle { @inlinable @inline(__always) package func idealBucket(forHashValue hashValue: Int) -> Bucket { - return Bucket(offset: hashValue & (bucketCount - 1)) + return Bucket(offset: unsafe hashValue & (bucketCount - 1)) } @inlinable @inline(__always) package func idealBucket(for element: Element) -> Bucket { - let hashValue = element._rawHashValue(seed: seed) - return idealBucket(forHashValue: hashValue) + let hashValue = element._rawHashValue(seed: unsafe seed) + return unsafe idealBucket(forHashValue: hashValue) } /// Return a bucket iterator for the chain starting at the bucket corresponding @@ -88,15 +94,15 @@ extension _HashTable.UnsafeHandle { @inlinable @inline(__always) package func bucketIterator(for element: Element) -> BucketIterator { - let bucket = idealBucket(for: element) - return bucketIterator(startingAt: bucket) + let bucket = unsafe idealBucket(for: element) + return unsafe bucketIterator(startingAt: bucket) } /// Return a bucket iterator for the chain starting at the specified bucket. @inlinable @inline(__always) package func bucketIterator(startingAt bucket: Bucket) -> BucketIterator { - BucketIterator(hashTable: self, startingAt: bucket) + unsafe BucketIterator(hashTable: self, startingAt: bucket) } @usableFromInline @@ -104,8 +110,8 @@ extension _HashTable.UnsafeHandle { package func startFind( _ startBucket: Bucket ) -> (iterator: BucketIterator, currentValue: Int?) { - let iterator = bucketIterator(startingAt: startBucket) - return (iterator, iterator.currentValue) + let iterator = unsafe bucketIterator(startingAt: startBucket) + return unsafe (iterator, iterator.currentValue) } @_effects(readonly) @@ -117,28 +123,28 @@ extension _HashTable.UnsafeHandle { // which is why the code below needs to special case it. // (For all scales > 5, the last bucket ends exactly on a word boundary.) - var (word, bit) = self.position(of: bucket) - if bit + scale <= 64 { + var (word, bit) = unsafe self.position(of: bucket) + if unsafe bit + scale <= 64 { // We're in luck, the current bucket is stored entirely within one word. - let w = self[word: word] - let currentRawValue = (w &>> bit) & bucketMask - let c = (scale == 5 && word == wordCount - 1 ? 32 : 64) - let remainingBitCount = c - (bit + scale) - let nextBits = (remainingBitCount == 0 ? 0 : w &>> (bit + scale)) + let w = unsafe self[word: word] + let currentRawValue = unsafe (w &>> bit) & bucketMask + let c = unsafe (scale == 5 && word == wordCount - 1 ? 32 : 64) + let remainingBitCount = unsafe c - (bit + scale) + let nextBits = unsafe (remainingBitCount == 0 ? 0 : w &>> (bit + scale)) assert(remainingBitCount >= 0) assert(bit < c) return (currentRawValue, nextBits, remainingBitCount) } else { // We need to read two words. - assert(scale != 5 || word < wordCount - 1) + assert(unsafe scale != 5 || word < wordCount - 1) assert(bit > 0) - let w1 = self[word: word] - word = self.word(after: word) - let w2 = self[word: word] - let currentRawValue = ((w1 &>> bit) | (w2 &<< (64 - bit))) & bucketMask - let overhang = scale - (64 - bit) + let w1 = unsafe self[word: word] + word = unsafe self.word(after: word) + let w2 = unsafe self[word: word] + let currentRawValue = unsafe ((w1 &>> bit) | (w2 &<< (64 - bit))) & bucketMask + let overhang = unsafe scale - (64 - bit) let nextBits = w2 &>> overhang - let c = (scale == 5 && word == wordCount - 1 ? 32 : 64) + let c = unsafe (scale == 5 && word == wordCount - 1 ? 32 : 64) let remainingBitCount = c - overhang return (currentRawValue, nextBits, remainingBitCount) } @@ -149,17 +155,18 @@ extension _HashTable.BucketIterator { /// The scale of the hash table. A table of scale *n* holds 2^*n* buckets, /// each of which contain an *n*-bit value. @inline(__always) - internal var _scale: Int { _hashTable.scale } + internal var _scale: Int { unsafe _hashTable.scale } /// The current position within the hash table. @inlinable @inline(__always) + @safe package var currentBucket: Bucket { _currentBucket } // For testing @usableFromInline package func isIdentical(to other: Self) -> Bool { - self._hashTable.isIdentical(to: other._hashTable) + unsafe self._hashTable.isIdentical(to: other._hashTable) && self.currentBucket == other.currentBucket && self._currentRawValue == other._currentRawValue && self.currentValue == other.currentValue @@ -169,6 +176,7 @@ extension _HashTable.BucketIterator { } @usableFromInline + @safe package var isOccupied: Bool { @_effects(readonly) @inline(__always) @@ -185,20 +193,22 @@ extension _HashTable.BucketIterator { package var currentValue: Int? { @inline(__always) @_effects(readonly) - get { _hashTable._value(forBucketContents: _currentRawValue) } + get { + unsafe _hashTable._value(forBucketContents: _currentRawValue) + } @_effects(releasenone) set { - _hashTable.assertMutable() - let v = _hashTable._bucketContents(for: newValue) + unsafe _hashTable.assertMutable() + let v = unsafe _hashTable._bucketContents(for: newValue) let pattern = v ^ _currentRawValue - assert(_currentBucket.offset < _hashTable.bucketCount) - let (word, bit) = _hashTable.position(of: _currentBucket) - _hashTable[word: word] ^= pattern &<< bit + assert(unsafe _currentBucket.offset < _hashTable.bucketCount) + let (word, bit) = unsafe _hashTable.position(of: _currentBucket) + unsafe _hashTable[word: word] ^= pattern &<< bit let extractedBits = 64 - bit - if extractedBits < _scale { - let word2 = _hashTable.word(after: word) - _hashTable[word: word2] ^= pattern &>> extractedBits + if unsafe extractedBits < _scale { + let word2 = unsafe _hashTable.word(after: word) + unsafe _hashTable[word: word2] ^= pattern &>> extractedBits } _currentRawValue = v } @@ -220,7 +230,7 @@ extension _HashTable.BucketIterator { package mutating func advance() { // Advance to next bucket, checking for wraparound condition. _currentBucket.offset &+= 1 - if _currentBucket.offset == _hashTable.bucketCount { + if unsafe _currentBucket.offset == _hashTable.bucketCount { guard !_wrappedAround else { // Prevent wasting battery in an infinite loop if a hash table // somehow becomes corrupt. @@ -231,30 +241,30 @@ extension _HashTable.BucketIterator { } // If we have loaded enough bits, eat them and return. - if _remainingBitCount >= _scale { - _currentRawValue = _nextBits & _hashTable.bucketMask - _nextBits &>>= _scale - _remainingBitCount -= _scale + if unsafe _remainingBitCount >= _scale { + unsafe _currentRawValue = _nextBits & _hashTable.bucketMask + unsafe _nextBits &>>= _scale + unsafe _remainingBitCount -= _scale return } // Load the next batch of bits. - var word = _hashTable.position(of: _currentBucket).word + var word = unsafe _hashTable.position(of: _currentBucket).word if _remainingBitCount != 0 { - word = _hashTable.word(after: word) + word = unsafe _hashTable.word(after: word) } - let c = (_hashTable.scale == 5 && word == _hashTable.wordCount - 1 ? 32 : 64) - let w = _hashTable[word: word] - _currentRawValue = (_nextBits | (w &<< _remainingBitCount)) & _hashTable.bucketMask - _nextBits = w &>> (_scale - _remainingBitCount) - _remainingBitCount = c - (_scale - _remainingBitCount) + let c = unsafe (_hashTable.scale == 5 && word == _hashTable.wordCount - 1 ? 32 : 64) + let w = unsafe _hashTable[word: word] + _currentRawValue = unsafe (_nextBits | (w &<< _remainingBitCount)) & _hashTable.bucketMask + _nextBits = unsafe w &>> (_scale - _remainingBitCount) + _remainingBitCount = unsafe c - (_scale - _remainingBitCount) } @usableFromInline @_effects(releasenone) package mutating func findNext() -> Int? { - advance() - return currentValue + unsafe advance() + return unsafe currentValue } /// Advance this iterator until it points to an occupied bucket with the @@ -262,8 +272,8 @@ extension _HashTable.BucketIterator { @inlinable @_effects(releasenone) package mutating func advance(until expected: Int) { - while isOccupied && currentValue != expected { - advance() + while unsafe isOccupied && currentValue != expected { + unsafe advance() } } @@ -273,7 +283,7 @@ extension _HashTable.BucketIterator { @_effects(releasenone) package mutating func advanceToNextUnoccupiedBucket() { while isOccupied { - advance() + unsafe advance() } } } diff --git a/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift b/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift index cd801a93..c3df4622 100644 --- a/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift +++ b/Sources/OrderedCollections/HashTable/_HashTable+CustomStringConvertible.swift @@ -28,12 +28,12 @@ extension _HashTable.Header: CustomStringConvertible { extension _HashTable.UnsafeHandle: CustomStringConvertible { package func _description(type: String) -> String { var d = """ - \(type)\(_header.pointee._description) - load factor: \(debugLoadFactor()) + \(type)\(unsafe _header.pointee._description) + load factor: \(unsafe debugLoadFactor()) """ - if bucketCount < 128 { + if unsafe bucketCount < 128 { d += "\n " - d += debugContents() + d += unsafe debugContents() .lazy .map { $0 == nil ? "_" : "\($0!)" } .joined(separator: " ") @@ -43,21 +43,21 @@ extension _HashTable.UnsafeHandle: CustomStringConvertible { @usableFromInline package var description: String { - _description(type: "_HashTable.UnsafeHandle") + unsafe _description(type: "_HashTable.UnsafeHandle") } } extension _HashTable: CustomStringConvertible { @usableFromInline package var description: String { - self.read { $0._description(type: "_HashTable") } + unsafe self.read { unsafe $0._description(type: "_HashTable") } } } extension _HashTable.Storage: CustomStringConvertible { @usableFromInline package var description: String { - _HashTable(self).read { $0._description(type: "_HashTable.Storage") } + unsafe _HashTable(self).read { unsafe $0._description(type: "_HashTable.Storage") } } } diff --git a/Sources/OrderedCollections/HashTable/_HashTable+Testing.swift b/Sources/OrderedCollections/HashTable/_HashTable+Testing.swift index 2a4ae77a..d7959a5b 100644 --- a/Sources/OrderedCollections/HashTable/_HashTable+Testing.swift +++ b/Sources/OrderedCollections/HashTable/_HashTable+Testing.swift @@ -19,28 +19,28 @@ extension _HashTable.Bucket: CustomStringConvertible { extension _UnsafeHashTable { package func debugOccupiedCount() -> Int { var count = 0 - var it = bucketIterator(startingAt: Bucket(offset: 0)) + var it = unsafe bucketIterator(startingAt: Bucket(offset: 0)) repeat { if it.isOccupied { count += 1 } - it.advance() + unsafe it.advance() } while it.currentBucket.offset != 0 return count } package func debugLoadFactor() -> Double { - return Double(debugOccupiedCount()) / Double(bucketCount) + return unsafe Double(debugOccupiedCount()) / Double(bucketCount) } package func debugContents() -> [Int?] { var result: [Int?] = [] - result.reserveCapacity(bucketCount) - var it = bucketIterator(startingAt: Bucket(offset: 0)) + result.reserveCapacity(unsafe bucketCount) + var it = unsafe bucketIterator(startingAt: Bucket(offset: 0)) repeat { - result.append(it.currentValue) - it.advance() - } while it.currentBucket.offset != 0 + unsafe result.append(it.currentValue) + unsafe it.advance() + } while it.currentBucket.offset != 0 return result } } @@ -55,12 +55,12 @@ extension _UnsafeHashTable.BucketIterator: CustomStringConvertible { } let offset = pad(String(_currentBucket.offset), to: 4) let value: String - if let v = currentValue { + if let v = unsafe currentValue { value = pad(String(v), to: 4) } else { value = " nil" } let remainingBits = pad(String(_nextBits, radix: 2), to: _remainingBitCount, by: "0") - return "BucketIterator(scale: \(_scale), bucket: \(offset), value: \(value), bits: \(remainingBits) (\(_remainingBitCount) bits))" + return "BucketIterator(scale: \(unsafe _scale), bucket: \(offset), value: \(value), bits: \(remainingBits) (\(_remainingBitCount) bits))" } } diff --git a/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift b/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift index 01d14c55..76b59965 100644 --- a/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift +++ b/Sources/OrderedCollections/HashTable/_HashTable+UnsafeHandle.swift @@ -27,6 +27,7 @@ extension _HashTable { /// the closure call that produced them. @usableFromInline @frozen + @unsafe package struct UnsafeHandle { @usableFromInline package typealias Bucket = _HashTable.Bucket @@ -43,6 +44,7 @@ extension _HashTable { /// True when this handle does not support table mutations. /// (This is only checked in debug builds.) @usableFromInline + @safe package let _readonly: Bool #endif @@ -54,8 +56,8 @@ extension _HashTable { buckets: UnsafeMutablePointer, readonly: Bool ) { - self._header = header - self._buckets = buckets + unsafe self._header = header + unsafe self._buckets = buckets #if DEBUG self._readonly = readonly #endif @@ -68,6 +70,7 @@ extension _HashTable { /// Note that this is a noop in release builds. @inlinable @inline(__always) + @safe package func assertMutable() { #if DEBUG assert(!_readonly, "Attempt to mutate a hash table through a read-only handle") @@ -80,8 +83,8 @@ extension _HashTable.UnsafeHandle { @inlinable package func isIdentical(to other: Self) -> Bool { guard - self._header == other._header, - self._buckets == other._buckets + unsafe self._header == other._header, + unsafe self._buckets == other._buckets else { return false } #if DEBUG guard self._readonly == other._readonly else { return false } @@ -93,18 +96,18 @@ extension _HashTable.UnsafeHandle { /// each of which contain an *n*-bit value. @inlinable @inline(__always) - package var scale: Int { _header.pointee.scale } + package var scale: Int { unsafe _header.pointee.scale } /// The scale corresponding to the last call to `reserveCapacity`. /// We store this to make sure we don't shrink the table below its reserved size. @inlinable @inline(__always) - package var reservedScale: Int { _header.pointee.reservedScale } + package var reservedScale: Int { unsafe _header.pointee.reservedScale } /// The hasher seed to use within this hash table. @inlinable @inline(__always) - package var seed: Int { _header.pointee.seed } + package var seed: Int { unsafe _header.pointee.seed } /// A bias value that needs to be added to buckets to convert them into offsets /// into element storage. (This allows O(1) insertions at the front when the @@ -112,35 +115,35 @@ extension _HashTable.UnsafeHandle { @inlinable @inline(__always) package var bias: Int { - get { _header.pointee.bias } - nonmutating set { _header.pointee.bias = newValue } + get { unsafe _header.pointee.bias } + nonmutating set { unsafe _header.pointee.bias = newValue } } /// The number of buckets within this hash table. This is always a power of two. @inlinable @inline(__always) - package var bucketCount: Int { 1 &<< scale } + package var bucketCount: Int { unsafe 1 &<< scale } @inlinable @inline(__always) - package var bucketMask: UInt64 { UInt64(truncatingIfNeeded: bucketCount) - 1 } + package var bucketMask: UInt64 { unsafe UInt64(truncatingIfNeeded: bucketCount) - 1 } /// The number of bits used to store all the buckets in this hash table. /// Each bucket holds a value that is `scale` bits wide. @inlinable @inline(__always) - package var bitCount: Int { scale &<< scale } + package var bitCount: Int { unsafe scale &<< scale } /// The number of 64-bit words that are available in the storage buffer, /// rounded up to the nearest whole number if necessary. @inlinable @inline(__always) - package var wordCount: Int { (bitCount + UInt64.bitWidth - 1) / UInt64.bitWidth } + package var wordCount: Int { unsafe (bitCount + UInt64.bitWidth - 1) / UInt64.bitWidth } /// The maximum number of items that can fit into this table. @inlinable @inline(__always) - package var capacity: Int { _HashTable.maximumCapacity(forScale: scale) } + package var capacity: Int { unsafe _HashTable.maximumCapacity(forScale: scale) } /// Return the bucket logically following `bucket` in this hash table. /// The buckets form a cycle, so the last bucket is logically followed by the first. @@ -148,7 +151,7 @@ extension _HashTable.UnsafeHandle { @inline(__always) package func bucket(after bucket: Bucket) -> Bucket { var offset = bucket.offset + 1 - if offset == bucketCount { + if unsafe offset == bucketCount { offset = 0 } return Bucket(offset: offset) @@ -159,7 +162,7 @@ extension _HashTable.UnsafeHandle { @inlinable @inline(__always) package func bucket(before bucket: Bucket) -> Bucket { - let offset = (bucket.offset == 0 ? bucketCount : bucket.offset) - 1 + let offset = (bucket.offset == 0 ? unsafe bucketCount : bucket.offset) - 1 return Bucket(offset: offset) } @@ -171,7 +174,7 @@ extension _HashTable.UnsafeHandle { @inline(__always) package func word(after word: Int) -> Int { var result = word + 1 - if result == wordCount { + if unsafe result == wordCount { result = 0 } return result @@ -185,7 +188,7 @@ extension _HashTable.UnsafeHandle { @inline(__always) package func word(before word: Int) -> Int { if word == 0 { - return wordCount - 1 + return unsafe wordCount - 1 } return word - 1 } @@ -194,7 +197,7 @@ extension _HashTable.UnsafeHandle { /// corresponding to `bucket`, along with its bit position within the word. @inlinable package func position(of bucket: Bucket) -> (word: Int, bit: Int) { - let start = bucket.offset &* scale + let start = unsafe bucket.offset &* scale return (start &>> 6, start & 0x3F) } } @@ -211,10 +214,10 @@ extension _HashTable.UnsafeHandle { /// factor guarantees that the hash table will never be completely full.) @inlinable package func _value(forBucketContents bucketContents: UInt64) -> Int? { - let mask = bucketMask + let mask = unsafe bucketMask assert(bucketContents <= mask) guard bucketContents != 0 else { return nil } - let v = (bucketContents ^ mask) &+ UInt64(truncatingIfNeeded: bias) + let v = (bucketContents ^ mask) &+ UInt64(truncatingIfNeeded: unsafe bias) return Int(truncatingIfNeeded: v >= mask ? v - mask : v) } @@ -230,9 +233,9 @@ extension _HashTable.UnsafeHandle { @inlinable package func _bucketContents(for value: Int?) -> UInt64 { guard var value = value else { return 0 } - let mask = Int(truncatingIfNeeded: bucketMask) + let mask = Int(truncatingIfNeeded: unsafe bucketMask) assert(value >= 0 && value < mask) - value &-= bias + value &-= unsafe bias if value < 0 { value += mask } assert(value >= 0 && value < mask) return UInt64(truncatingIfNeeded: value ^ mask) @@ -241,43 +244,43 @@ extension _HashTable.UnsafeHandle { @inlinable package subscript(word word: Int) -> UInt64 { @inline(__always) get { - assert(word >= 0 && word < wordCount) - return _buckets[word] + assert(unsafe word >= 0 && word < wordCount) + return unsafe _buckets[word] } @inline(__always) nonmutating set { - assert(word >= 0 && word < wordCount) + assert(unsafe word >= 0 && word < wordCount) assertMutable() - _buckets[word] = newValue + unsafe _buckets[word] = newValue } } @inlinable package subscript(raw bucket: Bucket) -> UInt64 { get { - assert(bucket.offset < bucketCount) - let (word, bit) = position(of: bucket) - var value = self[word: word] &>> bit + assert(unsafe bucket.offset < bucketCount) + let (word, bit) = unsafe position(of: bucket) + var value = unsafe self[word: word] &>> bit let extractedBits = 64 - bit - if extractedBits < scale { - let word2 = self.word(after: word) + if unsafe extractedBits < scale { + let word2 = unsafe self.word(after: word) value &= (1 &<< extractedBits) - 1 - value |= self[word: word2] &<< extractedBits + unsafe value |= self[word: word2] &<< extractedBits } - return value & bucketMask + return unsafe value & bucketMask } nonmutating set { assertMutable() - assert(bucket.offset < bucketCount) - let mask = bucketMask + assert(unsafe bucket.offset < bucketCount) + let mask = unsafe bucketMask assert(newValue <= mask) - let (word, bit) = position(of: bucket) - self[word: word] &= ~(mask &<< bit) - self[word: word] |= newValue &<< bit + let (word, bit) = unsafe position(of: bucket) + unsafe self[word: word] &= ~(mask &<< bit) + unsafe self[word: word] |= newValue &<< bit let extractedBits = 64 - bit - if extractedBits < scale { - let word2 = self.word(after: word) - self[word: word2] &= ~((1 &<< (scale - extractedBits)) - 1) - self[word: word2] |= newValue &>> extractedBits + if unsafe extractedBits < scale { + let word2 = unsafe self.word(after: word) + unsafe self[word: word2] &= ~((1 &<< (scale - extractedBits)) - 1) + unsafe self[word: word2] |= newValue &>> extractedBits } } } @@ -285,7 +288,7 @@ extension _HashTable.UnsafeHandle { @inlinable @inline(__always) package func isOccupied(_ bucket: Bucket) -> Bool { - self[raw: bucket] != 0 + unsafe self[raw: bucket] != 0 } /// Return or update the current value stored in the specified bucket. @@ -293,13 +296,13 @@ extension _HashTable.UnsafeHandle { @inlinable package subscript(bucket: Bucket) -> Int? { get { - let contents = self[raw: bucket] - return _value(forBucketContents: contents) + let contents = unsafe self[raw: bucket] + return unsafe _value(forBucketContents: contents) } nonmutating set { assertMutable() - let v = _bucketContents(for: newValue) - self[raw: bucket] = v + let v = unsafe _bucketContents(for: newValue) + unsafe self[raw: bucket] = v } } } @@ -311,7 +314,7 @@ extension _UnsafeHashTable { in elements: ContiguousArray ) -> (index: Int?, bucket: Bucket) { elements.withUnsafeBufferPointer { buffer in - _find(item, in: buffer) + unsafe _find(item, in: buffer) } } @@ -320,13 +323,13 @@ extension _UnsafeHashTable { _ item: Element, in elements: UnsafeBufferPointer ) -> (index: Int?, bucket: Bucket) { - let start = idealBucket(for: item) - var (iterator, value) = startFind(start) + let start = unsafe idealBucket(for: item) + var (iterator, value) = unsafe startFind(start) while let index = value { - if elements[_offset: index] == item { + if unsafe elements[_offset: index] == item { return (index, iterator.currentBucket) } - value = iterator.findNext() + value = unsafe iterator.findNext() } return (nil, iterator.currentBucket) } @@ -337,9 +340,9 @@ extension _UnsafeHashTable { package func firstOccupiedBucketInChain(with bucket: Bucket) -> Bucket { var bucket = bucket repeat { - bucket = self.bucket(before: bucket) - } while isOccupied(bucket) - return self.bucket(after: bucket) + bucket = unsafe self.bucket(before: bucket) + } while unsafe isOccupied(bucket) + return unsafe self.bucket(after: bucket) } @inlinable @@ -348,24 +351,24 @@ extension _UnsafeHashTable { hashValueGenerator: (Int, Int) -> Int // (offset, seed) -> hashValue ) { assertMutable() - var it = bucketIterator(startingAt: bucket) + var it = unsafe bucketIterator(startingAt: bucket) assert(it.isOccupied) - it.advance() + unsafe it.advance() guard it.isOccupied else { // Fast path: Don't get the start bucket when there's nothing to do. - self[bucket] = nil + unsafe self[bucket] = nil return } // If we've put a hole in the middle of a collision chain, some element after // the hole may belong where the new hole is. // Find the first bucket in the collision chain that contains the entry we've just deleted. - let start = firstOccupiedBucketInChain(with: bucket) + let start = unsafe firstOccupiedBucketInChain(with: bucket) var hole = bucket while it.isOccupied { - let hash = hashValueGenerator(it.currentValue!, seed) - let candidate = idealBucket(forHashValue: hash) + let hash = unsafe hashValueGenerator(it.currentValue!, seed) + let candidate = unsafe idealBucket(forHashValue: hash) // Does this element belong between start and hole? We need two // separate tests depending on whether [start, hole] wraps around the @@ -376,12 +379,12 @@ extension _UnsafeHashTable { // Fill the hole. Here we are mutating table contents behind the back of // the iterator; this is okay since we know we are never going to revisit // `hole` with it. - self[hole] = it.currentValue + unsafe self[hole] = it.currentValue hole = it.currentBucket } - it.advance() + unsafe it.advance() } - self[hole] = nil + unsafe self[hole] = nil } } @@ -394,40 +397,40 @@ extension _UnsafeHashTable { assertMutable() let index = elements._index(at: offset) if offset < elements.count / 2 { - self.bias += 1 - if offset <= capacity / 3 { + unsafe self.bias += 1 + if unsafe offset <= capacity / 3 { var i = 1 for item in elements[..= offset { - it.currentValue = value + 1 + if let value = unsafe it.currentValue, value >= offset { + unsafe it.currentValue = value + 1 } - it.advance() + unsafe it.advance() } while it.currentBucket.offset != 0 } } @@ -442,7 +445,7 @@ extension _UnsafeHashTable { in elements: Base ) where Base.Element: Hashable { let next = elements.index(after: index) - adjustContents(preparingForRemovalOf: index ..< next, in: elements) + unsafe adjustContents(preparingForRemovalOf: index ..< next, in: elements) } @inlinable @@ -459,50 +462,50 @@ extension _UnsafeHashTable { if startOffset >= remainingCount / 2 { let tailCount = elements.count - endOffset - if tailCount < capacity / 3 { + if unsafe tailCount < capacity / 3 { var i = endOffset for item in elements[bounds.upperBound...] { - var it = self.bucketIterator(for: item) - it.advance(until: i) - it.currentValue = i - c + var it = unsafe self.bucketIterator(for: item) + unsafe it.advance(until: i) + unsafe it.currentValue = i - c i += 1 } } else { - var it = bucketIterator(startingAt: Bucket(offset: 0)) + var it = unsafe bucketIterator(startingAt: Bucket(offset: 0)) repeat { - if let value = it.currentValue { + if let value = unsafe it.currentValue { if value >= endOffset { - it.currentValue = value - c + unsafe it.currentValue = value - c } else { assert(value < startOffset) } } - it.advance() + unsafe it.advance() } while it.currentBucket.offset != 0 } } else { - if startOffset < capacity / 3 { + if unsafe startOffset < capacity / 3 { var i = 0 for item in elements[..= endOffset) } } - it.advance() + unsafe it.advance() } while it.currentBucket.offset != 0 } - self.bias -= c + unsafe self.bias -= c } } } @@ -511,12 +514,12 @@ extension _UnsafeHashTable { @inlinable package func reverse(count: Int) { assertMutable() - var it = bucketIterator(startingAt: Bucket(offset: 0)) + var it = unsafe bucketIterator(startingAt: Bucket(offset: 0)) repeat { - if let value = it.currentValue { - it.currentValue = count - 1 - value + if let value = unsafe it.currentValue { + unsafe it.currentValue = count - 1 - value } - it.advance() + unsafe it.advance() } while it.currentBucket.offset != 0 } } @@ -525,7 +528,7 @@ extension _UnsafeHashTable { @usableFromInline package func clear() { assertMutable() - _buckets.update(repeating: 0, count: wordCount) + unsafe _buckets.update(repeating: 0, count: wordCount) } } @@ -538,7 +541,7 @@ extension _UnsafeHashTable { uncheckedUniqueElements elements: C ) where C.Element: Hashable { assertMutable() - assert(elements.count <= capacity) + assert(unsafe elements.count <= capacity) // fast path that doesn't allocate per element if _read accessor can't // be inlined because this function doesn't get specialized e.g. // if `Element` isn't known at compile time. @@ -548,9 +551,9 @@ extension _UnsafeHashTable { for index in elements.indices { // Find the insertion position. We know that we're inserting a new item, // so there is no need to compare it with any of the existing ones. - var it = bucketIterator(for: elements[index]) - it.advanceToNextUnoccupiedBucket() - it.currentValue = offset + var it = unsafe bucketIterator(for: elements[index]) + unsafe it.advanceToNextUnoccupiedBucket() + unsafe it.currentValue = offset offset += 1 } } @@ -562,9 +565,9 @@ extension _UnsafeHashTable { for index in elements.indices { // Find the insertion position. We know that we're inserting a new item, // so there is no need to compare it with any of the existing ones. - var it = bucketIterator(for: elements[index]) - it.advanceToNextUnoccupiedBucket() - it.currentValue = offset + var it = unsafe bucketIterator(for: elements[index]) + unsafe it.advanceToNextUnoccupiedBucket() + unsafe it.currentValue = offset offset += 1 } } @@ -579,7 +582,7 @@ extension _UnsafeHashTable { ) -> (success: Bool, end: C.Index) where C.Element: Hashable { assertMutable() - assert(elements.count <= capacity) + assert(unsafe elements.count <= capacity) // Iterate over elements and insert their offset into the hash table. // fast path that doesn't allocate per element if _read accessor can't @@ -590,14 +593,14 @@ extension _UnsafeHashTable { for index in elements.indices { // Find the insertion position. We know that we're inserting a new item, // so there is no need to compare it with any of the existing ones. - var it = bucketIterator(for: elements[index]) - while let offset = it.currentValue { - guard elements[_offset: offset] != elements[index] else { + var it = unsafe bucketIterator(for: elements[index]) + while let offset = unsafe it.currentValue { + guard unsafe elements[_offset: offset] != elements[index] else { return (false, index) } - it.advance() + unsafe it.advance() } - it.currentValue = offset + unsafe it.currentValue = offset offset += 1 } return (true, elements.endIndex) @@ -609,14 +612,14 @@ extension _UnsafeHashTable { for index in elements.indices { // Find the insertion position. We know that we're inserting a new item, // so there is no need to compare it with any of the existing ones. - var it = bucketIterator(for: elements[index]) - while let offset = it.currentValue { + var it = unsafe bucketIterator(for: elements[index]) + while let offset = unsafe it.currentValue { guard elements[_offset: offset] != elements[index] else { return (false, index) } - it.advance() + unsafe it.advance() } - it.currentValue = offset + unsafe it.currentValue = offset offset += 1 } return (true, elements.endIndex) diff --git a/Sources/OrderedCollections/HashTable/_HashTable.swift b/Sources/OrderedCollections/HashTable/_HashTable.swift index 21221ce1..378e7616 100644 --- a/Sources/OrderedCollections/HashTable/_HashTable.swift +++ b/Sources/OrderedCollections/HashTable/_HashTable.swift @@ -47,21 +47,28 @@ extension _HashTable { #if COLLECTIONS_DETERMINISTIC_HASHING let seed = scale << 6 #else - let seed = Int(bitPattern: Unmanaged.passUnretained(object).toOpaque()) + let seed = Int(bitPattern: unsafe Unmanaged.passUnretained(object).toOpaque()) #endif return Header(scale: scale, reservedScale: reservedScale, seed: seed) }) - storage.withUnsafeMutablePointerToElements { elements in - elements.initialize(repeating: 0, count: wordCount) + unsafe storage.withUnsafeMutablePointerToElements { elements in + unsafe elements.initialize(repeating: 0, count: wordCount) } - self.init(unsafeDowncast(storage, to: Storage.self)) + self.init(unsafe unsafeDowncast(storage, to: Storage.self)) } /// Populate a new hash table with data from `elements`. /// - /// - Parameter scale: The desired hash table scale or nil to use the minimum scale that satisfies invariants. - /// - Parameter reservedScale: The reserved scale to remember in the returned storage. - /// - Returns: `(storage, index)` where `storage` is a storage instance. The contents of `storage` reflects all elements in `contents[contents.startIndex ..< index]`. `index` is usually `contents.endIndex`, except when the function was asked to reject duplicates, in which case `index` addresses the first duplicate element in `contents` (if any). + /// - Parameter scale: The desired hash table scale or nil to use the minimum + /// scale that satisfies invariants. + /// - Parameter reservedScale: The reserved scale to remember in the returned + /// storage. + /// - Returns: `(storage, index)` where `storage` is a storage instance. The + /// contents of `storage` reflects all elements in + /// `contents[contents.startIndex ..< index]`. `index` is usually + /// `contents.endIndex`, except when the function was asked to reject + /// duplicates, in which case `index` addresses the first duplicate + /// element in `contents` (if any). @inlinable @inline(never) @_effects(releasenone) @@ -76,17 +83,24 @@ extension _HashTable { reservedScale) if scale < Self.minimumScale { return nil } let hashTable = Self(scale: scale, reservedScale: reservedScale) - hashTable.update { handle in - handle.fill(uncheckedUniqueElements: elements) + unsafe hashTable.update { handle in + unsafe handle.fill(uncheckedUniqueElements: elements) } return hashTable } /// Populate a new hash table with data from `elements`. /// - /// - Parameter scale: The desired hash table scale or nil to use the minimum scale that satisfies invariants. - /// - Parameter reservedScale: The reserved scale to remember in the returned storage. - /// - Returns: `(storage, index)` where `storage` is a storage instance. The contents of `storage` reflects all elements in `contents[contents.startIndex ..< index]`. `index` is usually `contents.endIndex`, except when the function was asked to reject duplicates, in which case `index` addresses the first duplicate element in `contents` (if any). + /// - Parameter scale: The desired hash table scale or nil to use the minimum + /// scale that satisfies invariants. + /// - Parameter reservedScale: The reserved scale to remember in the returned + /// storage. + /// - Returns: `(storage, index)` where `storage` is a storage instance. The + /// contents of `storage` reflects all elements in + /// `contents[contents.startIndex ..< index]`. `index` is usually + /// `contents.endIndex`, except when the function was asked to reject + /// duplicates, in which case `index` addresses the first duplicate + /// element in `contents` (if any). @inlinable @inline(never) @_effects(releasenone) @@ -110,7 +124,7 @@ extension _HashTable { var temp: ContiguousArray = [] temp.reserveCapacity(elements.count) for i in elements.indices { - let item = elements[i] + let item = unsafe elements[i] guard !temp._contains(item) else { return i } temp.append(item) } @@ -129,8 +143,8 @@ extension _HashTable { return (nil, elements.endIndex) } let hashTable = Self(scale: scale, reservedScale: reservedScale) - let (_, index) = hashTable.update { handle in - handle.fill(untilFirstDuplicateIn: elements) + let (_, index) = unsafe hashTable.update { handle in + unsafe handle.fill(untilFirstDuplicateIn: elements) } return (hashTable, index) } @@ -140,15 +154,15 @@ extension _HashTable { @usableFromInline @_effects(releasenone) package func copy() -> _HashTable { - self.read { handle in - let wordCount = handle.wordCount + unsafe self.read { handle in + let wordCount = unsafe handle.wordCount let new = Storage.create( minimumCapacity: wordCount, - makingHeaderWith: { _ in handle._header.pointee }) - new.withUnsafeMutablePointerToElements { elements in - elements.initialize(from: handle._buckets, count: wordCount) + makingHeaderWith: { _ in unsafe handle._header.pointee }) + unsafe new.withUnsafeMutablePointerToElements { elements in + unsafe elements.initialize(from: handle._buckets, count: wordCount) } - return Self(unsafeDowncast(new, to: Storage.self)) + return Self(unsafe unsafeDowncast(new, to: Storage.self)) } } } @@ -178,9 +192,9 @@ extension _HashTable { @inlinable @inline(__always) package func read(_ body: (_UnsafeHashTable) throws -> R) rethrows -> R { - try _storage.withUnsafeMutablePointers { header, elements in - let handle = _UnsafeHashTable(header: header, buckets: elements, readonly: true) - return try body(handle) + unsafe try _storage.withUnsafeMutablePointers { header, elements in + let handle = unsafe _UnsafeHashTable(header: header, buckets: elements, readonly: true) + return unsafe try body(handle) } } @@ -191,9 +205,9 @@ extension _HashTable { @inlinable @inline(__always) package func update(_ body: (_UnsafeHashTable) throws -> R) rethrows -> R { - try _storage.withUnsafeMutablePointers { header, elements in - let handle = _UnsafeHashTable(header: header, buckets: elements, readonly: false) - return try body(handle) + unsafe try _storage.withUnsafeMutablePointers { header, elements in + let handle = unsafe _UnsafeHashTable(header: header, buckets: elements, readonly: false) + return unsafe try body(handle) } } } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Codable.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Codable.swift index a63b65c3..f353292f 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Codable.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Codable.swift @@ -82,7 +82,7 @@ extension OrderedDictionary: Decodable where Key: Decodable, Value: Decodable { ) } let value = try container.decode(Value.self) - _keys._appendNew(key, in: bucket) + unsafe _keys._appendNew(key, in: bucket) _values.append(value) } _checkInvariants() diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift index 12099b15..289406d6 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Initializers.swift @@ -352,7 +352,7 @@ extension OrderedDictionary { self.init() reserveCapacity(keysAndValues.underestimatedCount) for (key, value) in keysAndValues { - _keys._appendNew(key) + unsafe _keys._appendNew(key) _values.append(value) } _checkInvariants() diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift index a61f0dea..4b37e033 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Move.swift @@ -71,7 +71,7 @@ extension OrderedDictionary { let c = range.count if c > 0, range.lowerBound != destination { _values.withUnsafeMutableBufferPointer { values in - values._moveSubrange( + unsafe values._moveSubrange( range.lowerBound ..< range.lowerBound + c, toOffset: destination) } } @@ -109,9 +109,9 @@ extension OrderedDictionary { to destination: Index ) { _values.withUnsafeMutableBufferPointer { values in - _keys._move(members: keys, to: destination) { + unsafe _keys._move(members: keys, to: destination) { sourceOffsets, sortedSources, isContiguousRange, target in - values._move( + unsafe values._move( sourceOffsets: sourceOffsets, sortedSources: sortedSources, isContiguousRange: isContiguousRange, @@ -150,9 +150,9 @@ extension OrderedDictionary { to destination: Index ) { _values.withUnsafeMutableBufferPointer { values in - _keys._move(indices: indices, to: destination) { + unsafe _keys._move(indices: indices, to: destination) { sourceOffsets, sortedSources, isContiguousRange, target in - values._move( + unsafe values._move( sourceOffsets: sourceOffsets, sortedSources: sortedSources, isContiguousRange: isContiguousRange, diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift index 6b6aed5c..ae4678aa 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial MutableCollection.swift @@ -92,7 +92,7 @@ extension OrderedDictionary { // Replace the key through OrderedSet's shared primitive, then overwrite the // value at `index` — each step is O(1). - let oldKey = _keys._replaceNew(at: index, with: key, in: bucket) + let oldKey = unsafe _keys._replaceNew(at: index, with: key, in: bucket) let oldValue = exchange(&_values[index], with: value) _checkInvariants() @@ -121,7 +121,7 @@ extension OrderedDictionary { by belongsInSecondPartition: (Element) throws -> Bool ) rethrows -> Int { let pivot = try _values.withUnsafeMutableBufferPointer { values in - try _keys._partition(values: values, by: belongsInSecondPartition) + unsafe try _keys._partition(values: values, by: belongsInSecondPartition) } _checkInvariants() return pivot @@ -173,8 +173,8 @@ extension OrderedDictionary { let temp = try self.sorted(by: areInIncreasingOrder) precondition(temp.count == self.count) temp.withUnsafeBufferPointer { source in - _keys = OrderedSet(uncheckedUniqueElements: source.lazy.map { $0.key }) - _values = ContiguousArray(source.lazy.map { $0.value }) + unsafe _keys = OrderedSet(uncheckedUniqueElements: source.lazy.map { $0.key }) + unsafe _values = ContiguousArray(source.lazy.map { $0.value }) } _checkInvariants() } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift index 46e4b1fb..3f705f09 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary+Partial RangeReplaceableCollection.swift @@ -175,7 +175,7 @@ extension OrderedDictionary { where shouldBeRemoved: (Self.Element) throws -> Bool ) rethrows { let pivot = try _values.withUnsafeMutableBufferPointer { values in - try _keys._halfStablePartition( + unsafe try _keys._halfStablePartition( values: values, by: shouldBeRemoved) } diff --git a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift index 9ca340c7..73e7921d 100644 --- a/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift +++ b/Sources/OrderedCollections/OrderedDictionary/OrderedDictionary.swift @@ -357,10 +357,10 @@ extension OrderedDictionary { case let (index?, newValue?): // Assign _values[index] = newValue case let (index?, nil): // Remove - _keys._removeExistingMember(at: index, in: bucket) + unsafe _keys._removeExistingMember(at: index, in: bucket) _values.remove(at: index) case let (nil, newValue?): // Insert - _keys._appendNew(key, in: bucket) + unsafe _keys._appendNew(key, in: bucket) _values.append(newValue) case (nil, nil): // Noop break @@ -410,9 +410,9 @@ extension OrderedDictionary { let standin = _values.remove(at: index) _values.append(standin) } - _keys._removeExistingMember(at: index, in: bucket) + unsafe _keys._removeExistingMember(at: index, in: bucket) case let (nil, value?): // Insert - _keys._appendNew(key, in: bucket) + unsafe _keys._appendNew(key, in: bucket) _values.append(value) case (nil, nil): // Noop break @@ -492,15 +492,16 @@ extension OrderedDictionary { } @inline(__always) // https://github.com/apple/swift-collections/issues/164 _modify { - var (index, value) = _prepareForDefaultedModify(key, defaultValue) + var (index, value) = unsafe _prepareForDefaultedModify(key, defaultValue) defer { - _finalizeDefaultedModify(index, &value) + unsafe _finalizeDefaultedModify(index, &value) } yield &value } } @inlinable + @unsafe internal mutating func _prepareForDefaultedModify( _ key: Key, _ defaultValue: () -> Value @@ -512,18 +513,19 @@ extension OrderedDictionary { } let value: Value = _values.withUnsafeMutableBufferPointer { buffer in assert(index < buffer.count) - return (buffer.baseAddress! + index).move() + return unsafe (buffer.baseAddress! + index).move() } return (index, value) } @inlinable + @unsafe internal mutating func _finalizeDefaultedModify( _ index: Int, _ value: inout Value ) { _values.withUnsafeMutableBufferPointer { buffer in assert(index < buffer.count) - (buffer.baseAddress! + index).initialize(to: value) + unsafe (buffer.baseAddress! + index).initialize(to: value) } } } @@ -578,7 +580,7 @@ extension OrderedDictionary { _values[index] = value return old } - _keys._appendNew(key, in: bucket) + unsafe _keys._appendNew(key, in: bucket) _values.append(value) return nil } @@ -691,7 +693,7 @@ extension OrderedDictionary { if let index = index { return try body(&_values[index]) } - _keys._appendNew(key, in: bucket) + unsafe _keys._appendNew(key, in: bucket) _values.append(defaultValue()) let i = _values.index(before: _values.endIndex) return try body(&_values[i]) @@ -740,7 +742,7 @@ extension OrderedDictionary { if let existingIndex = existingIndex { return try body(&_values[existingIndex]) } - _keys._insertNew(key, at: index, in: bucket) + unsafe _keys._insertNew(key, at: index, in: bucket) _values.insert(defaultValue(), at: index) return try body(&_values[index]) } @@ -781,7 +783,7 @@ extension OrderedDictionary { public mutating func removeValue(forKey key: Key) -> Value? { let (idx, bucket) = _keys._find(key) guard let index = idx else { return nil } - _keys._removeExistingMember(at: index, in: bucket) + unsafe _keys._removeExistingMember(at: index, in: bucket) return _values.remove(at: index) } } @@ -832,7 +834,7 @@ extension OrderedDictionary { if let index = index { try { $0 = try combine($0, value) }(&_values[index]) } else { - _keys._appendNew(key, in: bucket) + unsafe _keys._appendNew(key, in: bucket) _values.append(value) } } @@ -992,7 +994,7 @@ extension OrderedDictionary { ) rethrows -> Self { var result: OrderedDictionary = [:] for element in self where try isIncluded(element) { - result._keys._appendNew(element.key) + unsafe result._keys._appendNew(element.key) result._values.append(element.value) } return result @@ -1052,7 +1054,7 @@ extension OrderedDictionary { var result: OrderedDictionary = [:] for (key, value) in self { if let value = try transform(value) { - result._keys._appendNew(key) + unsafe result._keys._appendNew(key) result._values.append(value) } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift index 2efe70cf..22879d96 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Insertions.swift @@ -22,6 +22,7 @@ extension OrderedSet { /// - Complexity: Expected to be O(1) on average if `Element` /// implements high-quality hashing. @inlinable + @unsafe internal mutating func _appendNew(_ item: Element) { assert(!contains(item), "Duplicate item") _elements.append(item) @@ -31,10 +32,10 @@ extension OrderedSet { } guard _table != nil else { return } _ensureUnique() - _table!.update { hashTable in - var it = hashTable.bucketIterator(for: item) - it.advanceToNextUnoccupiedBucket() - it.currentValue = _elements.count - 1 + unsafe _table!.update { hashTable in + var it = unsafe hashTable.bucketIterator(for: item) + unsafe it.advanceToNextUnoccupiedBucket() + unsafe it.currentValue = _elements.count - 1 } } @@ -47,6 +48,7 @@ extension OrderedSet { /// /// - Complexity: Amortized O(1) @inlinable + @unsafe internal mutating func _appendNew(_ item: Element, in bucket: _Bucket) { _elements.append(item) @@ -56,9 +58,9 @@ extension OrderedSet { } guard _table != nil else { return } _ensureUnique() - _table!.update { hashTable in - assert(!hashTable.isOccupied(bucket)) - hashTable[bucket] = _elements.count - 1 + unsafe _table!.update { hashTable in + assert(unsafe !hashTable.isOccupied(bucket)) + unsafe hashTable[bucket] = _elements.count - 1 } } @@ -69,7 +71,7 @@ extension OrderedSet { ) -> (inserted: Bool, index: Int) { let (index, bucket) = _find(item) if let index = index { return (false, index) } - _appendNew(item, in: bucket) + unsafe _appendNew(item, in: bucket) return (true, _elements.index(before: _elements.endIndex)) } @@ -118,6 +120,7 @@ extension OrderedSet { extension OrderedSet { @inlinable + @unsafe internal mutating func _insertNew( _ item: Element, at index: Int, @@ -134,10 +137,10 @@ extension OrderedSet { } _ensureUnique() - _table!.update { hashTable in - assert(!hashTable.isOccupied(bucket)) - hashTable.adjustContents(preparingForInsertionOfElementAtOffset: index, in: _elements) - hashTable[bucket] = index + unsafe _table!.update { hashTable in + assert(unsafe !hashTable.isOccupied(bucket)) + unsafe hashTable.adjustContents(preparingForInsertionOfElementAtOffset: index, in: _elements) + unsafe hashTable[bucket] = index } _elements.insert(item, at: index) _checkInvariants() @@ -169,7 +172,7 @@ extension OrderedSet { ) -> (inserted: Bool, index: Int) { let (existing, bucket) = _find(item) if let existing = existing { return (false, existing) } - _insertNew(item, at: index, in: bucket) + unsafe _insertNew(item, at: index, in: bucket) return (true, index) } } @@ -213,10 +216,11 @@ extension OrderedSet { /// - Complexity: Amortized O(1) @inlinable @discardableResult + @unsafe internal mutating func _replaceNew( at index: Int, with item: Element, in bucket: _Bucket ) -> Element { - _appendNew(item, in: bucket) + unsafe _appendNew(item, in: bucket) swapAt(index, count - 1) return removeLast() } @@ -262,7 +266,7 @@ extension OrderedSet { } precondition(existing == nil, "Duplicate element") - return _replaceNew(at: index, with: item, in: bucket) + return unsafe _replaceNew(at: index, with: item, in: bucket) } } @@ -322,7 +326,7 @@ extension OrderedSet { _elements[existing] = item return (old, existing) } - _insertNew(item, at: index, in: bucket) + unsafe _insertNew(item, at: index, in: bucket) return (nil, index) } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift index 78678c0a..888fea1c 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Move.swift @@ -80,10 +80,10 @@ extension OrderedSet { "Destination index \(destination) out of range 0 ... \(count - c)") guard range.lowerBound != destination else { return } _elements.withUnsafeMutableBufferPointer { buffer in - buffer._moveSubrange( + unsafe buffer._moveSubrange( range.lowerBound ..< range.lowerBound + c, toOffset: destination) } - _updateHashAfterContiguousMove( + unsafe _updateHashAfterContiguousMove( src: range.lowerBound, count: c, to: destination) _checkInvariants() } @@ -118,7 +118,7 @@ extension OrderedSet { members elements: some Sequence, to destination: Index ) { - _move(members: elements, to: destination) + unsafe _move(members: elements, to: destination) } /// Moves the elements at the given indices so they land just before the @@ -149,7 +149,7 @@ extension OrderedSet { indices: some Sequence, to destination: Index ) { - _move(indices: indices, to: destination) + unsafe _move(indices: indices, to: destination) } } @@ -172,7 +172,7 @@ extension OrderedSet { "Destination index \(destination) out of range 0 ... \(count)") // Fast path: operate directly on the sequence's storage when available. let handled: Void? = indices.withContiguousStorageIfAvailable { buffer in - _move(fromIndices: buffer, to: destination, applyingTo: body) + unsafe _move(fromIndices: buffer, to: destination, applyingTo: body) } if handled != nil { return } @@ -204,7 +204,7 @@ extension OrderedSet { // elements before it gives the block's final start index. let target = destination - below sourceOffsets.withUnsafeBufferPointer { sourceOffsets in - _move( + unsafe _move( sourceOffsets: sourceOffsets, isContiguousRange: isContiguousRange, isSorted: isSorted, @@ -233,12 +233,12 @@ extension OrderedSet { var isSorted = true var below = 0 for i in 0 ..< sourceOffsets.count { - let index = sourceOffsets[i] + let index = unsafe sourceOffsets[i] precondition( index >= 0 && index < count, "Index \(index) at \(i) out of bounds 0 ..< \(count)") if i > 0 { - let prev = sourceOffsets[i - 1] + let prev = unsafe sourceOffsets[i - 1] if index <= prev { isSorted = false isContiguousRange = false @@ -249,7 +249,7 @@ extension OrderedSet { if index < destination { below += 1 } } let target = destination - below - _move( + unsafe _move( sourceOffsets: sourceOffsets, isContiguousRange: isContiguousRange, isSorted: isSorted, @@ -285,9 +285,9 @@ extension OrderedSet { var below = 0 var c = 0 for i in 0 ..< source.count { - guard let index = _find(source[i]).index else { continue } + guard let index = unsafe _find(source[i]).index else { continue } if c > 0 { - let prev = sourceOffsets[c - 1] + let prev = unsafe sourceOffsets[c - 1] if index <= prev { isSorted = false isContiguousRange = false @@ -296,10 +296,10 @@ extension OrderedSet { } } if index < destination { below += 1 } - sourceOffsets[c] = index + unsafe sourceOffsets[c] = index c += 1 } - _move( + unsafe _move( sourceOffsets: UnsafeBufferPointer(rebasing: sourceOffsets[.., sortedSources: UnsafeBufferPointer, @@ -412,18 +413,18 @@ extension OrderedSet { ) -> Void ) { _elements.withUnsafeMutableBufferPointer { buffer in - buffer._move( + unsafe buffer._move( sourceOffsets: sourceOffsets, sortedSources: sortedSources, isContiguousRange: isContiguousRange, to: destination) } - _updateHashAfterMove( + unsafe _updateHashAfterMove( sourceOffsets: sourceOffsets, sortedSources: sortedSources, isContiguousRange: isContiguousRange, to: destination) - body(sourceOffsets, sortedSources, isContiguousRange, destination) + unsafe body(sourceOffsets, sortedSources, isContiguousRange, destination) } } @@ -432,6 +433,7 @@ extension OrderedSet { /// `src` was rotated to start at `destination`. `_elements` is already /// rearranged. `destination` is the block's final start index (post-removal). @inlinable + @unsafe internal mutating func _updateHashAfterContiguousMove( src: Int, count: Int, @@ -443,53 +445,53 @@ extension OrderedSet { let distance: Int = destination < src ? src - destination : destination - src - _table!.update { hashTable in + unsafe _table!.update { hashTable in // Targeted bucket updates touch O(count + distance) buckets, while a // full scan touches all of `hashTable.capacity`. With a 3/4 load // factor, scanning becomes cheaper once the affected region grows // beyond roughly a third of the table. - let targetedUpdateLimit = hashTable.capacity / 3 + let targetedUpdateLimit = unsafe hashTable.capacity / 3 if count <= targetedUpdateLimit && distance <= targetedUpdateLimit { if destination < src { for newPos in destination ..< destination + count { - var it = hashTable.bucketIterator(for: _elements[newPos]) - it.advance(until: newPos + distance) - it.currentValue = newPos + var it = unsafe hashTable.bucketIterator(for: _elements[newPos]) + unsafe it.advance(until: newPos + distance) + unsafe it.currentValue = newPos } for newPos in destination + count ..< src + count { - var it = hashTable.bucketIterator(for: _elements[newPos]) - it.advance(until: newPos - count) - it.currentValue = newPos + var it = unsafe hashTable.bucketIterator(for: _elements[newPos]) + unsafe it.advance(until: newPos - count) + unsafe it.currentValue = newPos } } else { for newPos in src ..< destination { - var it = hashTable.bucketIterator(for: _elements[newPos]) - it.advance(until: newPos + count) - it.currentValue = newPos + var it = unsafe hashTable.bucketIterator(for: _elements[newPos]) + unsafe it.advance(until: newPos + count) + unsafe it.currentValue = newPos } for newPos in destination ..< destination + count { - var it = hashTable.bucketIterator(for: _elements[newPos]) - it.advance(until: newPos - distance) - it.currentValue = newPos + var it = unsafe hashTable.bucketIterator(for: _elements[newPos]) + unsafe it.advance(until: newPos - distance) + unsafe it.currentValue = newPos } } } else { - var it = hashTable.bucketIterator(startingAt: _Bucket(offset: 0)) + var it = unsafe hashTable.bucketIterator(startingAt: _Bucket(offset: 0)) repeat { - if let value = it.currentValue { + if let value = unsafe it.currentValue { if value >= src && value < src + count { - it.currentValue = destination < src + unsafe it.currentValue = destination < src ? value - distance : value + distance } else if destination < src && value >= destination && value < src { - it.currentValue = value + count + unsafe it.currentValue = value + count } else if destination > src && value >= src + count && value < destination + count { - it.currentValue = value - count + unsafe it.currentValue = value - count } } - it.advance() + unsafe it.advance() } while it.currentBucket.offset != 0 } } @@ -506,17 +508,17 @@ extension OrderedSet { to destination: Int ) { let count = sourceOffsets.count - let minSource = sortedSources[0] + let minSource = unsafe sortedSources[0] if isContiguousRange { - _updateHashAfterContiguousMove( + unsafe _updateHashAfterContiguousMove( src: minSource, count: count, to: destination) return } guard _table != nil else { return } - let maxSource = sortedSources[count - 1] + let maxSource = unsafe sortedSources[count - 1] let affectedStart: Int = Swift.min(minSource, destination) let affectedEnd: Int = Swift.max(maxSource, destination + count - 1) let affectedCount: Int = affectedEnd - affectedStart + 1 @@ -528,31 +530,31 @@ extension OrderedSet { if affectedCount <= targetedUpdateLimit { _ensureUnique() - _table!.update { hashTable in + unsafe _table!.update { hashTable in for i in 0 ..< count { - let oldPos = sourceOffsets[i] + let oldPos = unsafe sourceOffsets[i] let newPos = destination + i if oldPos != newPos { - var it = hashTable.bucketIterator(for: _elements[newPos]) - it.advance(until: oldPos) - it.currentValue = newPos + var it = unsafe hashTable.bucketIterator(for: _elements[newPos]) + unsafe it.advance(until: oldPos) + unsafe it.currentValue = newPos } } if affectedStart < destination { - var oldPos = affectedStart + var oldPos = unsafe affectedStart + sortedSources._sortedCount(below: affectedStart) var si = oldPos - affectedStart for newPos in affectedStart ..< destination { // Mirrors the catch-up loop after the gap; see there. - while si < count && sortedSources[si] <= oldPos { + while unsafe si < count && sortedSources[si] <= oldPos { oldPos += 1 si += 1 } if oldPos != newPos { - var it = hashTable.bucketIterator(for: _elements[newPos]) - it.advance(until: oldPos) - it.currentValue = newPos + var it = unsafe hashTable.bucketIterator(for: _elements[newPos]) + unsafe it.advance(until: oldPos) + unsafe it.currentValue = newPos } oldPos += 1 } @@ -560,21 +562,21 @@ extension OrderedSet { if destination + count <= affectedEnd { let firstNSIndex = destination - var oldPos = firstNSIndex + var oldPos = unsafe firstNSIndex + sortedSources._sortedCount(below: firstNSIndex) var si = oldPos - firstNSIndex for newPos in (destination + count) ... affectedEnd { // `<=` (not `==`): the initial `oldPos` counts sources // strictly below `firstNSIndex`, so any source in // `[firstNSIndex, oldPos]` still needs folding in here. - while si < count && sortedSources[si] <= oldPos { + while unsafe si < count && sortedSources[si] <= oldPos { oldPos += 1 si += 1 } if oldPos != newPos { - var it = hashTable.bucketIterator(for: _elements[newPos]) - it.advance(until: oldPos) - it.currentValue = newPos + var it = unsafe hashTable.bucketIterator(for: _elements[newPos]) + unsafe it.advance(until: oldPos) + unsafe it.currentValue = newPos } oldPos += 1 } @@ -584,9 +586,9 @@ extension OrderedSet { // Full rebuild: build fresh storage when shared, rather than copying the // old table only to clear it. if _isUnique() { - _table!.update { hashTable in - hashTable.clear() - hashTable.fill(uncheckedUniqueElements: _elements) + unsafe _table!.update { hashTable in + unsafe hashTable.clear() + unsafe hashTable.fill(uncheckedUniqueElements: _elements) } } else { _regenerateHashTable(scale: _scale, reservedScale: _reservedScale) @@ -609,26 +611,26 @@ extension UnsafeMutableBufferPointer { to destination: Int ) { let c = sourceOffsets.count - let minSource = sortedSources[0] + let minSource = unsafe sortedSources[0] if isContiguousRange { - _moveSubrange(minSource ..< minSource + c, toOffset: destination) + unsafe _moveSubrange(minSource ..< minSource + c, toOffset: destination) return } - if sortedSources[c - 1] - minSource == c - 1 { + if unsafe sortedSources[c - 1] - minSource == c - 1 { // Contiguous indices in a different order: rotate, then permute. - _moveSubrange(minSource ..< minSource + c, toOffset: destination) + unsafe _moveSubrange(minSource ..< minSource + c, toOffset: destination) withUnsafeTemporaryAllocation(of: Int.self, capacity: c) { perm in for i in 0 ..< c { - perm[i] = sourceOffsets[i] - minSource + unsafe perm[i] = sourceOffsets[i] - minSource } - _applyPermutation(perm, offset: destination) + unsafe _applyPermutation(perm, offset: destination) } return } - _moveScattered( + unsafe _moveScattered( movingFrom: sourceOffsets, sortedSources: sortedSources, to: destination, @@ -647,13 +649,13 @@ extension UnsafeMutableBufferPointer { let src = source.lowerBound let count = source.count if destination < src { - _reverse(destination ..< src) - _reverse(src ..< src + count) - _reverse(destination ..< src + count) + unsafe _reverse(destination ..< src) + unsafe _reverse(src ..< src + count) + unsafe _reverse(destination ..< src + count) } else { - _reverse(src ..< src + count) - _reverse(src + count ..< destination + count) - _reverse(src ..< destination + count) + unsafe _reverse(src ..< src + count) + unsafe _reverse(src + count ..< destination + count) + unsafe _reverse(src ..< destination + count) } } @@ -663,7 +665,7 @@ extension UnsafeMutableBufferPointer { var lo = range.lowerBound var hi = range.upperBound - 1 while lo < hi { - swapAt(lo, hi) + unsafe swapAt(lo, hi) lo += 1 hi -= 1 } @@ -686,11 +688,11 @@ extension UnsafeMutableBufferPointer { of: Element.self, capacity: count ) { saved in for i in 0 ..< count { - saved.initializeElement(at: i, to: self[sourceOffsets[i]]) + unsafe saved.initializeElement(at: i, to: self[sourceOffsets[i]]) } - defer { saved.baseAddress!.deinitialize(count: count) } + defer { unsafe saved.baseAddress!.deinitialize(count: count) } - _compactAndPlace( + unsafe _compactAndPlace( removing: sortedSources, inserting: saved, at: destination, @@ -719,12 +721,12 @@ extension UnsafeMutableBufferPointer { var readLeft = 0 var si = 0 while writeLeft < destination { - if si < removalCount && sortedRemovals[si] == readLeft { + if unsafe si < removalCount && sortedRemovals[si] == readLeft { si += 1 readLeft += 1 } else { if writeLeft != readLeft { - self[writeLeft] = self[readLeft] + unsafe self[writeLeft] = self[readLeft] } writeLeft += 1 readLeft += 1 @@ -737,12 +739,12 @@ extension UnsafeMutableBufferPointer { var readRight = totalCount - 1 var sj = removalCount - 1 while writeRight >= destination + removalCount { - if sj >= 0 && sortedRemovals[sj] == readRight { + if unsafe sj >= 0 && sortedRemovals[sj] == readRight { sj -= 1 readRight -= 1 } else { if writeRight != readRight { - self[writeRight] = self[readRight] + unsafe self[writeRight] = self[readRight] } writeRight -= 1 readRight -= 1 @@ -751,7 +753,7 @@ extension UnsafeMutableBufferPointer { // Place inserted elements in the gap. for i in 0 ..< removalCount { - self[destination + i] = insertions[i] + unsafe self[destination + i] = insertions[i] } } @@ -765,17 +767,17 @@ extension UnsafeMutableBufferPointer { offset: Int ) { for start in 0 ..< perm.count { - guard perm[start] != start else { continue } + guard unsafe perm[start] != start else { continue } var j = start - let temp = self[offset + j] - while perm[j] != start { - let from = perm[j] - self[offset + j] = self[offset + from] - perm[j] = j + let temp = unsafe self[offset + j] + while unsafe perm[j] != start { + let from = unsafe perm[j] + unsafe self[offset + j] = self[offset + from] + unsafe perm[j] = j j = from } - self[offset + j] = temp - perm[j] = j + unsafe self[offset + j] = temp + unsafe perm[j] = j } } } @@ -789,7 +791,7 @@ extension UnsafeBufferPointer where Element == Int { var hi = count while lo < hi { let mid = lo + (hi - lo) / 2 - if self[mid] < value { + if unsafe self[mid] < value { lo = mid + 1 } else { hi = mid diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift index 8be97ff8..d8d5b6ed 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial MutableCollection.swift @@ -35,9 +35,10 @@ extension OrderedSet { _elements.swapAt(i, j) guard _table != nil else { return } _ensureUnique() - _table!.update { hashTable in - hashTable.swapBucketValues(for: _elements[i], withCurrentValue: j, - and: _elements[j], withCurrentValue: i) + unsafe _table!.update { hashTable in + unsafe hashTable.swapBucketValues( + for: _elements[i], withCurrentValue: j, + and: _elements[j], withCurrentValue: i) } _checkInvariants() } @@ -95,9 +96,9 @@ extension OrderedSet { return try _elements.partition(by: belongsInSecondPartition) } _ensureUnique() - let result: Int = try _table!.update { hashTable in + let result: Int = unsafe try _table!.update { hashTable in let maybeOffset: Int? = try _elements.withContiguousMutableStorageIfAvailable { buffer in - let pivot = try buffer._partition( + let pivot = unsafe try buffer._partition( with: hashTable, by: belongsInSecondPartition, callback: callback) @@ -106,7 +107,7 @@ extension OrderedSet { if let offset = maybeOffset { return _elements.index(startIndex, offsetBy: offset) } - return try _elements._partition( + return unsafe try _elements._partition( with: hashTable, by: belongsInSecondPartition, callback: callback) @@ -150,8 +151,9 @@ extension MutableCollection where Self: RandomAccessCollection, Element: Hashabl swapAt(low, high) let offsetLow = _offset(of: low) let offsetHigh = _offset(of: high) - hashTable.swapBucketValues(for: self[low], withCurrentValue: offsetHigh, - and: self[high], withCurrentValue: offsetLow) + unsafe hashTable.swapBucketValues( + for: self[low], withCurrentValue: offsetHigh, + and: self[high], withCurrentValue: offsetLow) callback(offsetLow, offsetHigh) formIndex(after: &low) @@ -166,10 +168,11 @@ extension _UnsafeHashTable { for left: Element, withCurrentValue leftValue: Int, and right: Element, withCurrentValue rightValue: Int ) { - let left = idealBucket(for: left) - let right = idealBucket(for: right) - swapBucketValues(for: left, withCurrentValue: leftValue, - and: right, withCurrentValue: rightValue) + let left = unsafe idealBucket(for: left) + let right = unsafe idealBucket(for: right) + unsafe swapBucketValues( + for: left, withCurrentValue: leftValue, + and: right, withCurrentValue: rightValue) } @usableFromInline @@ -178,13 +181,13 @@ extension _UnsafeHashTable { for left: Bucket, withCurrentValue leftValue: Int, and right: Bucket, withCurrentValue rightValue: Int ) { - var it = bucketIterator(startingAt: left) - it.advance(until: leftValue) + var it = unsafe bucketIterator(startingAt: left) + unsafe it.advance(until: leftValue) assert(it.isOccupied) - it.currentValue = rightValue + unsafe it.currentValue = rightValue - it = bucketIterator(startingAt: right) - it.advance(until: rightValue) + unsafe it = bucketIterator(startingAt: right) + unsafe it.advance(until: rightValue) assert(it.isOccupied) // Note: this second update may mistake the bucket for `right` with the // bucket for `left` whose value we just updated. The second update will @@ -192,7 +195,7 @@ extension _UnsafeHashTable { // When this happens, the lookup chains for both elements include each // other, so leaving the hash table unchanged still leaves us with a // working hash table. - it.currentValue = leftValue + unsafe it.currentValue = leftValue } } @@ -371,7 +374,7 @@ extension OrderedSet { precondition(self.count == values.count) var i = 0 try _elements.withUnsafeMutableBufferPointer { keys in - while i < keys.count, try !belongsInSecondPartition((keys[i], values[i])) { + while i < keys.count, try !belongsInSecondPartition(unsafe (keys[i], values[i])) { i += 1 } } @@ -384,14 +387,15 @@ extension OrderedSet { return try _elements.withUnsafeMutableBufferPointer { keys in for j in i + 1 ..< keys.count { - guard try !belongsInSecondPartition((keys[j], values[j])) else { + guard try !belongsInSecondPartition(unsafe (keys[j], values[j])) else { continue } - keys.swapAt(i, j) - values.swapAt(i, j) - table?.update { hashTable in - hashTable.swapBucketValues(for: keys[i], withCurrentValue: j, - and: keys[j], withCurrentValue: i) + unsafe keys.swapAt(i, j) + unsafe values.swapAt(i, j) + unsafe table?.update { hashTable in + unsafe hashTable.swapBucketValues( + for: keys[i], withCurrentValue: j, + and: keys[j], withCurrentValue: i) } i += 1 } @@ -422,7 +426,7 @@ extension OrderedSet { // Find next element from `lo` that may not be in the right place. while true { if low == high { return low } - if try belongsInSecondPartition((keys[low], values[low])) { break } + if try belongsInSecondPartition(unsafe (keys[low], values[low])) { break } low += 1 } @@ -430,15 +434,16 @@ extension OrderedSet { while true { high -= 1 if low == high { return low } - if try !belongsInSecondPartition((keys[high], values[high])) { break } + if try !belongsInSecondPartition(unsafe (keys[high], values[high])) { break } } // Swap the two elements as well as their associated hash table buckets. - keys.swapAt(low, high) - values.swapAt(low, high) - table?.update { hashTable in - hashTable.swapBucketValues(for: keys[low], withCurrentValue: high, - and: keys[high], withCurrentValue: low) + unsafe keys.swapAt(low, high) + unsafe values.swapAt(low, high) + unsafe table?.update { hashTable in + unsafe hashTable.swapBucketValues( + for: keys[low], withCurrentValue: high, + and: keys[high], withCurrentValue: low) } low += 1 } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift index c91583ef..90da6bbd 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial RangeReplaceableCollection.swift @@ -30,8 +30,8 @@ extension OrderedSet { } guard _table != nil else { return } _ensureUnique() - _table!.update { hashTable in - hashTable.clear() + unsafe _table!.update { hashTable in + unsafe hashTable.clear() } } @@ -52,7 +52,7 @@ extension OrderedSet { public mutating func remove(at index: Int) -> Self.Element { _elements._failEarlyRangeCheck(index, bounds: startIndex ..< endIndex) let bucket = _bucket(for: index) - return _removeExistingMember(at: index, in: bucket) + return unsafe _removeExistingMember(at: index, in: bucket) } /// Removes the specified subrange of elements from the collection. @@ -86,18 +86,18 @@ extension OrderedSet { } _ensureUnique() - _table!.update { hashTable in + unsafe _table!.update { hashTable in // Delete the hash table entries for all members we're removing. for item in _elements[bounds] { - let (offset, bucket) = hashTable._find(item, in: _elements) + let (offset, bucket) = unsafe hashTable._find(item, in: _elements) precondition(offset != nil, "Corrupt hash table") - hashTable.delete( + unsafe hashTable.delete( bucket: bucket, hashValueGenerator: { offset, seed in return _elements[offset]._rawHashValue(seed: seed) }) } - hashTable.adjustContents(preparingForRemovalOf: bounds, in: _elements) + unsafe hashTable.adjustContents(preparingForRemovalOf: bounds, in: _elements) } _elements.removeSubrange(bounds) _checkInvariants() @@ -136,11 +136,11 @@ extension OrderedSet { defer { _checkInvariants() } let old = _elements.removeLast() _ensureUnique() - _table!.update { hashTable in - var it = hashTable.bucketIterator(for: old) - it.advance(until: _elements.count) + unsafe _table!.update { hashTable in + var it = unsafe hashTable.bucketIterator(for: old) + unsafe it.advance(until: _elements.count) // Delete the entry for the removed member. - hashTable.delete( + unsafe hashTable.delete( bucket: it.currentBucket, hashValueGenerator: { offset, seed in _elements[offset]._rawHashValue(seed: seed) diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift index 892f7219..853bf3bf 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra intersection.swift @@ -47,7 +47,7 @@ extension OrderedSet { var result = Self() for item in self { if other.contains(item) { - result._appendNew(item) + unsafe result._appendNew(item) } } result._checkInvariants() @@ -99,13 +99,13 @@ extension OrderedSet { public __consuming func intersection( _ other: some Sequence ) -> Self { - _UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset in + unsafe _UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset in for item in other { if let index = self._find_inlined(item).index { - bitset.insert(index) + unsafe bitset.insert(index) } } - return self._extractSubset(using: bitset) + return unsafe self._extractSubset(using: bitset) } } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqualSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqualSet.swift index 0b76b42c..cc62a97b 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqualSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isEqualSet.swift @@ -74,11 +74,11 @@ extension OrderedSet { } #endif - return _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in + return unsafe _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in var c = 0 for item in other { guard let index = _find(item).index else { return false } - if seen.insert(index) { + if unsafe seen.insert(index) { c &+= 1 } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift index d43bbd5e..2e9c45e8 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSubset.swift @@ -140,13 +140,13 @@ extension OrderedSet { return !other.allSatisfy { self.contains($0) } } - return _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in + return unsafe _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in // Mark elements in `self` that we've seen in `other`. var isKnownStrict = false var c = 0 for item in other { if let index = _find(item).index { - if seen.insert(index) { + if unsafe seen.insert(index) { c &+= 1 if c == self.count, isKnownStrict { // We've seen enough. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift index 4bf910e6..69b82753 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isStrictSuperset.swift @@ -140,14 +140,14 @@ extension OrderedSet { return false } - return _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in + return unsafe _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in // Mark elements in `self` that we've seen in `other`. var c = 0 for item in other { guard let index = _find(item).index else { return false } - if seen.insert(index) { + if unsafe seen.insert(index) { c &+= 1 if c == self.count { // We've seen enough. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift index fa316dba..228dbef7 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra isSubset.swift @@ -137,12 +137,12 @@ extension OrderedSet { return true } - return _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in + return unsafe _UnsafeBitSet.withTemporaryBitSet(capacity: count) { seen in // Mark elements in `self` that we've seen in `other`. var c = 0 for item in other { if let index = _find(item).index { - if seen.insert(index) { + if unsafe seen.insert(index) { c &+= 1 if c == self.count { // We've seen enough. diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift index 4740a2a2..16251487 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra subtracting.swift @@ -92,12 +92,12 @@ extension OrderedSet { @inlinable __consuming func _subtracting(_ other: some Sequence) -> Self { guard count > 0 else { return Self() } - return _UnsafeBitSet.withTemporaryBitSet(capacity: count) { difference in - difference.insertAll(upTo: count) + return unsafe _UnsafeBitSet.withTemporaryBitSet(capacity: count) { difference in + unsafe difference.insertAll(upTo: count) var c = count for item in other { if let index = self._find(item).index { - if difference.remove(index) { + if unsafe difference.remove(index) { c &-= 1 if c == 0 { return Self() @@ -106,7 +106,7 @@ extension OrderedSet { } } assert(c > 0) - return _extractSubset(using: difference, count: c) + return unsafe _extractSubset(using: difference, count: c) } } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift index 9531a849..67155c27 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra symmetricDifference.swift @@ -43,24 +43,25 @@ extension OrderedSet { /// `Element` implements high-quality hashing. @inlinable public __consuming func symmetricDifference(_ other: __owned Self) -> Self { - _UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset1 in - _UnsafeBitSet.withTemporaryBitSet(capacity: other.count) { bitset2 in - bitset1.insertAll(upTo: self.count) + unsafe _UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset1 in + unsafe _UnsafeBitSet.withTemporaryBitSet(capacity: other.count) { bitset2 in + unsafe bitset1.insertAll(upTo: self.count) for item in other { if let index = self._find(item).index { - bitset1.remove(index) + unsafe bitset1.remove(index) } } - bitset2.insertAll(upTo: other.count) + unsafe bitset2.insertAll(upTo: other.count) for item in self { if let index = other._find(item).index { - bitset2.remove(index) + unsafe bitset2.remove(index) } } - var result = self._extractSubset(using: bitset1, - extraCapacity: bitset2.count) - for offset in bitset2 { - result._appendNew(other._elements[Int(bitPattern: offset)]) + var result = unsafe self._extractSubset( + using: bitset1, + extraCapacity: bitset2.count) + for unsafe offset in unsafe bitset2 { + unsafe result._appendNew(other._elements[Int(bitPattern: offset)]) } result._checkInvariants() return result @@ -118,19 +119,19 @@ extension OrderedSet { public __consuming func symmetricDifference( _ other: __owned some Sequence ) -> Self { - _UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset in + unsafe _UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset in var new = Self() - bitset.insertAll(upTo: self.count) + unsafe bitset.insertAll(upTo: self.count) for item in other { if let index = self._find(item).index { - bitset.remove(index) + unsafe bitset.remove(index) } else { new.append(item) } } - var result = _extractSubset(using: bitset, extraCapacity: new.count) + var result = unsafe _extractSubset(using: bitset, extraCapacity: new.count) for item in new._elements { - result._appendNew(item) + unsafe result._appendNew(item) } result._checkInvariants() return result diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift index 59ab5444..3b7270b8 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Partial SetAlgebra+Basics.swift @@ -72,7 +72,7 @@ extension OrderedSet { public mutating func remove(_ member: Element) -> Element? { let (idx, bucket) = _find(member) guard let index = idx else { return nil } - return _removeExistingMember(at: index, in: bucket) + return unsafe _removeExistingMember(at: index, in: bucket) } } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift index 35c286a4..5941899a 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+RandomAccessCollection.swift @@ -39,7 +39,7 @@ extension OrderedSet: Sequence { preconditionFailure("Attempt to copy contents into nil buffer pointer") } let c = Swift.min(buffer.count, ptr.count) - p.initialize(from: buffer.baseAddress!, count: c) + unsafe p.initialize(from: buffer.baseAddress!, count: c) return c } return (Iterator(_elements: self, _position: copied), copied) @@ -273,8 +273,8 @@ extension OrderedSet: RandomAccessCollection { guard let table = _table else { return _elements._customIndexOfEquatableElement(element) } - return table.read { hashTable in - let (o, _) = hashTable._find(element, in: _elements) + return unsafe table.read { hashTable in + let (o, _) = unsafe hashTable._find(element, in: _elements) guard let offset = o else { return .some(nil) } return offset } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift index 26ba74fb..4a7c3594 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+SubSequence.swift @@ -98,7 +98,7 @@ extension OrderedSet.SubSequence: Sequence { } let c = Swift.min(buffer.count, ptr.count) if c > 0 { - p.initialize(from: buffer.baseAddress!, count: c) + unsafe p.initialize(from: buffer.baseAddress!, count: c) } return c } diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift index fe496e7c..5d64200d 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet+Testing.swift @@ -50,8 +50,8 @@ extension OrderedSet { @_alwaysEmitIntoClient package static func _biasRange(scale: Int) -> Range { - guard scale != 0 else { return Range(uncheckedBounds: (0, 1)) } - return Range(uncheckedBounds: (0, (1 &<< scale) - 1)) + guard scale != 0 else { return unsafe Range(uncheckedBounds: (0, 1)) } + return unsafe Range(uncheckedBounds: (0, (1 &<< scale) - 1)) } } @@ -67,8 +67,8 @@ extension OrderedSet._UnstableInternals { package var hashTableContents: [Int?] { guard let table = base._table else { return [] } - return table.read { hashTable in - hashTable.debugContents() + return unsafe table.read { hashTable in + unsafe hashTable.debugContents() } } @@ -76,13 +76,13 @@ extension OrderedSet._UnstableInternals { package mutating func _regenerateHashTable(bias: Int) { base._ensureUnique() let new = base._table!.copy() - base._table!.read { source in - new.update { target in - target.bias = bias - var it = source.bucketIterator(startingAt: _Bucket(offset: 0)) + unsafe base._table!.read { source in + unsafe new.update { target in + unsafe target.bias = bias + var it = unsafe source.bucketIterator(startingAt: _Bucket(offset: 0)) repeat { - target[it.currentBucket] = it.currentValue - it.advance() + unsafe target[it.currentBucket] = it.currentValue + unsafe it.advance() } while it.currentBucket.offset != 0 } } @@ -113,8 +113,8 @@ extension OrderedSet { precondition(scale >= _HashTable.minimumScale || bias == 0) let table = _HashTable(scale: Swift.max(scale, _HashTable.minimumScale)) table.header.bias = bias - let (success, index) = table.update { hashTable in - hashTable.fill(untilFirstDuplicateIn: contents) + let (success, index) = unsafe table.update { hashTable in + unsafe hashTable.fill(untilFirstDuplicateIn: contents) } precondition(success, "Duplicate element at index \(index)") self.init( diff --git a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift index 64f42448..d3a3e9f2 100644 --- a/Sources/OrderedCollections/OrderedSet/OrderedSet.swift +++ b/Sources/OrderedCollections/OrderedSet/OrderedSet.swift @@ -402,9 +402,9 @@ extension OrderedSet { return } _ensureUnique() - _table!.update { hashTable in - hashTable.clear() - hashTable.fill(uncheckedUniqueElements: _elements) + unsafe _table!.update { hashTable in + unsafe hashTable.clear() + unsafe hashTable.fill(uncheckedUniqueElements: _elements) } } @@ -414,8 +414,8 @@ extension OrderedSet { return } _ensureUnique() - _table!.update { hashTable in - hashTable.reverse(count: _elements.count) + unsafe _table!.update { hashTable in + unsafe hashTable.reverse(count: _elements.count) } } } @@ -446,10 +446,10 @@ extension OrderedSet { internal func _find_inlined(_ item: Element) -> (index: Int?, bucket: _Bucket) { _elements.withUnsafeBufferPointer { elements in guard let table = _table else { - return (elements._firstIndex(of: item), _Bucket(offset: 0)) + return unsafe (elements._firstIndex(of: item), _Bucket(offset: 0)) } - return table.read { hashTable in - hashTable._find(item, in: elements) + return unsafe table.read { hashTable in + unsafe hashTable._find(item, in: elements) } } } @@ -457,9 +457,9 @@ extension OrderedSet { @inlinable internal func _bucket(for index: Int) -> _Bucket { guard let table = _table else { return _Bucket(offset: 0) } - return table.read { hashTable in - var it = hashTable.bucketIterator(for: _elements[index]) - it.advance(until: index) + return unsafe table.read { hashTable in + var it = unsafe hashTable.bucketIterator(for: _elements[index]) + unsafe it.advance(until: index) precondition(it.isOccupied, "Corrupt hash table") return it.currentBucket } @@ -501,10 +501,10 @@ extension UnsafeBufferPointer where Element: Equatable { func _firstIndex(of element: Element) -> Index? { var i = self.startIndex while i != self.endIndex { - if self[i] == element { + if unsafe self[i] == element { return i } - self.formIndex(after: &i) + unsafe self.formIndex(after: &i) } return nil } @@ -518,8 +518,8 @@ extension OrderedSet { count: Int? = nil, extraCapacity: Int = 0 ) -> Self { - let c = count ?? bitset.count - assert(c == 0 || bitset.max()! <= self.count) + let c = unsafe count ?? bitset.count + assert(unsafe c == 0 || bitset.max()! <= self.count) if c == 0 { return Self(minimumCapacity: extraCapacity) } if c == self.count { if extraCapacity <= self._capacity - self.count { @@ -530,8 +530,8 @@ extension OrderedSet { return copy } var result = Self(minimumCapacity: c + extraCapacity) - for offset in bitset { - result._appendNew(_elements[Int(bitPattern: offset)]) + for unsafe offset in unsafe bitset { + unsafe result._appendNew(_elements[Int(bitPattern: offset)]) } assert(result.count == c) result._checkInvariants() @@ -542,6 +542,7 @@ extension OrderedSet { extension OrderedSet { @inlinable @discardableResult + @unsafe internal mutating func _removeExistingMember( at index: Int, in bucket: _Bucket @@ -557,14 +558,14 @@ extension OrderedSet { defer { _checkInvariants() } _ensureUnique() - _table!.update { hashTable in + unsafe _table!.update { hashTable in // Delete the entry for the removed member. - hashTable.delete( + unsafe hashTable.delete( bucket: bucket, hashValueGenerator: { offset, seed in _elements[offset]._rawHashValue(seed: seed) }) - hashTable.adjustContents(preparingForRemovalOf: index, in: _elements) + unsafe hashTable.adjustContents(preparingForRemovalOf: index, in: _elements) } return _elements.remove(at: index) } @@ -585,11 +586,11 @@ extension OrderedSet { public func filter( _ isIncluded: (Element) throws -> Bool ) rethrows -> Self { - try _UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset in + unsafe try _UnsafeBitSet.withTemporaryBitSet(capacity: self.count) { bitset in for i in _elements.indices where try isIncluded(_elements[i]) { - bitset.insert(i) + unsafe bitset.insert(i) } - return self._extractSubset(using: bitset) + return unsafe self._extractSubset(using: bitset) } } } diff --git a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift index c53cb7be..2061ce2a 100644 --- a/Sources/RopeModule/BigString/Basics/BigString+Contents.swift +++ b/Sources/RopeModule/BigString/Basics/BigString+Contents.swift @@ -543,20 +543,20 @@ extension BigString { let endRopeIndex = end._rope! if ri == endRopeIndex { - let buffer = _rope[ri]._bytes.extracting(start._chunkIndex.utf8Offset ..< end._chunkIndex.utf8Offset) - body(buffer) + let buffer = unsafe _rope[ri]._bytes.extracting(start._chunkIndex.utf8Offset ..< end._chunkIndex.utf8Offset) + unsafe body(buffer) return } - body(_rope[ri]._bytes.extracting(start._chunkIndex.utf8Offset...)) + unsafe body(_rope[ri]._bytes.extracting(start._chunkIndex.utf8Offset...)) _rope.formIndex(after: &ri) while ri < endRopeIndex { - body(_rope[ri]._bytes) + unsafe body(_rope[ri]._bytes) _rope.formIndex(after: &ri) } - body(_rope[ri]._bytes.extracting(.. diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Append and Insert.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Append and Insert.swift index eb6b62f2..368c7044 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Append and Insert.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+Append and Insert.swift @@ -49,15 +49,15 @@ extension BigString._Chunk { } mutating func _append(_ str: consuming Substring, _ other: Counts) { - _append(other) { - _ = $0.initialize(from: str.utf8) + unsafe _append(other) { + _ = unsafe $0.initialize(from: str.utf8) } } mutating func _append(_ span: UTF8Span, _ other: Counts) { - _append(other) { buffer in + unsafe _append(other) { buffer in span.span.withUnsafeBufferPointer { - _ = buffer.initialize(fromContentsOf: $0) + _ = unsafe buffer.initialize(fromContentsOf: $0) } } } @@ -71,13 +71,11 @@ extension BigString._Chunk { let utf8Before = Int(counts.utf8) counts.append(newCounts) - storage.withUnsafeMutablePointerToElements { - let buffer = UnsafeMutableBufferPointer( + unsafe storage.withUnsafeMutablePointerToElements { + let buffer = unsafe UnsafeMutableBufferPointer( start: $0, - count: Self.maxUTF8Count - ) - - body(buffer.extracting(utf8Before...)) + count: Self.maxUTF8Count) + unsafe body(buffer.extracting(utf8Before...)) } invariantCheck() @@ -89,17 +87,17 @@ extension BigString._Chunk { precondition(to.utf8Offset + originalRange.count <= Self.maxUTF8Count) // Only grab the slice pointing at initialized code units. - let originalBuffer = _mutableBytes.extracting(originalRange) + let originalBuffer = unsafe _mutableBytes.extracting(originalRange) // Grab the buffer starting from the shifted utf8 offset till the // length of the already initialized buffer. let newOriginalRange = to.utf8Offset ..< originalRange.count + to.utf8Offset - let newOriginalBuffer = _mutableBytes.extracting(newOriginalRange) + let newOriginalBuffer = unsafe _mutableBytes.extracting(newOriginalRange) // Initialize the contents of the new buffer from the original. // // Note: This most likely overlaps - _ = newOriginalBuffer.moveInitialize(fromContentsOf: originalBuffer) + _ = unsafe newOriginalBuffer.moveInitialize(fromContentsOf: originalBuffer) } mutating func _prepend(_ span: UTF8Span, _ other: Counts) { @@ -113,11 +111,11 @@ extension BigString._Chunk { // Grab the prepended text's buffer. let prependRange = 0.. String { diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+UTF16.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+UTF16.swift index 787bda0a..9c6d8718 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+UTF16.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+UTF16.swift @@ -129,28 +129,28 @@ extension BigString._Chunk { var utf16Count = 0 let utf8Offset = j.utf8Offset - i.utf8Offset - var readPtr = _bytes.baseAddress.unsafelyUnwrapped + i.utf8Offset - let endPtr = readPtr + utf8Offset + var readPtr = unsafe _bytes.baseAddress.unsafelyUnwrapped + i.utf8Offset + let endPtr = unsafe readPtr + utf8Offset - while readPtr < endPtr { - let byte = readPtr.pointee + while unsafe readPtr < endPtr { + let byte = unsafe readPtr.pointee if !UTF8.isContinuation(byte) { break } - readPtr += 1 + unsafe readPtr += 1 } - while readPtr < endPtr { - let byte = readPtr.pointee + while unsafe readPtr < endPtr { + let byte = unsafe readPtr.pointee let len = utf8ScalarLength(byte) - if readPtr + len <= endPtr { + if unsafe readPtr + len <= endPtr { utf16Count += len == 4 ? 2 : 1 } - readPtr += len + unsafe readPtr += len } switch (i.isUTF16TrailingSurrogate, j.isUTF16TrailingSurrogate) { diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+UnicodeScalar.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+UnicodeScalar.swift index 6a52e954..40c9f4e2 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk+UnicodeScalar.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk+UnicodeScalar.swift @@ -34,7 +34,7 @@ extension BigString._Chunk { var i = i - while UTF8.isContinuation(_bytes[i.utf8Offset]) { + while UTF8.isContinuation(unsafe _bytes[i.utf8Offset]) { i = i.offset(by: -1) } @@ -46,7 +46,7 @@ extension BigString._Chunk { i = i.offset(by: 1) - while i < endIndex, UTF8.isContinuation(_bytes[i.utf8Offset]) { + while i < endIndex, UTF8.isContinuation(unsafe _bytes[i.utf8Offset]) { i = i.offset(by: 1) } @@ -58,7 +58,7 @@ extension BigString._Chunk { i = i.offset(by: -1) - while i > startIndex, UTF8.isContinuation(_bytes[i.utf8Offset]) { + while i > startIndex, UTF8.isContinuation(unsafe _bytes[i.utf8Offset]) { i = i.offset(by: -1) } @@ -108,7 +108,7 @@ extension BigString._Chunk { let i = scalarIndex(roundingDown: i) - let x = _bytes[i.utf8Offset] + let x = unsafe _bytes[i.utf8Offset] if UTF8.isASCII(x) { return Unicode.Scalar(x) @@ -117,22 +117,22 @@ extension BigString._Chunk { switch utf8ScalarLength(x) { case 2: let x = UInt32(x & 0b0001_1111) - let cont = UInt32(_bytes[i.offset(by: 1).utf8Offset] & 0b0011_1111) + let cont = UInt32(unsafe _bytes[i.offset(by: 1).utf8Offset] & 0b0011_1111) let c = (x &<< 6) | cont - return Unicode.Scalar(c).unsafelyUnwrapped + return unsafe Unicode.Scalar(c).unsafelyUnwrapped case 3: let x = UInt32(x & 0b0000_1111) - let cont1 = UInt32(_bytes[i.offset(by: 1).utf8Offset] & 0b0011_1111) - let cont2 = UInt32(_bytes[i.offset(by: 2).utf8Offset] & 0b0011_1111) + let cont1 = UInt32(unsafe _bytes[i.offset(by: 1).utf8Offset] & 0b0011_1111) + let cont2 = UInt32(unsafe _bytes[i.offset(by: 2).utf8Offset] & 0b0011_1111) let c = (x &<< 12) | (cont1 &<< 6) | cont2 - return Unicode.Scalar(c).unsafelyUnwrapped + return unsafe Unicode.Scalar(c).unsafelyUnwrapped case 4: let x = UInt32(x & 0b0000_0111) - let cont1 = UInt32(_bytes[i.offset(by: 1).utf8Offset] & 0b0011_1111) - let cont2 = UInt32(_bytes[i.offset(by: 2).utf8Offset] & 0b0011_1111) - let cont3 = UInt32(_bytes[i.offset(by: 3).utf8Offset] & 0b0011_1111) + let cont1 = UInt32(unsafe _bytes[i.offset(by: 1).utf8Offset] & 0b0011_1111) + let cont2 = UInt32(unsafe _bytes[i.offset(by: 2).utf8Offset] & 0b0011_1111) + let cont3 = UInt32(unsafe _bytes[i.offset(by: 3).utf8Offset] & 0b0011_1111) let c = (x &<< 18) | (cont1 &<< 12) | (cont2 &<< 6) | cont3 - return Unicode.Scalar(c).unsafelyUnwrapped + return unsafe Unicode.Scalar(c).unsafelyUnwrapped default: fatalError() } diff --git a/Sources/RopeModule/BigString/Chunk/BigString+Chunk.swift b/Sources/RopeModule/BigString/Chunk/BigString+Chunk.swift index dab502c2..268ed599 100644 --- a/Sources/RopeModule/BigString/Chunk/BigString+Chunk.swift +++ b/Sources/RopeModule/BigString/Chunk/BigString+Chunk.swift @@ -22,27 +22,26 @@ extension BigString { var storage: ManagedBuffer<(), UInt8> init() { - self.init(Counts()) { _ in } + unsafe self.init(Counts()) { _ in } } init(_ counts: Counts, _ body: (UnsafeMutableBufferPointer) -> ()) { self.counts = counts storage = .create(minimumCapacity: Self.maxUTF8Count) { - $0.withUnsafeMutablePointerToElements { - let buffer = UnsafeMutableBufferPointer( + unsafe $0.withUnsafeMutablePointerToElements { + let buffer = unsafe UnsafeMutableBufferPointer( start: $0, count: Self.maxUTF8Count ) - - body(buffer) + unsafe body(buffer) } } } init(_ string: String, _ counts: Counts) { - self.init(counts) { - _ = $0.initialize(from: string.utf8) + unsafe self.init(counts) { + _ = unsafe $0.initialize(from: string.utf8) } } @@ -51,9 +50,9 @@ extension BigString { } init(copying span: UTF8Span, _ counts: Counts) { - self.init(counts) { buffer in + unsafe self.init(counts) { buffer in span.span.withUnsafeBufferPointer { - _ = buffer.initialize(fromContentsOf: $0) + _ = unsafe buffer.initialize(fromContentsOf: $0) } } } @@ -77,31 +76,31 @@ extension BigString._Chunk { } var _bytes: UnsafeBufferPointer { - storage.withUnsafeMutablePointerToElements { - UnsafeBufferPointer(start: $0, count: Int(counts.utf8)) + unsafe storage.withUnsafeMutablePointerToElements { + unsafe UnsafeBufferPointer(start: $0, count: Int(counts.utf8)) } } // Note: This should ONLY be called by '_prepend'. Also, this is over the // entire chunk's buffer instead of just the initialized code units. var _mutableBytes: UnsafeMutableBufferPointer { - storage.withUnsafeMutablePointerToElements { - UnsafeMutableBufferPointer(start: $0, count: Self.maxUTF8Count) + unsafe storage.withUnsafeMutablePointerToElements { + unsafe UnsafeMutableBufferPointer(start: $0, count: Self.maxUTF8Count) } } var span: Span { @_lifetime(borrow self) get { - let span = Span(_unsafeElements: _bytes) - return _overrideLifetime(span, borrowing: self) + let span = unsafe Span(_unsafeElements: _bytes) + return unsafe _overrideLifetime(span, borrowing: self) } } var utf8Span: UTF8Span { @_lifetime(borrow self) get { - return _overrideLifetime(UTF8Span(unchecked: span), borrowing: self) + return unsafe _overrideLifetime(UTF8Span(unchecked: span), borrowing: self) } } @@ -109,11 +108,11 @@ extension BigString._Chunk { func utf8Span(from i: Index, to j: Index? = nil) -> UTF8Span { guard j == nil else { let span = span.extracting(i.utf8Offset.. Self { - Self(counts) { - _ = $0.initialize(fromContentsOf: _bytes) + unsafe Self(counts) { + _ = unsafe $0.initialize(fromContentsOf: _bytes) } } diff --git a/Sources/RopeModule/BigString/Conformances/BigString+Equatable.swift b/Sources/RopeModule/BigString/Conformances/BigString+Equatable.swift index 76e50d63..3ae9cfdf 100644 --- a/Sources/RopeModule/BigString/Conformances/BigString+Equatable.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+Equatable.swift @@ -62,9 +62,9 @@ extension BigString { var remaining = left._utf8Count while remaining > 0 { - let consumed = it1.next(maximumCount: remaining) { b1 in - let consumed = it2.next(maximumCount: b1.count) { b2 in - guard b2.elementsEqual(b1.prefix(b2.count)) else { return (0, 0) } + let consumed = unsafe it1.next(maximumCount: remaining) { b1 in + let consumed = unsafe it2.next(maximumCount: b1.count) { b2 in + guard unsafe b2.elementsEqual(b1.prefix(b2.count)) else { return (0, 0) } return (b2.count, b2.count) } return (consumed, consumed) @@ -90,9 +90,9 @@ extension BigString { var it2 = BigString.UTF8View.Iterator(_base: right, from: rightRange.lowerBound) while remaining > 0 { - let consumed = it1.next(maximumCount: remaining) { b1 in - let consumed = it2.next(maximumCount: b1.count) { b2 in - guard b2.elementsEqual(b1.prefix(b2.count)) else { return (0, 0) } + let consumed = unsafe it1.next(maximumCount: remaining) { b1 in + let consumed = unsafe it2.next(maximumCount: b1.count) { b2 in + guard unsafe b2.elementsEqual(b1.prefix(b2.count)) else { return (0, 0) } return (b2.count, b2.count) } return (consumed, consumed) diff --git a/Sources/RopeModule/BigString/Conformances/BigString+Hashing.swift b/Sources/RopeModule/BigString/Conformances/BigString+Hashing.swift index 0cf8d3c0..1b9ae849 100644 --- a/Sources/RopeModule/BigString/Conformances/BigString+Hashing.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+Hashing.swift @@ -39,7 +39,7 @@ extension BigString { /// Feed the UTF-8 encoding of `self` into hasher, with a terminating byte. internal func hashUTF8(into hasher: inout Hasher) { for chunk in self._rope { - hasher.combine(bytes: UnsafeRawBufferPointer(chunk._bytes)) + unsafe hasher.combine(bytes: UnsafeRawBufferPointer(chunk._bytes)) } hasher.combine(0xFF as UInt8) } @@ -47,8 +47,8 @@ extension BigString { /// Feed the UTF-8 encoding of `self[start.. Bool { diff --git a/Sources/RopeModule/BigString/Conformances/BigString+TextOutputStream.swift b/Sources/RopeModule/BigString/Conformances/BigString+TextOutputStream.swift index b46d9bfb..dc2bd7f0 100644 --- a/Sources/RopeModule/BigString/Conformances/BigString+TextOutputStream.swift +++ b/Sources/RopeModule/BigString/Conformances/BigString+TextOutputStream.swift @@ -25,7 +25,7 @@ extension BigString: TextOutputStreamable { public func write(to target: inout some TextOutputStream) { for chunk in _rope { let str = String(unsafeUninitializedCapacity: chunk.utf8Count) { - $0.initialize(fromContentsOf: chunk._bytes) + unsafe $0.initialize(fromContentsOf: chunk._bytes) } str.write(to: &target) diff --git a/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift b/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift index 0844eecb..6a14e1f3 100644 --- a/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift +++ b/Sources/RopeModule/BigString/Operations/BigString+Initializers.swift @@ -96,11 +96,11 @@ extension String { } self.init(unsafeUninitializedCapacity: big._utf8Count) { - var buffer = $0 + var buffer = unsafe $0 for chunk in big._rope { - let result = buffer.initialize(fromContentsOf: chunk._bytes) - buffer = buffer.extracting(result...) + let result = unsafe buffer.initialize(fromContentsOf: chunk._bytes) + unsafe buffer = buffer.extracting(result...) } return big._utf8Count @@ -123,28 +123,28 @@ extension String { let startRopeIndex = start._rope! let endRopeIndex = end._rope! - var dest = $0 + var dest = unsafe $0 // Fast path: The entire contents of range exist within the same chunk. if startRopeIndex == endRopeIndex { - let src = big._rope[startRopeIndex]._bytes.extracting(start._chunkIndex.utf8Offset ..< end._chunkIndex.utf8Offset) - return dest.initialize(fromContentsOf: src) + let src = unsafe big._rope[startRopeIndex]._bytes.extracting(start._chunkIndex.utf8Offset ..< end._chunkIndex.utf8Offset) + return unsafe dest.initialize(fromContentsOf: src) } - var src = big._rope[startRopeIndex]._bytes.extracting(start._chunkIndex.utf8Offset...) - var result = dest.initialize(fromContentsOf: src) - dest = dest.extracting(result...) + var src = unsafe big._rope[startRopeIndex]._bytes.extracting(start._chunkIndex.utf8Offset...) + var result = unsafe dest.initialize(fromContentsOf: src) + unsafe dest = dest.extracting(result...) var i = big._rope.index(after: startRopeIndex) while i < endRopeIndex { - let initialized = dest.initialize(fromContentsOf: big._rope[i]._bytes) + let initialized = unsafe dest.initialize(fromContentsOf: big._rope[i]._bytes) result += initialized - dest = dest.extracting(initialized...) + unsafe dest = dest.extracting(initialized...) big._rope.formIndex(after: &i) } - src = big._rope[endRopeIndex]._bytes.extracting(..) -> (consumed: Int, result: R) ) -> R { guard _index < _base.endIndex else { - let r = body(UnsafeBufferPointer(start: nil, count: 0)) + let r = unsafe body(UnsafeBufferPointer(start: nil, count: 0)) precondition(r.consumed == 0) return r.result } @@ -109,13 +109,13 @@ extension BigString.UTF8View.Iterator: IteratorProtocol { var utf8Offset = _index.utf8Offset let chunk = _base._rope[ri] - let slice = chunk._bytes[ci...].prefix(maximumCount) - assert(!slice.isEmpty) - let (consumed, result) = body(UnsafeBufferPointer(rebasing: slice)) - precondition(consumed >= 0 && consumed <= slice.count) + let slice = unsafe chunk._bytes[ci...].prefix(maximumCount) + assert(unsafe !slice.isEmpty) + let (consumed, result) = unsafe body(UnsafeBufferPointer(rebasing: slice)) + precondition(unsafe consumed >= 0 && consumed <= slice.count) utf8Offset += consumed ci += consumed - let haveMore = ci < chunk._bytes.count + let haveMore = unsafe ci < chunk._bytes.count if haveMore { _index = BigString.Index(_utf8Offset: utf8Offset, _rope: ri, chunkOffset: ci) diff --git a/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift index 3a18ecca..24a9acc4 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UTF16View.swift @@ -28,7 +28,7 @@ extension BigSubstring { self._base = base let lower = base._utf16Index(roundingDown: bounds.lowerBound) let upper = base._utf16Index(roundingDown: bounds.upperBound) - self._bounds = Range(uncheckedBounds: (lower, upper)) + self._bounds = unsafe Range(uncheckedBounds: (lower, upper)) } internal init(_substring: BigSubstring) { diff --git a/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift index 381a5088..76e8f4f1 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UTF8View.swift @@ -28,7 +28,7 @@ extension BigSubstring { self._base = base let lower = base._utf8Index(roundingDown: bounds.lowerBound) let upper = base._utf8Index(roundingDown: bounds.upperBound) - self._bounds = Range(uncheckedBounds: (lower, upper)) + self._bounds = unsafe Range(uncheckedBounds: (lower, upper)) } internal init(_substring: BigSubstring) { diff --git a/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift b/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift index dbace149..795c9827 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring+UnicodeScalarView.swift @@ -30,7 +30,7 @@ extension BigSubstring { self._base = base let lower = base._unicodeScalarIndex(roundingDown: bounds.lowerBound) let upper = base._unicodeScalarIndex(roundingDown: bounds.upperBound) - self._bounds = Range(uncheckedBounds: (lower, upper)) + self._bounds = unsafe Range(uncheckedBounds: (lower, upper)) } internal init(_substring: BigSubstring) { diff --git a/Sources/RopeModule/BigString/Views/BigSubstring.swift b/Sources/RopeModule/BigString/Views/BigSubstring.swift index a23cf55a..d47cdd3a 100644 --- a/Sources/RopeModule/BigString/Views/BigSubstring.swift +++ b/Sources/RopeModule/BigString/Views/BigSubstring.swift @@ -32,7 +32,7 @@ public struct BigSubstring: Sendable { // round substring bounds down to the nearest character. let start = base.index(roundingDown: bounds.lowerBound) let end = base.index(roundingDown: bounds.upperBound) - self._bounds = Range(uncheckedBounds: (start, end)) + self._bounds = unsafe Range(uncheckedBounds: (start, end)) } } @@ -272,7 +272,7 @@ extension BigSubstring { extension BigSubstring: RangeReplaceableCollection { public init() { let str = BigString() - let bounds = Range(uncheckedBounds: (str.startIndex, str.endIndex)) + let bounds = unsafe Range(uncheckedBounds: (str.startIndex, str.endIndex)) self.init(_unchecked: str, in: bounds) } diff --git a/Sources/RopeModule/Rope/Basics/Rope+Builder.swift b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift index 66deee50..0f601ac3 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+Builder.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Builder.swift @@ -361,10 +361,10 @@ extension Rope { guard c > 0 else { return } if c == 1 { if node.isLeaf { - let item = node.readLeaf { $0.children[slots.lowerBound] } + let item = unsafe node.readLeaf { unsafe $0.children[slots.lowerBound] } _insertBeforeTip(item) } else { - let child = node.readInner { $0.children[slots.lowerBound] } + let child = unsafe node.readInner { unsafe $0.children[slots.lowerBound] } _insertBeforeTip(child) } return @@ -380,10 +380,10 @@ extension Rope { guard c > 0 else { return } if c == 1 { if node.isLeaf { - let item = node.readLeaf { $0.children[slots.lowerBound] } + let item = unsafe node.readLeaf { unsafe $0.children[slots.lowerBound] } _insertAfterTip(item) } else { - let child = node.readInner { $0.children[slots.lowerBound] } + let child = unsafe node.readInner { unsafe $0.children[slots.lowerBound] } _insertAfterTip(child) } return diff --git a/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift b/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift index 5c47ac9a..29cb4980 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+Debugging.swift @@ -18,7 +18,7 @@ import InternalCollectionsUtilities extension Rope._UnmanagedLeaf: CustomStringConvertible { @usableFromInline internal var description: String { - _addressString(for: _ref.toOpaque()) + _addressString(for: unsafe _ref.toOpaque()) } } @@ -33,7 +33,9 @@ extension Rope._Node { @inlinable internal var nodeCount: Int { guard !isLeaf else { return 1 } - return readInner { $0.children.reduce(into: 1) { $0 += $1.nodeCount } } + return unsafe readInner { + unsafe $0.children.reduce(into: 1) { $0 += $1.nodeCount } + } } } @@ -75,20 +77,20 @@ extension Rope._Node { guard heightLimit > 0 else { return } if height > 0 { - readInner { - let c = $0.children + unsafe readInner { + let c = unsafe $0.children for slot in 0 ..< c.count { - c[slot].dump( + unsafe c[slot].dump( heightLimit: heightLimit - 1, firstPrefix: "\(restPrefix)\(slot): ", restPrefix: "\(restPrefix) ") } } } else { - readLeaf { - let c = $0.children + unsafe readLeaf { + let c = unsafe $0.children for slot in 0 ..< c.count { - print("\(restPrefix)\(slot): \(c[slot])") + print("\(restPrefix)\(slot): \(unsafe c[slot])") } } } diff --git a/Sources/RopeModule/Rope/Basics/Rope+_Node.swift b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift index f49b0e86..371425ed 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_Node.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_Node.swift @@ -33,8 +33,8 @@ extension Rope { internal init(leaf: _Storage<_Item>, summary: Summary? = nil) { self.object = leaf self.summary = .zero - self.summary = readLeaf { handle in - handle.children.reduce(into: .zero) { $0.add($1.summary) } + self.summary = unsafe readLeaf { handle in + unsafe handle.children.reduce(into: .zero) { $0.add($1.summary) } } } @@ -43,8 +43,8 @@ extension Rope { assert(inner.header.height > 0) self.object = inner self.summary = .zero - self.summary = readInner { handle in - handle.children.reduce(into: .zero) { $0.add($1.summary) } + self.summary = unsafe readInner { handle in + unsafe handle.children.reduce(into: .zero) { $0.add($1.summary) } } } } @@ -57,14 +57,14 @@ extension Rope._Node: @unchecked Sendable where Element: Sendable { extension Rope._Node { @inlinable internal var _headerPtr: UnsafePointer<_RopeStorageHeader> { - let p = _getUnsafePointerToStoredProperties(object) + let p = unsafe _getUnsafePointerToStoredProperties(object) .assumingMemoryBound(to: _RopeStorageHeader.self) - return .init(p) + return unsafe .init(p) } @inlinable internal var header: _RopeStorageHeader { - _headerPtr.pointee + unsafe _headerPtr.pointee } @inlinable @inline(__always) @@ -76,13 +76,13 @@ extension Rope._Node { @inlinable @inline(__always) internal var asLeaf: _Storage<_Item> { assert(height == 0) - return unsafeDowncast(object, to: _Storage<_Item>.self) + return unsafe unsafeDowncast(object, to: _Storage<_Item>.self) } @inlinable @inline(__always) internal var asInner: _Storage { assert(height > 0) - return unsafeDowncast(object, to: _Storage.self) + return unsafe unsafeDowncast(object, to: _Storage.self) } @inlinable @inline(__always) @@ -127,9 +127,9 @@ extension Rope._Node { var new = createInner(height: left.height + 1) new.summary = left.summary new.summary.add(right.summary) - new.updateInner { h in - h._appendChild(left) - h._appendChild(right) + unsafe new.updateInner { h in + unsafe h._appendChild(left) + unsafe h._appendChild(right) } return new } @@ -154,28 +154,29 @@ extension Rope._Node { @inlinable @inline(never) internal func copy() -> Self { if isLeaf { - return Self(leaf: readLeaf { $0.copy() }, summary: self.summary) + return Self(leaf: unsafe readLeaf { unsafe $0.copy() }, summary: self.summary) } - return Self(inner: readInner { $0.copy() }, summary: self.summary) + return Self(inner: unsafe readInner { unsafe $0.copy() }, summary: self.summary) } @inlinable @inline(never) internal func copy(slots: Range) -> Self { if isLeaf { - let (object, summary) = readLeaf { $0.copy(slots: slots) } + let (object, summary) = unsafe readLeaf { unsafe $0.copy(slots: slots) } return Self(leaf: object, summary: summary) } - let (object, summary) = readInner { $0.copy(slots: slots) } + let (object, summary) = unsafe readInner { unsafe $0.copy(slots: slots) } return Self(inner: object, summary: summary) } @inlinable @inline(__always) + @unsafe internal func readLeaf( _ body: (_UnsafeHandle<_Item>) -> R ) -> R { - asLeaf.withUnsafeMutablePointers { h, p in - let handle = _UnsafeHandle(isMutable: false, header: h, start: p) - return body(handle) + unsafe asLeaf.withUnsafeMutablePointers { h, p in + let handle = unsafe _UnsafeHandle(isMutable: false, header: h, start: p) + return unsafe body(handle) } } @@ -183,9 +184,9 @@ extension Rope._Node { internal mutating func updateLeaf( _ body: (_UnsafeHandle<_Item>) -> R ) -> R { - asLeaf.withUnsafeMutablePointers { h, p in - let handle = _UnsafeHandle(isMutable: true, header: h, start: p) - return body(handle) + unsafe asLeaf.withUnsafeMutablePointers { h, p in + let handle = unsafe _UnsafeHandle(isMutable: true, header: h, start: p) + return unsafe body(handle) } } @@ -193,9 +194,9 @@ extension Rope._Node { internal func readInner( _ body: (_UnsafeHandle) -> R ) -> R { - asInner.withUnsafeMutablePointers { h, p in - let handle = _UnsafeHandle(isMutable: false, header: h, start: p) - return body(handle) + unsafe asInner.withUnsafeMutablePointers { h, p in + let handle = unsafe _UnsafeHandle(isMutable: false, header: h, start: p) + return unsafe body(handle) } } @@ -203,9 +204,9 @@ extension Rope._Node { internal mutating func updateInner( _ body: (_UnsafeHandle) -> R ) -> R { - asInner.withUnsafeMutablePointers { h, p in - let handle = _UnsafeHandle(isMutable: true, header: h, start: p) - return body(handle) + unsafe asInner.withUnsafeMutablePointers { h, p in + let handle = unsafe _UnsafeHandle(isMutable: true, header: h, start: p) + return unsafe body(handle) } } } @@ -216,7 +217,7 @@ extension Rope._Node { assert(isLeaf) ensureUnique() self.summary.add(item.summary) - updateLeaf { $0._insertChild(item, at: slot) } + unsafe updateLeaf { unsafe $0._insertChild(item, at: slot) } } @inlinable @@ -225,7 +226,7 @@ extension Rope._Node { assert(self.height == node.height + 1) ensureUnique() self.summary.add(node.summary) - updateInner { $0._insertChild(node, at: slot) } + unsafe updateInner { unsafe $0._insertChild(node, at: slot) } } } @@ -235,7 +236,7 @@ extension Rope._Node { assert(isLeaf) ensureUnique() self.summary.add(item.summary) - updateLeaf { $0._appendChild(item) } + unsafe updateLeaf { unsafe $0._appendChild(item) } } @inlinable @@ -243,7 +244,7 @@ extension Rope._Node { assert(!isLeaf) ensureUnique() self.summary.add(node.summary) - updateInner { $0._appendChild(node) } + unsafe updateInner { unsafe $0._appendChild(node) } } } @@ -254,7 +255,7 @@ extension Rope._Node { ) -> (removed: _Item, delta: Summary) { assert(isLeaf) ensureUnique() - let item = updateLeaf { $0._removeChild(at: slot) } + let item = unsafe updateLeaf { unsafe $0._removeChild(at: slot) } let delta = item.summary self.summary.subtract(delta) return (item, delta) @@ -264,7 +265,7 @@ extension Rope._Node { internal mutating func _removeNode(at slot: Int) -> Self { assert(!isLeaf) ensureUnique() - let result = updateInner { $0._removeChild(at: slot) } + let result = unsafe updateInner { unsafe $0._removeChild(at: slot) } self.summary.subtract(result.summary) return result } @@ -346,15 +347,15 @@ extension Rope._Node { assert(self.height == other.height) let delta: Summary if isLeaf { - delta = self.updateLeaf { dst in - other.updateLeaf { src in - dst._appendChildren(movingFromPrefixOf: src, count: count) + delta = unsafe self.updateLeaf { dst in + unsafe other.updateLeaf { src in + unsafe dst._appendChildren(movingFromPrefixOf: src, count: count) } } } else { - delta = self.updateInner { dst in - other.updateInner { src in - dst._appendChildren(movingFromPrefixOf: src, count: count) + delta = unsafe self.updateInner { dst in + unsafe other.updateInner { src in + unsafe dst._appendChildren(movingFromPrefixOf: src, count: count) } } } @@ -369,15 +370,15 @@ extension Rope._Node { assert(self.height == other.height) let delta: Summary if isLeaf { - delta = self.updateLeaf { dst in - other.updateLeaf { src in - dst._prependChildren(movingFromSuffixOf: src, count: count) + delta = unsafe self.updateLeaf { dst in + unsafe other.updateLeaf { src in + unsafe dst._prependChildren(movingFromSuffixOf: src, count: count) } } } else { - delta = self.updateInner { dst in - other.updateInner { src in - dst._prependChildren(movingFromSuffixOf: src, count: count) + delta = unsafe self.updateInner { dst in + unsafe other.updateInner { src in + unsafe dst._prependChildren(movingFromSuffixOf: src, count: count) } } } @@ -395,7 +396,7 @@ extension Rope._Node { @inlinable internal var lastPath: _Path { var path = _Path(height: self.height) - _ = descendToLastItem(under: &path) + _ = unsafe descendToLastItem(under: &path) return path } @@ -407,7 +408,7 @@ extension Rope._Node { @inlinable internal func descendToFirstItem(under path: inout _Path) -> _UnmanagedLeaf { path.clear(below: self.height + 1) - return unmanagedLeaf(at: path) + return unsafe unmanagedLeaf(at: path) } @inlinable @@ -416,9 +417,11 @@ extension Rope._Node { let slot = self.childCount - 1 path[h] = slot if h > 0 { - return readInner { $0.children[slot].descendToLastItem(under: &path) } + return unsafe readInner { + unsafe $0.children[slot].descendToLastItem(under: &path) + } } - return asUnmanagedLeaf + return unsafe asUnmanagedLeaf } } @@ -427,7 +430,7 @@ extension Rope { internal func _unmanagedLeaf(at path: _Path) -> _UnmanagedLeaf? { assert(path.height == self._height) guard path < _endPath else { return nil } - return root.unmanagedLeaf(at: path) + return unsafe root.unmanagedLeaf(at: path) } } @@ -435,16 +438,16 @@ extension Rope._Node { @inlinable internal var asUnmanagedLeaf: _UnmanagedLeaf { assert(height == 0) - return _UnmanagedLeaf(unsafeDowncast(self.object, to: _Storage<_Item>.self)) + return unsafe _UnmanagedLeaf(unsafe unsafeDowncast(self.object, to: _Storage<_Item>.self)) } @inlinable internal func unmanagedLeaf(at path: _Path) -> _UnmanagedLeaf { if height == 0 { - return asUnmanagedLeaf + return unsafe asUnmanagedLeaf } let slot = path[height] - return readInner { $0.children[slot].unmanagedLeaf(at: path) } + return unsafe readInner { unsafe $0.children[slot].unmanagedLeaf(at: path) } } } @@ -459,12 +462,12 @@ extension Rope._Node { return false } i._path[h] = slot - i._leaf = asUnmanagedLeaf + unsafe i._leaf = asUnmanagedLeaf return true } - return readInner { - let c = $0.children - if c[slot].formSuccessor(of: &i) { + return unsafe readInner { + let c = unsafe $0.children + if unsafe c[slot].formSuccessor(of: &i) { return true } slot += 1 @@ -472,7 +475,7 @@ extension Rope._Node { return false } i._path[h] = slot - i._leaf = c[slot].descendToFirstItem(under: &i._path) + unsafe i._leaf = c[slot].descendToFirstItem(under: &i._path) return true } } @@ -486,12 +489,12 @@ extension Rope._Node { return false } i._path[h] = slot &- 1 - i._leaf = asUnmanagedLeaf + unsafe i._leaf = asUnmanagedLeaf return true } - return readInner { - let c = $0.children - if slot < c.count, c[slot].formPredecessor(of: &i) { + return unsafe readInner { + let c = unsafe $0.children + if slot < c.count, unsafe c[slot].formPredecessor(of: &i) { return true } guard slot > 0 else { @@ -499,7 +502,7 @@ extension Rope._Node { } slot -= 1 i._path[h] = slot - i._leaf = c[slot].descendToLastItem(under: &i._path) + unsafe i._leaf = c[slot].descendToLastItem(under: &i._path) return true } } @@ -513,9 +516,9 @@ extension Rope._Node { } _modify { assert(childCount > 0) - var state = _prepareModifyLast() + var state = unsafe _prepareModifyLast() defer { - _ = _finalizeModify(&state) + _ = unsafe _finalizeModify(&state) } yield &state.item } @@ -538,15 +541,15 @@ extension Rope._Node { let slot = path[h] precondition(slot < childCount, "Path out of bounds") guard h == 0 else { - return readInner { $0.children[slot][path] } + return unsafe readInner { unsafe $0.children[slot][path] } } - return readLeaf { $0.children[slot] } + return unsafe readLeaf { unsafe $0.children[slot] } } @inline(__always) _modify { - var state = _prepareModify(at: path) + var state = unsafe _prepareModify(at: path) defer { - _ = _finalizeModify(&state) + _ = unsafe _finalizeModify(&state) } yield &state.item } @@ -568,38 +571,50 @@ extension Rope._Node { } @inlinable + @unsafe internal mutating func _prepareModify(at path: _Path) -> _ModifyState { ensureUnique() let h = height let slot = path[h] precondition(slot < childCount, "Path out of bounds") guard h == 0 else { - return updateInner { $0.mutableChildren[slot]._prepareModify(at: path) } + return unsafe updateInner { + unsafe $0.mutableChildren[slot]._prepareModify(at: path) + } + } + let item = unsafe updateLeaf { + unsafe $0.mutableChildren.moveElement(from: slot) } - let item = updateLeaf { $0.mutableChildren.moveElement(from: slot) } return _ModifyState(path: path, item: item, summary: item.summary) } @inlinable + @unsafe internal mutating func _prepareModifyLast() -> _ModifyState { var path = _Path(height: height) - return _prepareModifyLast(&path) + return unsafe _prepareModifyLast(&path) } @inlinable + @unsafe internal mutating func _prepareModifyLast(_ path: inout _Path) -> _ModifyState { ensureUnique() let h = height let slot = self.childCount - 1 path[h] = slot guard h == 0 else { - return updateInner { $0.mutableChildren[slot]._prepareModifyLast(&path) } + return unsafe updateInner { + unsafe $0.mutableChildren[slot]._prepareModifyLast(&path) + } + } + let item = unsafe updateLeaf { + unsafe $0.mutableChildren.moveElement(from: slot) } - let item = updateLeaf { $0.mutableChildren.moveElement(from: slot) } return _ModifyState(path: path, item: item, summary: item.summary) } @inlinable + @unsafe internal mutating func _finalizeModify( _ state: inout _ModifyState ) -> (delta: Summary, leaf: _UnmanagedLeaf) { @@ -608,13 +623,17 @@ extension Rope._Node { let slot = state.path[h] assert(slot < childCount, "Path out of bounds") guard h == 0 else { - let r = updateInner { $0.mutableChildren[slot]._finalizeModify(&state) } - summary.add(r.delta) - return r + let r = unsafe updateInner { + unsafe $0.mutableChildren[slot]._finalizeModify(&state) + } + unsafe summary.add(r.delta) + return unsafe r } let delta = state.item.summary.subtracting(state.summary) - updateLeaf { $0.mutableChildren.initializeElement(at: slot, to: state.item) } + unsafe updateLeaf { + unsafe $0.mutableChildren.initializeElement(at: slot, to: state.item) + } summary.add(delta) - return (delta, asUnmanagedLeaf) + return (delta, unsafe asUnmanagedLeaf) } } diff --git a/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift b/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift index 024a4c33..4bc3dc32 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_Storage.swift @@ -13,6 +13,7 @@ @usableFromInline @frozen // Not really! This module isn't ABI stable. +@safe internal struct _RopeStorageHeader { @usableFromInline var _childCount: UInt16 @usableFromInline let height: UInt8 @@ -46,14 +47,14 @@ extension Rope { @inlinable internal static func create(height: UInt8) -> _Storage { let object = create(minimumCapacity: Summary.maxNodeSize) { _ in .init(height: height) } - return unsafeDowncast(object, to: _Storage.self) + return unsafe unsafeDowncast(object, to: _Storage.self) } @inlinable deinit { - withUnsafeMutablePointers { h, p in - p.deinitialize(count: h.pointee.childCount) - h.pointee._childCount = .max + unsafe withUnsafeMutablePointers { h, p in + unsafe p.deinitialize(count: h.pointee.childCount) + unsafe h.pointee._childCount = .max } } } diff --git a/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift b/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift index 1b8c4dde..e9d5748b 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_UnmanagedLeaf.swift @@ -14,6 +14,7 @@ extension Rope { @frozen // Not really! This module isn't ABI stable. @usableFromInline + @unsafe internal struct _UnmanagedLeaf { @usableFromInline internal typealias _Item = Rope._Item @usableFromInline internal typealias _Leaf = _Storage<_Item> @@ -23,15 +24,16 @@ extension Rope { @inlinable internal init(_ leaf: __shared _Leaf) { - _ref = .passUnretained(leaf) + unsafe _ref = .passUnretained(leaf) } } } extension Rope._UnmanagedLeaf: Equatable { @inlinable + @safe internal static func ==(left: Self, right: Self) -> Bool { - left._ref.toOpaque() == right._ref.toOpaque() + unsafe left._ref.toOpaque() == right._ref.toOpaque() } } @@ -40,10 +42,10 @@ extension Rope._UnmanagedLeaf { internal func read( body: (_UnsafeHandle<_Item>) -> R ) -> R { - _ref._withUnsafeGuaranteedRef { leaf in - leaf.withUnsafeMutablePointers { h, p in - let handle = _UnsafeHandle(isMutable: false, header: h, start: p) - return body(handle) + unsafe _ref._withUnsafeGuaranteedRef { leaf in + unsafe leaf.withUnsafeMutablePointers { h, p in + let handle = unsafe _UnsafeHandle(isMutable: false, header: h, start: p) + return unsafe body(handle) } } } diff --git a/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift b/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift index 4f54fb17..cc0b08b9 100644 --- a/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift +++ b/Sources/RopeModule/Rope/Basics/Rope+_UnsafeHandle.swift @@ -14,6 +14,7 @@ extension Rope { @usableFromInline @frozen // Not really! This module isn't ABI stable. + @unsafe internal struct _UnsafeHandle> { @usableFromInline internal typealias Summary = Rope.Summary @@ -24,6 +25,7 @@ extension Rope { internal let _start: UnsafeMutablePointer #if DEBUG @usableFromInline + @safe internal let _isMutable: Bool #endif @@ -33,14 +35,15 @@ extension Rope { header: UnsafeMutablePointer<_RopeStorageHeader>, start: UnsafeMutablePointer ) { - self._header = header - self._start = start + unsafe self._header = header + unsafe self._start = start #if DEBUG self._isMutable = isMutable #endif } @inlinable @inline(__always) + @safe internal func assertMutable() { #if DEBUG assert(_isMutable) @@ -51,58 +54,59 @@ extension Rope { extension Rope._UnsafeHandle { @inlinable @inline(__always) + @safe internal var capacity: Int { Summary.maxNodeSize } @inlinable @inline(__always) - internal var height: UInt8 { _header.pointee.height } + internal var height: UInt8 { unsafe _header.pointee.height } @inlinable internal var childCount: Int { - get { _header.pointee.childCount } + get { unsafe _header.pointee.childCount } nonmutating set { assertMutable() - _header.pointee.childCount = newValue + unsafe _header.pointee.childCount = newValue } } @inlinable internal var children: UnsafeBufferPointer { - UnsafeBufferPointer(start: _start, count: childCount) + unsafe UnsafeBufferPointer(start: _start, count: childCount) } @inlinable internal func child(at slot: Int) -> Child? { assert(slot >= 0) - guard slot < childCount else { return nil } - return (_start + slot).pointee + guard unsafe slot < childCount else { return nil } + return unsafe (_start + slot).pointee } @inlinable internal var mutableChildren: UnsafeMutableBufferPointer { assertMutable() - return UnsafeMutableBufferPointer(start: _start, count: childCount) + return unsafe UnsafeMutableBufferPointer(start: _start, count: childCount) } @inlinable internal func mutableChildPtr(at slot: Int) -> UnsafeMutablePointer { assertMutable() - assert(slot >= 0 && slot < childCount) - return _start + slot + assert(unsafe slot >= 0 && slot < childCount) + return unsafe _start + slot } @inlinable internal var mutableBuffer: UnsafeMutableBufferPointer { assertMutable() - return UnsafeMutableBufferPointer(start: _start, count: capacity) + return unsafe UnsafeMutableBufferPointer(start: _start, count: capacity) } @inlinable internal func copy() -> Rope._Storage { - let new = Rope._Storage.create(height: self.height) - let c = self.childCount + let new = unsafe Rope._Storage.create(height: self.height) + let c = unsafe self.childCount new.header.childCount = c - new.withUnsafeMutablePointerToElements { target in - target.initialize(from: self._start, count: c) + unsafe new.withUnsafeMutablePointerToElements { target in + unsafe target.initialize(from: self._start, count: c) } return new } @@ -111,13 +115,13 @@ extension Rope._UnsafeHandle { internal func copy( slots: Range ) -> (object: Rope._Storage, summary: Summary) { - assert(slots.lowerBound >= 0 && slots.upperBound <= childCount) - let object = Rope._Storage.create(height: self.height) + assert(unsafe slots.lowerBound >= 0 && slots.upperBound <= childCount) + let object = unsafe Rope._Storage.create(height: self.height) let c = slots.count - let summary = object.withUnsafeMutablePointers { h, p in - h.pointee.childCount = c - p.initialize(from: self._start + slots.lowerBound, count: slots.count) - return UnsafeBufferPointer(start: p, count: c)._sum() + let summary = unsafe object.withUnsafeMutablePointers { h, p in + unsafe h.pointee.childCount = c + unsafe p.initialize(from: self._start + slots.lowerBound, count: slots.count) + return unsafe UnsafeBufferPointer(start: p, count: c)._sum() } return (object, summary) } @@ -125,57 +129,57 @@ extension Rope._UnsafeHandle { @inlinable internal func _insertChild(_ child: __owned Child, at slot: Int) { assertMutable() - assert(childCount < capacity) - assert(slot >= 0 && slot <= childCount) - (_start + slot + 1).moveInitialize(from: _start + slot, count: childCount - slot) - (_start + slot).initialize(to: child) - childCount += 1 + assert(unsafe childCount < capacity) + assert(unsafe slot >= 0 && slot <= childCount) + unsafe (_start + slot + 1).moveInitialize(from: _start + slot, count: childCount - slot) + unsafe (_start + slot).initialize(to: child) + unsafe childCount += 1 } @inlinable internal func _appendChild(_ child: __owned Child) { assertMutable() - assert(childCount < capacity) - (_start + childCount).initialize(to: child) - childCount += 1 + assert(unsafe childCount < capacity) + unsafe (_start + childCount).initialize(to: child) + unsafe childCount += 1 } @inlinable internal func _removeChild(at slot: Int) -> Child { assertMutable() - assert(slot >= 0 && slot < childCount) - let result = (_start + slot).move() - (_start + slot).moveInitialize(from: _start + slot + 1, count: childCount - slot - 1) - childCount -= 1 + assert(unsafe slot >= 0 && slot < childCount) + let result = unsafe (_start + slot).move() + unsafe (_start + slot).moveInitialize(from: _start + slot + 1, count: childCount - slot - 1) + unsafe childCount -= 1 return result } @inlinable internal func _removePrefix(_ n: Int) -> Summary { assertMutable() - assert(n <= childCount) + assert(unsafe n <= childCount) var delta = Summary.zero - let c = mutableChildren + let c = unsafe mutableChildren for i in 0 ..< n { - let child = c.moveElement(from: i) + let child = unsafe c.moveElement(from: i) delta.add(child.summary) } - childCount -= n - _start.moveInitialize(from: _start + n, count: childCount) + unsafe childCount -= n + unsafe _start.moveInitialize(from: _start + n, count: childCount) return delta } @inlinable internal func _removeSuffix(_ n: Int) -> Summary { assertMutable() - assert(n <= childCount) + assert(unsafe n <= childCount) var delta = Summary.zero - let c = mutableChildren - for i in childCount - n ..< childCount { - let child = c.moveElement(from: i) + let c = unsafe mutableChildren + for i in unsafe childCount - n ..< childCount { + let child = unsafe c.moveElement(from: i) delta.add(child.summary) } - childCount -= n + unsafe childCount -= n return delta } @@ -185,16 +189,16 @@ extension Rope._UnsafeHandle { ) -> Summary { assertMutable() src.assertMutable() - assert(self.height == src.height) + assert(unsafe self.height == src.height) guard count > 0 else { return .zero } - assert(count >= 0 && count <= src.childCount) - assert(count <= capacity - self.childCount) - - (_start + childCount).moveInitialize(from: src._start, count: count) - src._start.moveInitialize(from: src._start + count, count: src.childCount - count) - childCount += count - src.childCount -= count - return children.suffix(count)._sum() + assert(unsafe count >= 0 && count <= src.childCount) + assert(unsafe count <= capacity - self.childCount) + + unsafe (_start + childCount).moveInitialize(from: src._start, count: count) + unsafe src._start.moveInitialize(from: src._start + count, count: src.childCount - count) + unsafe childCount += count + unsafe src.childCount -= count + return unsafe children.suffix(count)._sum() } @inlinable @@ -203,16 +207,16 @@ extension Rope._UnsafeHandle { ) -> Summary { assertMutable() src.assertMutable() - assert(self.height == src.height) + assert(unsafe self.height == src.height) guard count > 0 else { return .zero } - assert(count >= 0 && count <= src.childCount) - assert(count <= capacity - childCount) - - (_start + count).moveInitialize(from: _start, count: childCount) - _start.moveInitialize(from: src._start + src.childCount - count, count: count) - childCount += count - src.childCount -= count - return children.prefix(count)._sum() + assert(unsafe count >= 0 && count <= src.childCount) + assert(unsafe count <= capacity - childCount) + + unsafe (_start + count).moveInitialize(from: _start, count: childCount) + unsafe _start.moveInitialize(from: src._start + src.childCount - count, count: count) + unsafe childCount += count + unsafe src.childCount -= count + return unsafe children.prefix(count)._sum() } @inlinable @@ -220,11 +224,11 @@ extension Rope._UnsafeHandle { from start: Int, to end: Int, in metric: some RopeMetric ) -> Int { if start <= end { - return children[start ..< end].reduce(into: 0) { + return unsafe children[start ..< end].reduce(into: 0) { $0 += metric._nonnegativeSize(of: $1.summary) } } - return -children[end ..< start].reduce(into: 0) { + return unsafe -children[end ..< start].reduce(into: 0) { $0 += metric._nonnegativeSize(of: $1.summary) } } diff --git a/Sources/RopeModule/Rope/Basics/Rope.swift b/Sources/RopeModule/Rope/Basics/Rope.swift index 465573c5..13ea2fc9 100644 --- a/Sources/RopeModule/Rope/Basics/Rope.swift +++ b/Sources/RopeModule/Rope/Basics/Rope.swift @@ -15,6 +15,7 @@ /// The rope is augmented by the commutative group specified by `Element.Summary`, enabling /// quick lookup operations. @frozen // Not really! This module isn't ABI stable. +@safe public struct Rope { @usableFromInline internal var _root: _Node? @@ -36,7 +37,7 @@ public struct Rope { @inlinable internal var root: _Node { - @inline(__always) get { _root.unsafelyUnwrapped } + @inline(__always) get { unsafe _root.unsafelyUnwrapped } @inline(__always) _modify { yield &_root! } } diff --git a/Sources/RopeModule/Rope/Basics/_RopePath.swift b/Sources/RopeModule/Rope/Basics/_RopePath.swift index 48884efd..ed91b402 100644 --- a/Sources/RopeModule/Rope/Basics/_RopePath.swift +++ b/Sources/RopeModule/Rope/Basics/_RopePath.swift @@ -13,6 +13,7 @@ @usableFromInline @frozen // Not really! This module isn't ABI stable +@safe internal struct _RopePath { // ┌──────────────────────────────────┬────────┐ // │ b63:b8 │ b7:b0 │ diff --git a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift index fb237016..0aaad313 100644 --- a/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Collection.swift @@ -32,8 +32,8 @@ extension Rope { @inlinable public func grease(_ index: inout Index) { validate(index) - guard index._leaf == nil else { return } - index._leaf = _unmanagedLeaf(at: index._path) + guard unsafe index._leaf == nil else { return } + unsafe index._leaf = _unmanagedLeaf(at: index._path) } } @@ -69,12 +69,12 @@ extension Rope: BidirectionalCollection { @inlinable public var startIndex: Index { // Note: `leaf` is intentionally not set here, to speed up accessing this property. - return Index(version: _version, path: _startPath, leaf: nil) + return Index(version: _version, path: _startPath) } @inlinable public var endIndex: Index { - Index(version: _version, path: _endPath, leaf: nil) + Index(version: _version, path: _endPath) } @inlinable @@ -95,11 +95,11 @@ extension Rope: BidirectionalCollection { public func formIndex(after i: inout Index) { validate(i) precondition(i < endIndex, "Cannot advance above endIndex") - if let leaf = i._leaf { - let done = leaf.read { - let slot = i._path[$0.height] &+ 1 - guard slot < $0.childCount else { return false } - i._path[$0.height] = slot + if let leaf = unsafe i._leaf { + let done = unsafe leaf.read { + let slot = unsafe i._path[$0.height] &+ 1 + guard unsafe slot < $0.childCount else { return false } + unsafe i._path[$0.height] = slot return true } if done { return } @@ -113,11 +113,11 @@ extension Rope: BidirectionalCollection { public func formIndex(before i: inout Index) { validate(i) precondition(i > startIndex, "Cannot advance below startIndex") - if let leaf = i._leaf { - let done = leaf.read { - let slot = i._path[$0.height] + if let leaf = unsafe i._leaf { + let done = unsafe leaf.read { + let slot = unsafe i._path[$0.height] guard slot > 0 else { return false } - i._path[$0.height] = slot &- 1 + unsafe i._path[$0.height] = slot &- 1 return true } if done { return } @@ -130,9 +130,9 @@ extension Rope: BidirectionalCollection { public subscript(i: Index) -> Element { get { validate(i) - if let ref = i._leaf { - return ref.read { - $0.children[i._path[$0.height]].value + if let ref = unsafe i._leaf { + return unsafe ref.read { + unsafe $0.children[i._path[$0.height]].value } } return root[i._path].value @@ -154,11 +154,11 @@ extension Rope { by body: (inout Element) -> R ) -> R { validate(index) - var state = root._prepareModify(at: index._path) + var state = unsafe root._prepareModify(at: index._path) defer { _invalidateIndices() index._version = self._version - index._leaf = root._finalizeModify(&state).leaf + unsafe index._leaf = root._finalizeModify(&state).leaf } return body(&state.item.value) } @@ -225,13 +225,13 @@ extension Rope { validate(end) if start == end { return 0 } precondition(_root != nil, "Invalid index") - if start._leaf == end._leaf, let leaf = start._leaf { + if unsafe start._leaf == end._leaf, let leaf = unsafe start._leaf { // Fast path: both indices are pointing within the same leaf. - return leaf.read { - let h = $0.height + return unsafe leaf.read { + let h = unsafe $0.height let a = start._path[h] let b = end._path[h] - return $0.distance(from: a, to: b, in: metric) + return unsafe $0.distance(from: a, to: b, in: metric) } } if start < end { @@ -260,11 +260,11 @@ extension Rope._Node { return metric._nonnegativeSize(of: self.summary) } if height == 0 { - return readLeaf { $0.distance(from: 0, to: slot, in: metric) } + return unsafe readLeaf { unsafe $0.distance(from: 0, to: slot, in: metric) } } - return readInner { - var distance = $0.distance(from: 0, to: slot, in: metric) - distance += $0.children[slot].distanceFromStart(to: index, in: metric) + return unsafe readInner { + var distance = unsafe $0.distance(from: 0, to: slot, in: metric) + distance += unsafe $0.children[slot].distanceFromStart(to: index, in: metric) return distance } } @@ -294,16 +294,16 @@ extension Rope._Node { } if height == 0 { assert(a < b) - return readLeaf { $0.distance(from: a, to: b, in: metric) } + return unsafe readLeaf { unsafe $0.distance(from: a, to: b, in: metric) } } - return readInner { - let c = $0.children + return unsafe readInner { + let c = unsafe $0.children if a == b { - return c[a].distance(from: start, to: end, in: metric) + return unsafe c[a].distance(from: start, to: end, in: metric) } - var d = c[a].distanceToEnd(from: start, in: metric) - d += $0.distance(from: a + 1, to: b, in: metric) - d += c[b].distanceFromStart(to: end, in: metric) + var d = unsafe c[a].distanceToEnd(from: start, in: metric) + d += unsafe $0.distance(from: a + 1, to: b, in: metric) + d += unsafe c[b].distanceFromStart(to: end, in: metric) return d } } @@ -329,10 +329,10 @@ extension Rope { precondition(success, "Position out of bounds") return } - if let leaf = i._leaf { + if let leaf = unsafe i._leaf { // Fast path: move within a single leaf - let r = leaf.read { - $0._seekForwardInLeaf(from: &i._path, by: &distance, in: metric, preferEnd: preferEnd) + let r = unsafe leaf.read { + unsafe $0._seekForwardInLeaf(from: &i._path, by: &distance, in: metric, preferEnd: preferEnd) } if r { return } } @@ -366,12 +366,12 @@ extension Rope._UnsafeHandle { preferEnd: Bool ) -> Bool { assert(distance >= 0) - assert(height == 0) - let c = children + assert(unsafe height == 0) + let c = unsafe children var slot = path[0] defer { path[0] = slot } while slot < c.count { - let d = metric._nonnegativeSize(of: c[slot].summary) + let d = metric._nonnegativeSize(of: unsafe c[slot].summary) if preferEnd ? d >= distance : d > distance { return true } @@ -389,11 +389,11 @@ extension Rope._UnsafeHandle { preferEnd: Bool ) -> Bool { assert(distance >= 0) - assert(height == 0) - let c = children + assert(unsafe height == 0) + let c = unsafe children var slot = path[0] &- 1 while slot >= 0 { - let d = metric._nonnegativeSize(of: c[slot].summary) + let d = metric._nonnegativeSize(of: unsafe c[slot].summary) if preferEnd ? d > distance : d >= distance { path[0] = slot distance = d &- distance @@ -417,29 +417,30 @@ extension Rope._Node { assert(distance >= 0) if height == 0 { - let r = readLeaf { - $0._seekForwardInLeaf(from: &i._path, by: &distance, in: metric, preferEnd: preferEnd) + let r = unsafe readLeaf { + unsafe $0._seekForwardInLeaf( + from: &i._path, by: &distance, in: metric, preferEnd: preferEnd) } if r { - i._leaf = asUnmanagedLeaf + unsafe i._leaf = asUnmanagedLeaf } return r } - return readInner { + return unsafe readInner { var slot = i._path[height] precondition(slot < childCount, "Invalid index") - let c = $0.children - if c[slot].seekForward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) { + let c = unsafe $0.children + if unsafe c[slot].seekForward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) { return true } slot &+= 1 while slot < c.count { - let d = metric.size(of: c[slot].summary) + let d = metric.size(of: unsafe c[slot].summary) if preferEnd ? d >= distance : d > distance { - i._path[$0.height] = slot - i._clear(below: $0.height) - let success = c[slot].seekForward( + unsafe i._path[$0.height] = slot + unsafe i._clear(below: $0.height) + let success = unsafe c[slot].seekForward( from: &i, by: &distance, in: metric, preferEnd: preferEnd) precondition(success) return true @@ -461,27 +462,31 @@ extension Rope._Node { assert(distance >= 0) guard distance > 0 || preferEnd else { return true } if height == 0 { - return readLeaf { - $0._seekBackwardInLeaf(from: &i._path, by: &distance, in: metric, preferEnd: preferEnd) + return unsafe readLeaf { + unsafe $0._seekBackwardInLeaf( + from: &i._path, by: &distance, in: metric, preferEnd: preferEnd) } } - return readInner { + return unsafe readInner { var slot = i._path[height] precondition(slot <= childCount, "Invalid index") - let c = $0.children - if slot < childCount, - c[slot].seekBackward(from: &i, by: &distance, in: metric, preferEnd: preferEnd) { + let c = unsafe $0.children + if + slot < childCount, + unsafe c[slot].seekBackward( + from: &i, by: &distance, in: metric, preferEnd: preferEnd) + { return true } slot -= 1 while slot >= 0 { - let d = metric.size(of: c[slot].summary) + let d = metric.size(of: unsafe c[slot].summary) if preferEnd ? d > distance : d >= distance { - i._path[$0.height] = slot - i._clear(below: $0.height) + unsafe i._path[$0.height] = slot + unsafe i._clear(below: $0.height) distance = d - distance - let success = c[slot].seekForward( + let success = unsafe c[slot].seekForward( from: &i, by: &distance, in: metric, preferEnd: preferEnd) precondition(success) return true diff --git a/Sources/RopeModule/Rope/Conformances/Rope+Index.swift b/Sources/RopeModule/Rope/Conformances/Rope+Index.swift index 4b8447b4..993640a4 100644 --- a/Sources/RopeModule/Rope/Conformances/Rope+Index.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Index.swift @@ -13,6 +13,7 @@ extension Rope { @frozen // Not really! This module isn't ABI stable. + @safe public struct Index: @unchecked Sendable { @usableFromInline internal typealias Summary = Rope.Summary @usableFromInline internal typealias _Path = Rope._Path @@ -27,15 +28,27 @@ extension Rope { /// This must only be dereferenced while we own a tree with a matching /// version. @usableFromInline + @unsafe internal var _leaf: _UnmanagedLeaf? @inlinable + @safe + internal init( + version: _RopeVersion, path: _Path + ) { + self._version = version + self._path = path + unsafe self._leaf = nil + } + + @inlinable + @unsafe internal init( version: _RopeVersion, path: _Path, leaf: __shared _UnmanagedLeaf? ) { self._version = version self._path = path - self._leaf = leaf + unsafe self._leaf = leaf } } } @@ -43,7 +56,7 @@ extension Rope { extension Rope.Index { @inlinable internal static var _invalid: Self { - Self(version: _RopeVersion(0), path: _RopePath(_value: .max), leaf: nil) + Self(version: _RopeVersion(0), path: _RopePath(_value: .max)) } @inlinable diff --git a/Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift b/Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift index 30893223..11d63ceb 100644 --- a/Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift +++ b/Sources/RopeModule/Rope/Conformances/Rope+Sequence.swift @@ -23,6 +23,7 @@ extension Rope: Sequence { } @frozen // Not really! This module isn't ABI stable. + @safe public struct Iterator: IteratorProtocol { @usableFromInline internal let _rope: Rope @@ -40,8 +41,8 @@ extension Rope: Sequence { @inlinable public mutating func next() -> Element? { - guard let leaf = _index._leaf else { return nil } - let item = leaf.read { $0.children[_index._path[0]].value } + guard let leaf = unsafe _index._leaf else { return nil } + let item = unsafe leaf.read { unsafe $0.children[_index._path[0]].value } _rope.formIndex(after: &_index) return item } diff --git a/Sources/RopeModule/Rope/Operations/Rope+Append.swift b/Sources/RopeModule/Rope/Operations/Rope+Append.swift index 1beadba0..6a1b9b4a 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Append.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Append.swift @@ -35,23 +35,24 @@ extension Rope._Node { ensureUnique() if height > 0 { var summary = self.summary - let spawn = updateInner { - let p = $0.mutableChildPtr(at: $0.childCount - 1) - summary.subtract(p.pointee.summary) - let spawn = p.pointee.append(item) - summary.add(p.pointee.summary) + let spawn = unsafe updateInner { + let p = unsafe $0.mutableChildPtr(at: $0.childCount - 1) + summary.subtract(unsafe p.pointee.summary) + let spawn = unsafe p.pointee.append(item) + summary.add(unsafe p.pointee.summary) return spawn } self.summary = summary guard let spawn = spawn else { return nil } #if true // Compress existing nodes if possible. - updateInner { - let c = $0.mutableChildren - let s = c[c.count - 2].childCount + c[c.count - 1].childCount + unsafe updateInner { + let c = unsafe $0.mutableChildren + let s = unsafe c[c.count - 2].childCount + c[c.count - 1].childCount if s <= Summary.maxNodeSize { - Self.redistributeChildren(&c[c.count - 2], &c[c.count - 1], to: s) - let removed = $0._removeChild(at: c.count - 1) + unsafe Self.redistributeChildren( + &c[c.count - 2], &c[c.count - 1], to: s) + let removed = unsafe $0._removeChild(at: c.count - 1) assert(removed.childCount == 0) } } diff --git a/Sources/RopeModule/Rope/Operations/Rope+Extract.swift b/Sources/RopeModule/Rope/Operations/Rope+Extract.swift index 0c36d74c..2ed7476f 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Extract.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Extract.swift @@ -43,12 +43,13 @@ extension Rope._Node { guard start != end else { return } if self.isLeaf { - self.readLeaf { - let l = $0.findSlot(at: start, in: metric, preferEnd: false) - let u = $0.findSlot(from: l, offsetBy: end - start, in: metric, preferEnd: true) - let c = $0.children + unsafe self.readLeaf { + let l = unsafe $0.findSlot(at: start, in: metric, preferEnd: false) + let u = unsafe $0.findSlot( + from: l, offsetBy: end - start, in: metric, preferEnd: true) + let c = unsafe $0.children if l.slot == u.slot { - var item = c[l.slot] + var item = unsafe c[l.slot] let i = metric.index(at: l.remaining, in: item.value) var item2 = item.split(at: i) let j = metric.index( @@ -59,35 +60,36 @@ extension Rope._Node { return } assert(l.slot < u.slot) - var left = c[l.slot] + var left = unsafe c[l.slot] left = left.split(at: metric.index(at: l.remaining, in: left.value)) builder._insertBeforeTip(left) for i in l.slot + 1 ..< u.slot { - builder._insertBeforeTip(c[i]) + unsafe builder._insertBeforeTip(c[i]) } - var right = c[u.slot] + var right = unsafe c[u.slot] _ = right.split(at: metric.index(at: u.remaining, in: right.value)) builder._insertBeforeTip(right) } return } - self.readInner { - let l = $0.findSlot(at: start, in: metric, preferEnd: false) - let u = $0.findSlot(from: l, offsetBy: end - start, in: metric, preferEnd: true) - let c = $0.children + unsafe self.readInner { + let l = unsafe $0.findSlot(at: start, in: metric, preferEnd: false) + let u = unsafe $0.findSlot(from: l, offsetBy: end - start, in: metric, preferEnd: true) + let c = unsafe $0.children if l.slot == u.slot { - c[l.slot].extract( + unsafe c[l.slot].extract( from: l.remaining, to: u.remaining, in: metric, into: &builder) return } assert(l.slot < u.slot) - let lsize = metric._nonnegativeSize(of: c[l.slot].summary) - c[l.slot].extract(from: l.remaining, to: lsize, in: metric, into: &builder) + let lsize = metric._nonnegativeSize(of: unsafe c[l.slot].summary) + unsafe c[l.slot].extract( + from: l.remaining, to: lsize, in: metric, into: &builder) for i in l.slot + 1 ..< u.slot { - builder._insertBeforeTip(c[i]) + builder._insertBeforeTip(unsafe c[i]) } - c[u.slot].extract(from: 0, to: u.remaining, in: metric, into: &builder) + unsafe c[u.slot].extract(from: 0, to: u.remaining, in: metric, into: &builder) } } } diff --git a/Sources/RopeModule/Rope/Operations/Rope+Find.swift b/Sources/RopeModule/Rope/Operations/Rope+Find.swift index 1bc8df2f..67a5fe3e 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Find.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Find.swift @@ -27,16 +27,18 @@ extension Rope { var node = root var path = _Path(height: node.height) while node.height > 0 { - node = node.readInner { - let r = $0.findSlot(at: position, in: metric, preferEnd: preferEnd) + node = unsafe node.readInner { + let r = unsafe $0.findSlot(at: position, in: metric, preferEnd: preferEnd) position = r.remaining - path[$0.height] = r.slot - return $0.children[r.slot] + path[unsafe $0.height] = r.slot + return unsafe $0.children[r.slot] } } - let r = node.readLeaf { $0.findSlot(at: position, in: metric, preferEnd: preferEnd) } + let r = unsafe node.readLeaf { + unsafe $0.findSlot(at: position, in: metric, preferEnd: preferEnd) + } path[0] = r.slot - let index = Index(version: _version, path: path, leaf: node.asUnmanagedLeaf) + let index = unsafe Index(version: _version, path: path, leaf: node.asUnmanagedLeaf) return (index, r.remaining) } } @@ -50,8 +52,8 @@ extension Rope._UnsafeHandle { ) -> (slot: Int, remaining: Int) { var remaining = position var size = 0 - for slot in 0 ..< childCount { - size = metric.size(of: children[slot].summary) + for slot in unsafe 0 ..< childCount { + size = metric.size(of: unsafe children[slot].summary) let next = remaining - size let adjustment = (preferEnd ? 0 : 1) if next + adjustment <= 0 { @@ -60,7 +62,7 @@ extension Rope._UnsafeHandle { remaining = next } precondition(remaining == 0, "Position out of bounds") - return preferEnd ? (childCount - 1, remaining + size) : (childCount, 0) + return unsafe preferEnd ? (childCount - 1, remaining + size) : (childCount, 0) } @inlinable @@ -70,19 +72,19 @@ extension Rope._UnsafeHandle { in metric: some RopeMetric, preferEnd: Bool = true ) -> (slot: Int, remaining: Int) { - assert(p.slot >= 0 && p.slot < childCount) - assert(p.remaining >= 0 && p.remaining <= metric.size(of: children[p.slot].summary)) + assert(unsafe p.slot >= 0 && p.slot < childCount) + assert(p.remaining >= 0 && p.remaining <= metric.size(of: unsafe children[p.slot].summary)) assert(distance >= 0) let adjustment = (preferEnd ? 0 : 1) var d = p.remaining + distance var slot = p.slot - while slot < childCount { - let size = metric.size(of: children[slot].summary) + while unsafe slot < childCount { + let size = metric.size(of: unsafe children[slot].summary) if d + adjustment <= size { break } d -= size slot += 1 } - assert(slot < childCount || d == 0) + assert(unsafe slot < childCount || d == 0) return (slot, d) } } diff --git a/Sources/RopeModule/Rope/Operations/Rope+ForEachWhile.swift b/Sources/RopeModule/Rope/Operations/Rope+ForEachWhile.swift index 92ad48b0..3f32b832 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+ForEachWhile.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+ForEachWhile.swift @@ -40,18 +40,18 @@ extension Rope._Node { _ body: (Element) -> Bool ) -> Bool { if isLeaf { - return readLeaf { - let c = $0.children + return unsafe readLeaf { + let c = unsafe $0.children for i in 0 ..< c.count { - guard body(c[i].value) else { return false } + guard unsafe body(c[i].value) else { return false } } return true } } - return readInner { - let c = $0.children + return unsafe readInner { + let c = unsafe $0.children for i in 0 ..< c.count { - guard c[i].forEachWhile(body) else { return false } + guard unsafe c[i].forEachWhile(body) else { return false } } return true } @@ -64,26 +64,27 @@ extension Rope._Node { _ body: (Element, Element.Index?) -> Bool ) -> Bool { if isLeaf { - return readLeaf { - let c = $0.children - var (slot, rem) = $0.findSlot(at: position, in: metric, preferEnd: false) - let i = metric.index(at: rem, in: c[slot].value) - if !body(c[slot].value, i) { return false } + return unsafe readLeaf { + let c = unsafe $0.children + var (slot, rem) = unsafe $0.findSlot( + at: position, in: metric, preferEnd: false) + let i = metric.index(at: rem, in: unsafe c[slot].value) + if !body(unsafe c[slot].value, i) { return false } slot += 1 while slot < c.count { - if !body(c[slot].value, nil) { return false } + if !body(unsafe c[slot].value, nil) { return false } slot += 1 } return true } } - return readInner { - let c = $0.children - var (slot, rem) = $0.findSlot(at: position, in: metric, preferEnd: false) - if !c[slot].forEachWhile(from: rem, in: metric, body) { return false } + return unsafe readInner { + let c = unsafe $0.children + var (slot, rem) = unsafe $0.findSlot(at: position, in: metric, preferEnd: false) + if unsafe !c[slot].forEachWhile(from: rem, in: metric, body) { return false } slot += 1 while slot < c.count { - if !c[slot].forEachWhile({ body($0, nil) }) { return false } + if unsafe !c[slot].forEachWhile({ body($0, nil) }) { return false } slot += 1 } return true diff --git a/Sources/RopeModule/Rope/Operations/Rope+Insert.swift b/Sources/RopeModule/Rope/Operations/Rope+Insert.swift index 7437762f..c7e189a5 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Insert.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Insert.swift @@ -89,13 +89,13 @@ extension Rope._Node { ) -> Self? { ensureUnique() if height > 0 { - let (slot, remaining) = readInner { - $0.findSlot(at: position, in: metric, preferEnd: false) + let (slot, remaining) = unsafe readInner { + unsafe $0.findSlot(at: position, in: metric, preferEnd: false) } return _innerInsert(at: slot) { $0.insert(item, at: remaining, in: metric) } } - let (slot, remaining) = readLeaf { - $0.findSlot(at: position, in: metric, preferEnd: false) + let (slot, remaining) = unsafe readLeaf { + unsafe $0.findSlot(at: position, in: metric, preferEnd: false) } precondition(remaining == 0, "Inserted element doesn't fall on an element boundary") return _leafInsert(item, at: slot) @@ -110,11 +110,11 @@ extension Rope._Node { ) -> Self? { assert(slot < childCount) var summary = self.summary - let spawn = updateInner { - let p = $0.mutableChildPtr(at: slot) - summary.subtract(p.pointee.summary) - let spawn = body(&p.pointee) - summary.add(p.pointee.summary) + let spawn = unsafe updateInner { + let p = unsafe $0.mutableChildPtr(at: slot) + unsafe summary.subtract(p.pointee.summary) + let spawn = unsafe body(&p.pointee) + unsafe summary.add(p.pointee.summary) return spawn } self.summary = summary @@ -131,24 +131,24 @@ extension Rope._Node { #if true // Compress existing nodes if possible. if slot > 0 { // Try merging remainder into previous child. - updateInner { - let c = $0.mutableChildren - let s = c[slot - 1].childCount + c[slot].childCount + unsafe updateInner { + let c = unsafe $0.mutableChildren + let s = unsafe c[slot - 1].childCount + c[slot].childCount guard s <= Summary.maxNodeSize else { return } - Self.redistributeChildren(&c[slot - 1], &c[slot], to: s) - let removed = $0._removeChild(at: slot) + unsafe Self.redistributeChildren(&c[slot - 1], &c[slot], to: s) + let removed = unsafe $0._removeChild(at: slot) assert(removed.childCount == 0) nextSlot -= 1 } } if nextSlot < childCount { // Try merging new spawn into subsequent child. - let merged: Summary? = updateInner { - let c = $0.mutableChildren - let s = spawn.childCount + c[nextSlot].childCount + let merged: Summary? = unsafe updateInner { + let c = unsafe $0.mutableChildren + let s = unsafe spawn.childCount + c[nextSlot].childCount guard s <= Summary.maxNodeSize else { return nil } let summary = spawn.summary - Self.redistributeChildren(&spawn, &c[nextSlot], to: 0) + unsafe Self.redistributeChildren(&spawn, &c[nextSlot], to: 0) assert(spawn.childCount == 0) return summary } @@ -203,18 +203,18 @@ extension Rope._Node { _ item: inout _Item, at slot: Int ) -> Bool { assert(item.isUndersized) - let r = updateLeaf { (h) -> (merged: Bool, delta: Summary) in + let r = unsafe updateLeaf { (h) -> (merged: Bool, delta: Summary) in if slot > 0 { - let p = h.mutableChildPtr(at: slot - 1) - let sum = p.pointee.summary - let merged = p.pointee.rebalance(nextNeighbor: &item) - let delta = p.pointee.summary.subtracting(sum) + let p = unsafe h.mutableChildPtr(at: slot - 1) + let sum = unsafe p.pointee.summary + let merged = unsafe p.pointee.rebalance(nextNeighbor: &item) + let delta = unsafe p.pointee.summary.subtracting(sum) return (merged, delta) } - let p = h.mutableChildPtr(at: slot) - let sum = p.pointee.summary - let merged = p.pointee.rebalance(prevNeighbor: &item) - let delta = p.pointee.summary.subtracting(sum) + let p = unsafe h.mutableChildPtr(at: slot) + let sum = unsafe p.pointee.summary + let merged = unsafe p.pointee.rebalance(prevNeighbor: &item) + let delta = unsafe p.pointee.summary.subtracting(sum) return (merged, delta) } self.summary.add(r.delta) diff --git a/Sources/RopeModule/Rope/Operations/Rope+Join.swift b/Sources/RopeModule/Rope/Operations/Rope+Join.swift index 28f04e76..73b98291 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Join.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Join.swift @@ -77,8 +77,8 @@ extension Rope._Node { return (scion, d.subtracting(scion.summary)) } - var (remainder, delta) = self.updateInner { h in - h.mutableChildren[0]._graftFront(&scion) + var (remainder, delta) = unsafe self.updateInner { h in + unsafe h.mutableChildren[0]._graftFront(&scion) } self.summary.add(delta) guard let remainder = remainder else { return (nil, delta) } @@ -113,8 +113,8 @@ extension Rope._Node { return (emptied ? nil : scion, self.summary.subtracting(origSum)) } - var (remainder, delta) = self.updateInner { h in - h.mutableChildren[h.childCount - 1]._graftBack(&scion) + var (remainder, delta) = unsafe self.updateInner { h in + unsafe h.mutableChildren[h.childCount - 1]._graftBack(&scion) } self.summary.add(delta) guard let remainder = remainder else { return (nil, delta) } diff --git a/Sources/RopeModule/Rope/Operations/Rope+MutatingForEach.swift b/Sources/RopeModule/Rope/Operations/Rope+MutatingForEach.swift index ac0adf98..922848f5 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+MutatingForEach.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+MutatingForEach.swift @@ -66,28 +66,28 @@ extension Rope._Node { var delta = Summary.zero defer { self.summary.add(delta) } if h > 0 { - let r = updateInner { - let c = $0.mutableChildren + let r = unsafe updateInner { + let c = unsafe $0.mutableChildren while slot < c.count { - let (r, d) = c[slot].mutatingForEach(from: &index, body: body) + let (r, d) = unsafe c[slot].mutatingForEach(from: &index, body: body) delta.add(d) guard r else { return false } slot += 1 index._path.clear(below: h) index._path[h] = slot } - index._leaf = nil + unsafe index._leaf = nil return true } return (r, delta) } - index._leaf = asUnmanagedLeaf - let r = updateLeaf { - let c = $0.mutableChildren + unsafe index._leaf = asUnmanagedLeaf + let r = unsafe updateLeaf { + let c = unsafe $0.mutableChildren while slot < c.count { - let sum = c[slot].summary - let r = body(&c[slot].value) - delta.add(c[slot].summary.subtracting(sum)) + let sum = unsafe c[slot].summary + let r = unsafe body(&c[slot].value) + delta.add(unsafe c[slot].summary.subtracting(sum)) guard r else { return false } slot += 1 index._path[h] = slot diff --git a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift index 734ee45e..53d2aea6 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Remove.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Remove.swift @@ -24,7 +24,7 @@ extension Rope { @discardableResult public mutating func remove(at index: inout Index) -> Element { let (old, path) = _remove(at: index) - index = Index(version: _version, path: path, leaf: _unmanagedLeaf(at: path)) + index = unsafe Index(version: _version, path: path, leaf: _unmanagedLeaf(at: path)) return old } @@ -38,7 +38,7 @@ extension Rope { _root = nil assert(r.pathIsAtEnd) } else if root.childCount == 1, root.height > 0 { - root = root.readInner { $0.children.first! } + root = unsafe root.readInner { unsafe $0.children.first! } path.popRoot() } _invalidateIndices() @@ -59,7 +59,7 @@ extension Rope._Node { let r = _removeItem(at: slot) return (r.removed, r.delta, self.isUndersized, slot == childCount) } - let r = updateInner { $0.mutableChildren[slot].remove(at: &path) } + let r = unsafe updateInner { unsafe $0.mutableChildren[slot].remove(at: &path) } self.summary.subtract(r.delta) var isAtEnd = r.pathIsAtEnd if r.needsFixing { @@ -88,12 +88,12 @@ extension Rope { if root.isEmpty { _root = nil } else if root.childCount == 1, root.height > 0 { - root = root.readInner { $0.children.first! } + root = unsafe root.readInner { unsafe $0.children.first! } } if r.pathIsAtEnd { return (r.removed.value, endIndex) } - let i = Index(version: _version, path: path, leaf: nil) + let i = Index(version: _version, path: path) return (r.removed.value, i) } } @@ -117,18 +117,18 @@ extension Rope._Node { ensureUnique() let h = height guard h > 0 else { - let (slot, remaining) = readLeaf { - $0.findSlot(at: position, in: metric, preferEnd: false) + let (slot, remaining) = unsafe readLeaf { + unsafe $0.findSlot(at: position, in: metric, preferEnd: false) } precondition(remaining == 0, "Element to be removed doesn't fall on an element boundary") path[h] = slot let r = _removeItem(at: slot) return (r.removed, r.delta, self.isUndersized, slot == childCount) } - let r = updateInner { - let (slot, remaining) = $0.findSlot(at: position, in: metric, preferEnd: false) + let r = unsafe updateInner { + let (slot, remaining) = unsafe $0.findSlot(at: position, in: metric, preferEnd: false) path[h] = slot - return $0.mutableChildren[slot].remove(at: remaining, in: metric, initializing: &path) + return unsafe $0.mutableChildren[slot].remove(at: remaining, in: metric, initializing: &path) } self.summary.subtract(r.delta) var isAtEnd = r.pathIsAtEnd @@ -152,21 +152,21 @@ extension Rope._Node { @discardableResult internal mutating func fixDeficiency(on path: inout _Path) -> Bool { assert(isUnique()) - return updateInner { - let c = $0.mutableChildren - let h = $0.height + return unsafe updateInner { + let c = unsafe $0.mutableChildren + let h = unsafe $0.height let slot = path[h] - assert(c[slot].isUndersized) + assert(unsafe c[slot].isUndersized) guard c.count > 1 else { return true } let prev = slot - 1 let prevSum: Int if prev >= 0 { - let prevCount = c[prev].childCount - prevSum = prevCount + c[slot].childCount + let prevCount = unsafe c[prev].childCount + prevSum = unsafe prevCount + c[slot].childCount if prevSum <= Summary.maxNodeSize { - Self.redistributeChildren(&c[prev], &c[slot], to: prevSum) - assert(c[slot].isEmpty) - _ = $0._removeChild(at: slot) + unsafe Self.redistributeChildren(&c[prev], &c[slot], to: prevSum) + assert(unsafe c[slot].isEmpty) + _ = unsafe $0._removeChild(at: slot) path[h] = prev path[h - 1] += prevCount return true @@ -178,12 +178,12 @@ extension Rope._Node { let next = slot + 1 let nextSum: Int if next < c.count { - let nextCount = c[next].childCount - nextSum = c[slot].childCount + nextCount + let nextCount = unsafe c[next].childCount + nextSum = unsafe c[slot].childCount + nextCount if nextSum <= Summary.maxNodeSize { - Self.redistributeChildren(&c[slot], &c[next], to: nextSum) - assert(c[next].isEmpty) - _ = $0._removeChild(at: next) + unsafe Self.redistributeChildren(&c[slot], &c[next], to: nextSum) + assert(unsafe c[next].isEmpty) + _ = unsafe $0._removeChild(at: next) // `path` doesn't need updating. return false } @@ -192,20 +192,20 @@ extension Rope._Node { } if prev >= 0 { - assert(c[prev].childCount > Summary.minNodeSize) - let origCount = c[slot].childCount - Self.redistributeChildren(&c[prev], &c[slot], to: prevSum / 2) - path[h - 1] += c[slot].childCount - origCount - assert(!c[prev].isUndersized) - assert(!c[slot].isUndersized) + assert(unsafe c[prev].childCount > Summary.minNodeSize) + let origCount = unsafe c[slot].childCount + unsafe Self.redistributeChildren(&c[prev], &c[slot], to: prevSum / 2) + path[h - 1] += unsafe c[slot].childCount - origCount + assert(unsafe !c[prev].isUndersized) + assert(unsafe !c[slot].isUndersized) return true } assert(next < c.count) - assert(c[next].childCount > Summary.minNodeSize) - Self.redistributeChildren(&c[slot], &c[next], to: nextSum / 2) + assert(unsafe c[next].childCount > Summary.minNodeSize) + unsafe Self.redistributeChildren(&c[slot], &c[next], to: nextSum / 2) // `path` doesn't need updating. - assert(!c[slot].isUndersized) - assert(!c[next].isUndersized) + assert(unsafe !c[slot].isUndersized) + assert(unsafe !c[next].isUndersized) return false } } diff --git a/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift b/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift index d3b57575..0438e4eb 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+RemoveSubrange.swift @@ -63,9 +63,9 @@ extension Rope { var lower = bounds.lowerBound var upper = bounds.upperBound while !node.isLeaf { - let (l, u) = node.readInner { - let l = $0.findSlot(at: lower, in: metric, preferEnd: false) - let u = $0.findSlot(from: l, offsetBy: upper - lower, in: metric, preferEnd: true) + let (l, u) = unsafe node.readInner { + let l = unsafe $0.findSlot(at: lower, in: metric, preferEnd: false) + let u = unsafe $0.findSlot(from: l, offsetBy: upper - lower, in: metric, preferEnd: true) return (l, u) } if l.slot < u.slot { @@ -78,9 +78,9 @@ extension Rope { upper = u.remaining } - let (l, u) = node.readLeaf { - let l = $0.findSlot(at: lower, in: metric, preferEnd: false) - let u = $0.findSlot(from: l, offsetBy: bounds.count, in: metric, preferEnd: true) + let (l, u) = unsafe node.readLeaf { + let l = unsafe $0.findSlot(at: lower, in: metric, preferEnd: false) + let u = unsafe $0.findSlot(from: l, offsetBy: bounds.count, in: metric, preferEnd: true) return (l, u) } if l.slot < u.slot { @@ -117,7 +117,9 @@ extension Rope._Node { guard isLeaf else { // Extract children on boundaries. - let (lower, upper) = readInner { ($0.children[start.slot], $0.children[end.slot]) } + let (lower, upper) = unsafe readInner { + unsafe ($0.children[start.slot], $0.children[end.slot]) + } // Descend a lever lower. lower.removeSuffix(from: start.remaining, in: metric, into: &builder) @@ -125,7 +127,9 @@ extension Rope._Node { return } // Extract items on boundaries. - var (lower, upper) = readLeaf { ($0.children[start.slot], $0.children[end.slot]) } + var (lower, upper) = unsafe readLeaf { + unsafe ($0.children[start.slot], $0.children[end.slot]) + } let i1 = metric.index(at: start.remaining, in: lower.value) let i2 = metric.index(at: end.remaining, in: upper.value) @@ -152,11 +156,13 @@ extension Rope._Node { guard !node.isLeaf else { break } - let r = node.readInner { $0.findSlot(at: position, in: metric) } + let r = unsafe node.readInner { unsafe $0.findSlot(at: position, in: metric) } position = r.remaining node._innerRemoveSuffix(descending: r.slot, into: &builder) } - let r = node.readLeaf { $0.findSlot(at: position, in: metric, preferEnd: false) } + let r = unsafe node.readLeaf { + unsafe $0.findSlot(at: position, in: metric, preferEnd: false) + } var item = node._leafRemoveSuffix(returning: r.slot, into: &builder) let i = metric.index(at: r.remaining, in: item.value) _ = item.split(at: i) @@ -180,11 +186,11 @@ extension Rope._Node { guard !node.isLeaf else { break } - let r = node.readInner { $0.findSlot(at: position, in: metric) } + let r = unsafe node.readInner { unsafe $0.findSlot(at: position, in: metric) } position = r.remaining node._innerRemovePrefix(descending: r.slot, into: &builder) } - let r = node.readLeaf { $0.findSlot(at: position, in: metric) } + let r = unsafe node.readLeaf { unsafe $0.findSlot(at: position, in: metric) } var item = node._leafRemovePrefix(returning: r.slot, into: &builder) let i = metric.index(at: r.remaining, in: item.value) builder._insertAfterTip(item.split(at: i)) @@ -199,13 +205,13 @@ extension Rope._Node { assert(slot >= 0 && slot <= childCount) if slot == 0 { - self = readInner { $0.children[0] } + self = unsafe readInner { unsafe $0.children[0] } return } if slot == 1 { - let (remaining, new) = readInner { - let c = $0.children - return (c[0], c[1]) + let (remaining, new) = unsafe readInner { + let c = unsafe $0.children + return unsafe (c[0], c[1]) } builder._insertBeforeTip(remaining) self = new @@ -214,7 +220,9 @@ extension Rope._Node { ensureUnique() if slot < childCount - 1 { - let delta = updateInner { $0._removeSuffix($0.childCount - slot - 1) } + let delta = unsafe updateInner { + unsafe $0._removeSuffix($0.childCount - slot - 1) + } self.summary.subtract(delta) } var n = _removeNode(at: slot) @@ -232,12 +240,12 @@ extension Rope._Node { assert(slot >= 0 && slot < childCount) if slot == 0 { - return readLeaf { $0.children[0] } + return unsafe readLeaf { unsafe $0.children[0] } } if slot == 1 { - let (remaining, new) = readLeaf { - let c = $0.children - return (c[0], c[1]) + let (remaining, new) = unsafe readLeaf { + let c = unsafe $0.children + return unsafe (c[0], c[1]) } builder._insertBeforeTip(remaining) return new @@ -246,7 +254,9 @@ extension Rope._Node { var n = self n.ensureUnique() if slot < n.childCount - 1 { - let delta = n.updateLeaf { $0._removeSuffix($0.childCount - slot - 1) } + let delta = unsafe n.updateLeaf { + unsafe $0._removeSuffix($0.childCount - slot - 1) + } n.summary.subtract(delta) } let item = n._removeItem(at: slot).removed @@ -263,13 +273,13 @@ extension Rope._Node { assert(slot >= 0 && slot < childCount) if slot == childCount - 1 { - self = readInner { $0.children[$0.childCount - 1] } + self = unsafe readInner { unsafe $0.children[$0.childCount - 1] } return } if slot == childCount - 2 { - let (new, remaining) = readInner { - let c = $0.children - return (c[$0.childCount - 2], c[$0.childCount - 1]) + let (new, remaining) = unsafe readInner { + let c = unsafe $0.children + return unsafe (c[$0.childCount - 2], c[$0.childCount - 1]) } builder._insertAfterTip(remaining) self = new @@ -277,9 +287,9 @@ extension Rope._Node { } ensureUnique() - var (delta, n) = updateInner { - let n = $0.children[slot] - let delta = $0._removePrefix(slot + 1) + var (delta, n) = unsafe updateInner { + let n = unsafe $0.children[slot] + let delta = unsafe $0._removePrefix(slot + 1) return (delta, n) } self.summary.subtract(delta) @@ -297,12 +307,12 @@ extension Rope._Node { assert(slot >= 0 && slot <= childCount) if slot == childCount - 1 { - return readLeaf { $0.children[$0.childCount - 1] } + return unsafe readLeaf { unsafe $0.children[$0.childCount - 1] } } if slot == childCount - 2 { - let (new, remaining) = readLeaf { - let c = $0.children - return (c[$0.childCount - 2], c[$0.childCount - 1]) + let (new, remaining) = unsafe readLeaf { + let c = unsafe $0.children + return unsafe (c[$0.childCount - 2], c[$0.childCount - 1]) } builder._insertAfterTip(remaining) return new @@ -310,9 +320,9 @@ extension Rope._Node { var n = self n.ensureUnique() - let (delta, item) = n.updateLeaf { - let n = $0.children[slot] - let delta = $0._removePrefix(slot + 1) + let (delta, item) = unsafe n.updateLeaf { + let n = unsafe $0.children[slot] + let delta = unsafe $0._removePrefix(slot + 1) return (delta, n) } n.summary.subtract(delta) diff --git a/Sources/RopeModule/Rope/Operations/Rope+Split.swift b/Sources/RopeModule/Rope/Operations/Rope+Split.swift index f17ab097..c071788f 100644 --- a/Sources/RopeModule/Rope/Operations/Rope+Split.swift +++ b/Sources/RopeModule/Rope/Operations/Rope+Split.swift @@ -28,12 +28,12 @@ extension Rope { var node = root _root = nil while !node.isLeaf { - let r = node.readInner { $0.findSlot(at: position, in: metric) } + let r = unsafe node.readInner { unsafe $0.findSlot(at: position, in: metric) } position = r.remaining node._innerSplit(at: r.slot, into: &builder) } - let r = node.readLeaf { $0.findSlot(at: position, in: metric) } + let r = unsafe node.readLeaf { unsafe $0.findSlot(at: position, in: metric) } var item = node._leafSplit(at: r.slot, into: &builder) let index = metric.index(at: r.remaining, in: item.value) let suffix = item.split(at: index) diff --git a/Sources/RopeModule/Utilities/String Utilities.swift b/Sources/RopeModule/Utilities/String Utilities.swift index 4f53b19e..2ba1ae40 100644 --- a/Sources/RopeModule/Utilities/String Utilities.swift +++ b/Sources/RopeModule/Utilities/String Utilities.swift @@ -116,16 +116,16 @@ extension String { @available(SwiftStdlib 6.2, *) internal mutating func append(copying utf8Span: UTF8Span) { self = String(unsafeUninitializedCapacity: utf8.count + utf8Span.count) { - var buffer = $0 + var buffer = unsafe $0 let stringInitialized = withUTF8 { - buffer.initialize(fromContentsOf: $0) + unsafe buffer.initialize(fromContentsOf: $0) } - buffer = buffer.extracting(stringInitialized...) + unsafe buffer = buffer.extracting(stringInitialized...) let spanInitialized = utf8Span.span.withUnsafeBufferPointer { - buffer.initialize(fromContentsOf: $0) + unsafe buffer.initialize(fromContentsOf: $0) } return stringInitialized + spanInitialized diff --git a/Sources/RopeModule/Utilities/String.Index+ABI.swift b/Sources/RopeModule/Utilities/String.Index+ABI.swift index d9ce6a18..3d4ab298 100644 --- a/Sources/RopeModule/Utilities/String.Index+ABI.swift +++ b/Sources/RopeModule/Utilities/String.Index+ABI.swift @@ -15,7 +15,7 @@ extension String.Index { @inline(__always) var _abi_rawBits: UInt64 { - unsafeBitCast(self, to: UInt64.self) + unsafe unsafeBitCast(self, to: UInt64.self) } @inline(__always) @@ -62,12 +62,12 @@ extension String.Index { var _knownCharacterAligned: String.Index { let r = _abi_rawBits | Self._abi_characterAlignmentBit | Self._abi_scalarAlignmentBit - return unsafeBitCast(r, to: String.Index.self) + return unsafe unsafeBitCast(r, to: String.Index.self) } var _knownScalarAligned: String.Index { let r = _abi_rawBits | Self._abi_scalarAlignmentBit - return unsafeBitCast(r, to: String.Index.self) + return unsafe unsafeBitCast(r, to: String.Index.self) } } @@ -88,7 +88,7 @@ extension String.Index { @inline(__always) init(_rawBits: UInt64) { - self = unsafeBitCast(_rawBits, to: String.Index.self) + self = unsafe unsafeBitCast(_rawBits, to: String.Index.self) } @inline(__always) diff --git a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift index dac1d3c7..a50452d5 100644 --- a/Sources/RopeModule/Utilities/_CharacterRecognizer.swift +++ b/Sources/RopeModule/Utilities/_CharacterRecognizer.swift @@ -29,8 +29,8 @@ extension _CharacterRecognizer { mutating func firstBreak( in str: Substring ) -> Range? { - let r = str.utf8.withContiguousStorageIfAvailable { buffer in - self._firstBreak(inUncheckedUnsafeUTF8Buffer: buffer) + let r = unsafe str.utf8.withContiguousStorageIfAvailable { buffer in + unsafe self._firstBreak(inUncheckedUnsafeUTF8Buffer: buffer) } if let r { guard let scalarRange = r else { return nil } @@ -60,9 +60,12 @@ extension _CharacterRecognizer { from range: Range ) -> Range? { let bias = range.lowerBound.utf8Offset - let r = c.utf8Span(from: range.lowerBound, to: range.upperBound).span.withUnsafeBufferPointer { - _firstBreak(inUncheckedUnsafeUTF8Buffer: $0) - } + let r = c + .utf8Span(from: range.lowerBound, to: range.upperBound) + .span + .withUnsafeBufferPointer { + unsafe _firstBreak(inUncheckedUnsafeUTF8Buffer: $0) + } guard let r else { return nil diff --git a/Sources/SortedCollections/BTree/_BTree+BidirectionalCollection.swift b/Sources/SortedCollections/BTree/_BTree+BidirectionalCollection.swift index bca73df7..04e5fdbe 100644 --- a/Sources/SortedCollections/BTree/_BTree+BidirectionalCollection.swift +++ b/Sources/SortedCollections/BTree/_BTree+BidirectionalCollection.swift @@ -23,7 +23,7 @@ extension _BTree: BidirectionalCollection { /// - Complexity: O(1) @inlinable @inline(__always) - package var count: Int { self.root.storage.header.subtreeCount } + package var count: Int { unsafe self.root.storage.header.subtreeCount } /// A Boolean value that indicates whether the BTree is empty. @inlinable @@ -37,15 +37,15 @@ extension _BTree: BidirectionalCollection { package var startIndex: Index { if count == 0 { return endIndex } var depth: Int8 = 0 - var currentNode: Unmanaged = .passUnretained(self.root.storage) + var currentNode: Unmanaged = unsafe .passUnretained(self.root.storage) while true { - let shouldStop: Bool = currentNode._withUnsafeGuaranteedRef { - $0.read { handle in + let shouldStop: Bool = unsafe currentNode._withUnsafeGuaranteedRef { + unsafe $0.read { handle in if handle.isLeaf { return true } else { depth += 1 - currentNode = .passUnretained(handle[childAt: 0].storage) + unsafe currentNode = .passUnretained(handle[childAt: 0].storage) return false } } @@ -54,7 +54,7 @@ extension _BTree: BidirectionalCollection { if shouldStop { break } } - return Index( + return unsafe Index( node: currentNode, slot: 0, childSlots: _FixedSizeArray(repeating: 0, depth: depth), @@ -67,7 +67,7 @@ extension _BTree: BidirectionalCollection { /// - Complexity: O(1) @inlinable package var endIndex: Index { - Index( + unsafe Index( node: .passUnretained(self.root.storage), slot: -1, childSlots: Index.Offsets(repeating: 0), @@ -94,12 +94,12 @@ extension _BTree: BidirectionalCollection { @inlinable package func formIndex(after index: inout Index) { precondition(index.offset < self.count, - "Attempt to advance out of collection bounds.") + "Attempt to advance out of collection bounds") // TODO: this might be redundant given the fact the same (but generalized) // logic is implemented in offsetBy - let shouldSeekWithinLeaf = index.readNode { - $0.isLeaf && _fastPath(index.slot + 1 < $0.elementCount) + let shouldSeekWithinLeaf = unsafe index.readNode { + unsafe $0.isLeaf && _fastPath(index.slot + 1 < $0.elementCount) } if shouldSeekWithinLeaf { @@ -128,7 +128,7 @@ extension _BTree: BidirectionalCollection { @inlinable package func formIndex(before index: inout Index) { precondition(!self.isEmpty && index.offset != 0, - "Attempt to advance out of collection bounds.") + "Attempt to advance out of collection bounds") self.formIndex(&index, offsetBy: -1) } @@ -155,7 +155,7 @@ extension _BTree: BidirectionalCollection { package func formIndex(_ i: inout Index, offsetBy distance: Int) { let newIndex = i.offset + distance precondition(0 <= newIndex && newIndex <= self.count, - "Attempt to advance out of collection bounds.") + "Attempt to advance out of collection bounds") if newIndex == self.count { i = endIndex @@ -164,10 +164,10 @@ extension _BTree: BidirectionalCollection { // TODO: optimization for searching within children - if i != endIndex && i.readNode({ $0.isLeaf }) { + if unsafe i != endIndex && i.readNode({ $0.isLeaf }) { // Check if the target element will be in the same node let targetSlot = i.slot + distance - if 0 <= targetSlot && targetSlot < i.readNode({ $0.elementCount }) { + if unsafe 0 <= targetSlot && targetSlot < i.readNode({ unsafe $0.elementCount }) { i.slot = targetSlot i.offset = newIndex return @@ -197,7 +197,7 @@ extension _BTree: BidirectionalCollection { @inline(__always) package subscript(index: Index) -> Element { // Ensure we don't attempt to dereference the endIndex - precondition(index != endIndex, "Attempt to subscript out of range index.") + precondition(index != endIndex, "Attempt to subscript out of range index") return index.element } diff --git a/Sources/SortedCollections/BTree/_BTree+CustomDebugStringConvertible.swift b/Sources/SortedCollections/BTree/_BTree+CustomDebugStringConvertible.swift index a460556a..074eaf5e 100644 --- a/Sources/SortedCollections/BTree/_BTree+CustomDebugStringConvertible.swift +++ b/Sources/SortedCollections/BTree/_BTree+CustomDebugStringConvertible.swift @@ -17,8 +17,10 @@ extension _BTree: CustomDebugStringConvertible { #if DEBUG /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - return "BTree<\(Key.self), \(Value.self)>\n" + - self.root.read { String(reflecting: $0) } + return """ + BTree<\(Key.self), \(Value.self)> + \(unsafe self.root.read { unsafe String(reflecting: $0) }) + """ } #else /// A textual representation of this instance, suitable for debugging. diff --git a/Sources/SortedCollections/BTree/_BTree+Invariants.swift b/Sources/SortedCollections/BTree/_BTree+Invariants.swift index 4b0efe32..79bf089d 100644 --- a/Sources/SortedCollections/BTree/_BTree+Invariants.swift +++ b/Sources/SortedCollections/BTree/_BTree+Invariants.swift @@ -26,21 +26,21 @@ extension _BTree { maximum: Key? ) { node.read { handle in - assert(handle.depth == expectedDepth, "Node depth mismatch.") + assert(handle.depth == expectedDepth, "Node depth mismatch") assert(isRoot || handle.elementCount > 0, "Node cannot be empty") if handle.elementCount > 1 { for i in 0..<(handle.elementCount - 1) { assert(handle[keyAt: i] <= handle[keyAt: i + 1], - "Node keys out of order.") + "Node keys out of order") } } if handle.isLeaf { assert(handle.elementCount == handle.subtreeCount, - "Element and subtree count should match for leaves.") - assert(handle.depth == 0, "Non-zero depth for leaf.") - assert(isRoot || handle.isBalanced, "Unbalanced node.") + "Element and subtree count should match for leaves") + assert(handle.depth == 0, "Non-zero depth for leaf") + assert(isRoot || handle.isBalanced, "Unbalanced node") if handle.elementCount > 0 { return ( @@ -69,17 +69,17 @@ extension _BTree { if i == handle.childCount - 1 { assert(minimum! >= handle[keyAt: i - 1], - "Last subtree must be greater than or equal to last key.") + "Last subtree must be greater than or equal to last key") } else { assert(maximum! <= handle[keyAt: i], - "Subtree must be less than or equal to corresponding key.") + "Subtree must be less than or equal to corresponding key") } totalCount += handle[childAt: i].read { $0.subtreeCount } } assert(handle.subtreeCount == handle.elementCount + totalCount, - "Subtree count mismatch.") + "Subtree count mismatch") return ( minimum: subtreeMinimum, diff --git a/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift b/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift index 5a84fc47..bb939bed 100644 --- a/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift +++ b/Sources/SortedCollections/BTree/_BTree+Partial RangeReplaceableCollection.swift @@ -43,7 +43,7 @@ extension _BTree { if self.count == 0 { return nil } - let removedElement = self.root.update { $0.popLastElement() } + let removedElement = unsafe self.root.update { unsafe $0.popLastElement() } self._balanceRoot() return removedElement } @@ -80,7 +80,7 @@ extension _BTree { if self.count == 0 { return nil } - let removedElement = self.root.update { $0.popFirstElement() } + let removedElement = unsafe self.root.update { unsafe $0.popFirstElement() } self._balanceRoot() return removedElement } @@ -115,7 +115,7 @@ extension _BTree { @discardableResult internal mutating func remove(at index: Index) -> Element { invalidateIndices() - guard index != endIndex else { preconditionFailure("Index out of bounds.") } + guard index != endIndex else { preconditionFailure("Index out of bounds") } return self.remove(atOffset: index.offset) } @@ -131,8 +131,8 @@ extension _BTree { /// Removes the elements in the specified subrange from the collection. @inlinable internal mutating func removeSubrange(_ bounds: Range) { - guard bounds.lowerBound != endIndex else { preconditionFailure("Index out of bounds.") } - guard bounds.upperBound != endIndex else { preconditionFailure("Index out of bounds.") } + guard bounds.lowerBound != endIndex else { preconditionFailure("Index out of bounds") } + guard bounds.upperBound != endIndex else { preconditionFailure("Index out of bounds") } let rangeSize = self.distance(from: bounds.lowerBound, to: bounds.upperBound) let startOffset = bounds.lowerBound.offset diff --git a/Sources/SortedCollections/BTree/_BTree+Sequence.swift b/Sources/SortedCollections/BTree/_BTree+Sequence.swift index 5db12439..063805df 100644 --- a/Sources/SortedCollections/BTree/_BTree+Sequence.swift +++ b/Sources/SortedCollections/BTree/_BTree+Sequence.swift @@ -17,29 +17,30 @@ extension _BTree: Sequence { @inlinable package func forEach(_ body: (Element) throws -> Void) rethrows { func loop(node: Unmanaged) throws { - try node._withUnsafeGuaranteedRef { storage in - try storage.read { handle in - for i in 0..] /// Creates an iterator to the element within a tree corresponding to a specific index @@ -58,7 +60,7 @@ extension _BTree: Sequence { if _slowPath(self.tree.isEmpty || index.slot == -1) { self.slots = [] - self.path = [] + unsafe self.path = [] return } @@ -68,17 +70,17 @@ extension _BTree: Sequence { } self.slots.append(UInt16(index.slot)) - self.path = [] - - var node: Unmanaged = .passUnretained(tree.root.storage) - self.path.append(node) + unsafe self.path = [] + + var node: Unmanaged = unsafe .passUnretained(tree.root.storage) + unsafe self.path.append(node) for depth in 0.. Element? { // Check slot sentinel value for end of tree. - if _slowPath(path.isEmpty) { + if unsafe _slowPath(path.isEmpty) { return nil } - let element = path[path.count - 1]._withUnsafeGuaranteedRef { - $0.read { $0[elementAt: Int(slots[slots.count - 1])] } + let element = unsafe path[path.count - 1]._withUnsafeGuaranteedRef { + unsafe $0.read { + unsafe $0[elementAt: Int(slots[slots.count - 1])] + } } - path[path.count - 1]._withUnsafeGuaranteedRef { - $0.read({ handle in - self._advanceState(withLeaf: handle) + unsafe path[path.count - 1]._withUnsafeGuaranteedRef { + unsafe $0.read({ handle in + unsafe self._advanceState(withLeaf: handle) }) } diff --git a/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift b/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift index 57d01371..6e549210 100644 --- a/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift +++ b/Sources/SortedCollections/BTree/_BTree+UnsafeCursor.swift @@ -28,6 +28,7 @@ extension _BTree { /// - Warning: the tree root must remain alive for the entire lifetime of a cursor otherwise bad things /// may occur. @usableFromInline + @unsafe internal struct UnsafeCursor { @usableFromInline internal typealias Path = _FixedSizeArray> @@ -35,9 +36,9 @@ extension _BTree { /// This property is what takes ownership of the tree during the lifetime of the cursor. Once the cursor /// is consumed, it is set to nil and it is invalid to use the cursor. @usableFromInline + @safe internal var _root: Node.Storage? - /// Position of each of the parent nodes in their parents, including the bottom-most node. /// /// In the following tree, a cursor to `7` would contain `[1, 0]`. Referring to the child at index 1 @@ -51,10 +52,12 @@ extension _BTree { /// │1│3│ │7│9│ /// └─┴─┘ └─┴─┘ @usableFromInline + @safe internal var slots: _FixedSizeArray<_BTree.Slot> /// This stores a list of the nodes from top-to-bottom. @usableFromInline + @unsafe internal var path: Path /// Bottom most node that the index point to. @@ -77,6 +80,7 @@ extension _BTree { /// This is notable for CoW as all values below it would need to be duplicated. Updating this to be as /// high as accurately possible ensures there are no unnecessary copies made. @usableFromInline + @safe internal var lastUniqueDepth: Int @inlinable @@ -88,12 +92,12 @@ extension _BTree { lastUniqueDepth: Int ) { // Slots and path should be non-empty - assert(slots.depth >= 1, "Invalid tree cursor.") - assert(path.depth >= 1, "Invalid tree cursor.") - + assert(slots.depth >= 1, "Invalid tree cursor") + assert(unsafe path.depth >= 1, "Invalid tree cursor") + self._root = root self.slots = slots - self.path = path + unsafe self.path = path self.lastUniqueDepth = lastUniqueDepth } @@ -108,7 +112,7 @@ extension _BTree { internal func assertValid() { #if COLLECTIONS_INTERNAL_CHECKS assert(self._root != nil, - "Attempt to operate on an element using an invalid cursor.") + "Attempt to operate on an element using an invalid cursor") #endif } @@ -117,8 +121,8 @@ extension _BTree { @inlinable @inline(__always) internal mutating func apply(to tree: inout _BTree) { - assertValid() - assert(tree.root._storage == nil, "Must apply to same tree as original.") + unsafe assertValid() + assert(tree.root._storage == nil, "Must apply to same tree as original") swap(&tree.root._storage, &self._root) tree.checkInvariants() } @@ -127,7 +131,7 @@ extension _BTree { @inlinable @inline(__always) internal mutating func _declareUnique() { - self.lastUniqueDepth = Int(path.depth) + self.lastUniqueDepth = unsafe Int(path.depth) } /// Operators on a handle of the node @@ -137,11 +141,11 @@ extension _BTree { internal mutating func readCurrentNode( _ body: (Node.UnsafeHandle, Int) throws -> R ) rethrows -> R { - assertValid() - + unsafe assertValid() + let slot = Int(slots[slots.depth - 1]) - return try path[path.depth - 1]._withUnsafeGuaranteedRef { - try $0.read({ try body($0, slot) }) + return unsafe try path[path.depth - 1]._withUnsafeGuaranteedRef { + unsafe try $0.read({ unsafe try body($0, slot) }) } } @@ -153,19 +157,19 @@ extension _BTree { atDepth depth: Int8, _ body: (Node.UnsafeHandle, Int) throws -> R ) rethrows -> (node: Node, result: R) { - assertValid() - + unsafe assertValid() + let slot = Int(slots[depth]) let isOnUniquePath = depth <= lastUniqueDepth - return try path[depth]._withUnsafeGuaranteedRef { storage in + return unsafe try path[depth]._withUnsafeGuaranteedRef { storage in if isOnUniquePath { - let result = try storage.updateGuaranteedUnique({ try body($0, slot) }) + let result = unsafe try storage.updateGuaranteedUnique({ unsafe try body($0, slot) }) return (Node(storage), result) } else { let storage = storage.copy() - path[depth] = .passUnretained(storage) - let result = try storage.updateGuaranteedUnique({ try body($0, slot) }) + unsafe path[depth] = .passUnretained(storage) + let result = unsafe try storage.updateGuaranteedUnique({ unsafe try body($0, slot) }) return (Node(storage), result) } } @@ -187,19 +191,19 @@ extension _BTree { internal mutating func updateCurrentNode( _ body: (Node.UnsafeHandle, Int) throws -> R ) rethrows -> R { - assertValid() - defer { self._declareUnique() } - + unsafe assertValid() + defer { unsafe self._declareUnique() } + // Update the bottom-most node - var (node, result) = try self.updateNode(atDepth: path.depth - 1, body) - + var (node, result) = unsafe try self.updateNode(atDepth: path.depth - 1, body) + // Start the node above the bottom-most node, and propagate up the change - var depth = path.depth - 2 + var depth = unsafe path.depth - 2 while depth >= 0 { if depth > lastUniqueDepth { // If we're on a - let (newNode, _) = self.updateNode(atDepth: depth) { (handle, slot) in - _ = handle.exchangeChild(atSlot: slot, with: node) + let (newNode, _) = unsafe self.updateNode(atDepth: depth) { (handle, slot) in + _ = unsafe handle.exchangeChild(atSlot: slot, with: node) } node = newNode @@ -210,9 +214,9 @@ extension _BTree { let child = node let slot = Int(slots[depth]) - path[depth]._withUnsafeGuaranteedRef { storage in - storage.updateGuaranteedUnique { handle in - _ = handle.exchangeChild(atSlot: slot, with: child) + unsafe path[depth]._withUnsafeGuaranteedRef { storage in + unsafe storage.updateGuaranteedUnique { handle in + _ = unsafe handle.exchangeChild(atSlot: slot, with: child) } } @@ -238,8 +242,8 @@ extension _BTree { internal mutating func moveValue() -> Value { guard Node.hasValues else { return Node.dummyValue } - return self.updateCurrentNode { handle, slot in - handle.pointerToValue(atSlot: slot).move() + return unsafe self.updateCurrentNode { handle, slot in + unsafe handle.pointerToValue(atSlot: slot).move() } } @@ -249,8 +253,8 @@ extension _BTree { internal mutating func initializeValue(to value: Value) { guard Node.hasValues else { return } - self.updateCurrentNode { handle, slot in - handle.pointerToValue(atSlot: slot).initialize(to: value) + unsafe self.updateCurrentNode { handle, slot in + unsafe handle.pointerToValue(atSlot: slot).initialize(to: value) } } @@ -269,23 +273,23 @@ extension _BTree { _ element: Node.Element, capacity: Int ) { - assertValid() - defer { self._declareUnique() } - - var (node, splinter) = self.updateNode(atDepth: path.depth - 1) { handle, slot in - handle.insertElement(element, withRightChild: nil, atSlot: slot) + unsafe assertValid() + defer { unsafe self._declareUnique() } + + var (node, splinter) = unsafe self.updateNode(atDepth: path.depth - 1) { handle, slot in + unsafe handle.insertElement(element, withRightChild: nil, atSlot: slot) } // Start the node above the bottom-most node, and propagate up the change - var depth = path.depth - 2 + var depth = unsafe path.depth - 2 while depth >= 0 { - let (newNode, _) = self.updateNode(atDepth: depth) { (handle, slot) in - handle.exchangeChild(atSlot: slot, with: node) - + let (newNode, _) = unsafe self.updateNode(atDepth: depth) { (handle, slot) in + unsafe handle.exchangeChild(atSlot: slot, with: node) + if let lastSplinter = splinter { - splinter = handle.insertSplinter(lastSplinter, atSlot: slot) + splinter = unsafe handle.insertSplinter(lastSplinter, atSlot: slot) } else { - handle.subtreeCount += 1 + unsafe handle.subtreeCount += 1 } } @@ -307,58 +311,58 @@ extension _BTree { /// - Complexity: O(`log n`). Ascends the tree once. @inlinable internal mutating func removeElement(hasValueHole: Bool = false) { - assertValid() - defer { self._declareUnique() } - - var (node, _) = self.updateNode( + unsafe assertValid() + defer { unsafe self._declareUnique() } + + var (node, _) = unsafe self.updateNode( atDepth: path.depth - 1 ) { handle, slot in if handle.isLeaf { // Deletion within a leaf // removeElement(atSlot:) automatically adjusts node counts. if hasValueHole { - handle.removeElementWithoutValue(atSlot: slot) + unsafe handle.removeElementWithoutValue(atSlot: slot) } else { - handle.removeElement(atSlot: slot) + unsafe handle.removeElement(atSlot: slot) } } else { // Deletion within an internal node // Swap with the predecessor let predecessor = - handle[childAt: slot].update { $0.popLastElement() } - + unsafe handle[childAt: slot].update { unsafe $0.popLastElement() } + // Reduce the element count. - handle.subtreeCount -= 1 - + unsafe handle.subtreeCount -= 1 + // Replace the current element with the predecessor. if hasValueHole { - _ = handle.pointerToKey(atSlot: slot).move() - handle.initializeElement(atSlot: slot, to: predecessor) + _ = unsafe handle.pointerToKey(atSlot: slot).move() + unsafe handle.initializeElement(atSlot: slot, to: predecessor) } else { - handle.exchangeElement(atSlot: slot, with: predecessor) + unsafe handle.exchangeElement(atSlot: slot, with: predecessor) } // Balance the predecessor child slot, as the pop operation may have // brought it out of balance. - handle.balance(atSlot: slot) + unsafe handle.balance(atSlot: slot) } } // Balance the parents - var depth = path.depth - 2 + var depth = unsafe path.depth - 2 while depth >= 0 { - var (newNode, _) = self.updateNode(atDepth: depth) { (handle, slot) in - handle.exchangeChild(atSlot: slot, with: node) - handle.subtreeCount -= 1 - handle.balance(atSlot: slot) + var (newNode, _) = unsafe self.updateNode(atDepth: depth) { (handle, slot) in + unsafe handle.exchangeChild(atSlot: slot, with: node) + unsafe handle.subtreeCount -= 1 + unsafe handle.balance(atSlot: slot) } - if depth == 0 && newNode.read({ $0.elementCount == 0 && !$0.isLeaf }) { + if unsafe depth == 0 && newNode.read({ unsafe $0.elementCount == 0 && !$0.isLeaf }) { // If the root has no elements, we drop it and promote the child. - node = newNode.update(isUnique: true) { handle in - let newRoot = handle.moveChild(atSlot: 0) - handle.drop() + node = unsafe newNode.update(isUnique: true) { handle in + let newRoot = unsafe handle.moveChild(atSlot: 0) + unsafe handle.drop() return newRoot } } else { @@ -386,29 +390,29 @@ extension _BTree { // Initialize parents with some dummy value filling it. var parents = - UnsafeCursor.Path(repeating: .passUnretained(self.root.storage)) - + unsafe UnsafeCursor.Path(repeating: .passUnretained(self.root.storage)) + var ownedRoot: Node.Storage do { var tempRoot: Node.Storage? = nil swap(&tempRoot, &self.root._storage) - ownedRoot = tempRoot.unsafelyUnwrapped + ownedRoot = unsafe tempRoot.unsafelyUnwrapped } - var node: Unmanaged = .passUnretained(ownedRoot) - + var node: Unmanaged = unsafe .passUnretained(ownedRoot) + // The depth containing the first instance of a shared var lastUniqueDepth = isKnownUniquelyReferenced(&ownedRoot) ? 0 : -1 var isOnUniquePath = isKnownUniquelyReferenced(&ownedRoot) for d in 0.. = .passUnretained(ownedRoot) - + var node: Unmanaged = unsafe .passUnretained(ownedRoot) + // Initialize slot to some dummy value. var slot = -1 var found: Bool = false @@ -466,22 +465,22 @@ extension _BTree { var isOnUniquePath = isKnownUniquelyReferenced(&ownedRoot) while true { - let shouldStop: Bool = node._withUnsafeGuaranteedRef { storage in - storage.read { handle in - slot = handle.startSlot(forKey: key) - - if slot < handle.elementCount && handle[keyAt: slot] == key { + let shouldStop: Bool = unsafe node._withUnsafeGuaranteedRef { storage in + unsafe storage.read { handle in + slot = unsafe handle.startSlot(forKey: key) + + if unsafe slot < handle.elementCount && handle[keyAt: slot] == key { found = true return true } else { if handle.isLeaf { return true } else { - parents.append(node) + unsafe parents.append(node) slots.append(UInt16(slot)) - node = .passUnretained(handle[childAt: slot].storage) - if isOnUniquePath && handle.isChildUnique(atSlot: slot) { + unsafe node = .passUnretained(handle[childAt: slot].storage) + if unsafe isOnUniquePath && handle.isChildUnique(atSlot: slot) { lastUniqueDepth += 1 } else { isOnUniquePath = false @@ -497,17 +496,16 @@ extension _BTree { assert(slot != -1) - parents.append(node) + unsafe parents.append(node) slots.append(UInt16(slot)) - let cursor = UnsafeCursor( + let cursor = unsafe UnsafeCursor( root: ownedRoot, slots: slots, path: parents, - lastUniqueDepth: lastUniqueDepth - ) + lastUniqueDepth: lastUniqueDepth) - return (cursor, found) + return unsafe (cursor, found) } } diff --git a/Sources/SortedCollections/BTree/_BTree.Builder.swift b/Sources/SortedCollections/BTree/_BTree.Builder.swift index 8c6744c8..941f1dd9 100644 --- a/Sources/SortedCollections/BTree/_BTree.Builder.swift +++ b/Sources/SortedCollections/BTree/_BTree.Builder.swift @@ -87,13 +87,13 @@ extension _BTree { internal var seedling: Node { get { assert(_seedling != nil, - "Simultaneous access or access on consumed builder.") - return _seedling.unsafelyUnwrapped + "Simultaneous access or access on consumed builder") + return unsafe _seedling.unsafelyUnwrapped } _modify { assert(_seedling != nil, - "Simultaneous mutable access or mutable access on consumed builder.") - var value = _seedling.unsafelyUnwrapped + "Simultaneous mutable access or mutable access on consumed builder") + var value = unsafe _seedling.unsafelyUnwrapped _seedling = nil defer { _seedling = value } yield &value @@ -204,7 +204,7 @@ extension _BTree { @inlinable package mutating func append(_ element: __owned Element) { assert(lastKey == nil || lastKey! <= element.key, - "New element must be non-decreasing.") + "New element must be non-decreasing") defer { lastKey = element.key } if deduplicating { if let lastKey = lastKey { @@ -218,9 +218,9 @@ extension _BTree { state = .appendingToSeedling case .appendingToSeedling: - let isFull: Bool = seedling.update { handle in - handle.appendElement(element) - return handle.isFull + let isFull: Bool = unsafe seedling.update { handle in + unsafe handle.appendElement(element) + return unsafe handle.isFull } if _slowPath(isFull) { @@ -247,12 +247,12 @@ extension _BTree { // - The stack has saplings of decreasing depth. // - Saplings on the stack are completely filled except for their roots. if case (var previousSapling, let separator)? = self.popSapling() { - let saplingDepth = sapling.storage.header.depth - let previousSaplingDepth = previousSapling.storage.header.depth - let previousSaplingIsFull = previousSapling.read({ $0.isFull }) - + let saplingDepth = unsafe sapling.storage.header.depth + let previousSaplingDepth = unsafe previousSapling.storage.header.depth + let previousSaplingIsFull = unsafe previousSapling.read({ unsafe $0.isFull }) + assert(previousSaplingDepth >= saplingDepth, - "Builder invariant failure.") + "Builder invariant failure") if saplingDepth == previousSaplingDepth && previousSaplingIsFull { // This is when two nodes are full: @@ -300,8 +300,8 @@ extension _BTree { // ┌─┴─┐ ┌─┴─┐ ┌┴──┐ // │ A │ │ C │ │ E │ // └───┘ └───┘ └───┘ - previousSapling.update { - $0.appendElement(separator, withRightChild: sapling) + unsafe previousSapling.update { + unsafe $0.appendElement(separator, withRightChild: sapling) } sapling = previousSapling } else { diff --git a/Sources/SortedCollections/BTree/_BTree.Index.swift b/Sources/SortedCollections/BTree/_BTree.Index.swift index 9d923c9e..91fbf144 100644 --- a/Sources/SortedCollections/BTree/_BTree.Index.swift +++ b/Sources/SortedCollections/BTree/_BTree.Index.swift @@ -19,6 +19,7 @@ extension _BTree { /// - Warning: This has the capability to perform safety checks, however they must be explicitly be /// performed using the validation methods. @usableFromInline + @safe package struct Index { /// A fixed-size array large enough to represent all offsets within a B-Tree index @usableFromInline @@ -33,6 +34,7 @@ extension _BTree { /// /// This is equal to `root` to indicate the `endIndex` @usableFromInline + @unsafe internal var node: Unmanaged /// The slot within the bottom most node which the index points to. @@ -62,6 +64,7 @@ extension _BTree { /// - tree: The tree of this index. @inlinable @inline(__always) + @unsafe internal init( node: Unmanaged, slot: Int, @@ -69,7 +72,7 @@ extension _BTree { offset: Int, forTree tree: _BTree ) { - self.node = node + unsafe self.node = node self.slot = slot self.childSlots = childSlots self.offset = offset @@ -86,7 +89,7 @@ extension _BTree { internal func ensureValid(forTree tree: _BTree) { precondition( self.root === tree.root.storage && self.version == tree.version, - "Attempt to use an invalid index.") + "Attempt to use an invalid index") } /// Ensures the precondition that the index is valid for use with another index @@ -97,7 +100,7 @@ extension _BTree { self.root != nil && self.root === index.root && self.version == index.version, - "Attempt to use an invalid indices.") + "Attempt to use an invalid indices") } } } @@ -111,16 +114,16 @@ extension _BTree.Index { internal func readNode( _ body: (_BTree.Node.UnsafeHandle) throws -> R ) rethrows -> R { - assert(self.slot != -1, "Invalid operation to read end index.") - return try self.node._withUnsafeGuaranteedRef { try $0.read(body) } + assert(self.slot != -1, "Invalid operation to read end index") + return unsafe try self.node._withUnsafeGuaranteedRef { unsafe try $0.read(body) } } /// Gets the element the path points to. @inlinable @inline(__always) internal var element: _BTree.Element { - assert(self.slot != -1, "Cannot dereference out-of-bounds slot.") - return self.readNode { $0[elementAt: self.slot] } + assert(self.slot != -1, "Cannot dereference out-of-bounds slot") + return unsafe self.readNode { unsafe $0[elementAt: self.slot] } } } diff --git a/Sources/SortedCollections/BTree/_BTree.swift b/Sources/SortedCollections/BTree/_BTree.swift index 81cb943c..e5b5bf56 100644 --- a/Sources/SortedCollections/BTree/_BTree.swift +++ b/Sources/SortedCollections/BTree/_BTree.swift @@ -176,7 +176,9 @@ extension _BTree { invalidateIndices() defer { self.checkInvariants() } - let result = self.root.update { $0.updateAnyValue(value, forKey: key, updatingKey: updatingKey) } + let result = unsafe self.root.update { + unsafe $0.updateAnyValue(value, forKey: key, updatingKey: updatingKey) + } switch result { case let .updated(previousValue): return previousValue @@ -196,10 +198,10 @@ extension _BTree { @inlinable @inline(__always) package mutating func _balanceRoot() { - if self.root.read({ $0.elementCount == 0 && !$0.isLeaf }) { - let newRoot: Node = self.root.update { handle in - let newRoot = handle.moveChild(atSlot: 0) - handle.drop() + if unsafe self.root.read({ unsafe $0.elementCount == 0 && !$0.isLeaf }) { + let newRoot: Node = unsafe self.root.update { handle in + let newRoot = unsafe handle.moveChild(atSlot: 0) + unsafe handle.drop() return newRoot } @@ -225,8 +227,10 @@ extension _BTree { // TODO: It is possible that there is a single transient CoW copied made // if the removal results in the CoW copied node being completely removed // from the tree. - let removedElement = self.root.update { $0.removeAnyElement(forKey: key) } - + let removedElement = unsafe self.root.update { + unsafe $0.removeAnyElement(forKey: key) + } + // Check if the tree height needs to be reduced self._balanceRoot() self.checkInvariants() @@ -248,7 +252,9 @@ extension _BTree { invalidateIndices() defer { self.checkInvariants() } - let removedElement = self.root.update { $0.remove(at: offset) } + let removedElement = unsafe self.root.update { + unsafe $0.remove(at: offset) + } self._balanceRoot() return removedElement @@ -268,10 +274,10 @@ extension _BTree { var node: Node? = self.root while let currentNode = node { - let found: Bool = currentNode.read { handle in - let slot = handle.startSlot(forKey: key) - - if slot < handle.elementCount && handle[keyAt: slot] == key { + let found: Bool = unsafe currentNode.read { handle in + let slot = unsafe handle.startSlot(forKey: key) + + if unsafe slot < handle.elementCount && handle[keyAt: slot] == key { return true } else { if handle.isLeaf { @@ -279,7 +285,7 @@ extension _BTree { } else { // Release // Retain - node = handle[childAt: slot] + node = unsafe handle[childAt: slot] } } @@ -302,20 +308,20 @@ extension _BTree { /// - Complexity: O(`log n`) @inlinable package func findAnyValue(forKey key: Key) -> Value? { - var node: Unmanaged? = .passUnretained(self.root.storage) - - while let currentNode = node { - let value: Value? = currentNode._withUnsafeGuaranteedRef { - $0.read { handle in - let slot = handle.startSlot(forKey: key) - - if slot < handle.elementCount && handle[keyAt: slot] == key { - return handle[valueAt: slot] + var node: Unmanaged? = unsafe .passUnretained(self.root.storage) + + while let currentNode = unsafe node { + let value: Value? = unsafe currentNode._withUnsafeGuaranteedRef { + unsafe $0.read { handle in + let slot = unsafe handle.startSlot(forKey: key) + + if unsafe slot < handle.elementCount && handle[keyAt: slot] == key { + return unsafe handle[valueAt: slot] } else { if handle.isLeaf { - node = nil + unsafe node = nil } else { - node = .passUnretained(handle[childAt: slot].storage) + unsafe node = .passUnretained(handle[childAt: slot].storage) } } @@ -338,23 +344,23 @@ extension _BTree { @inlinable package func findAnyIndex(forKey key: Key) -> Index? { var childSlots = Index.Offsets(repeating: 0) - var node: Unmanaged? = .passUnretained(self.root.storage) + var node: Unmanaged? = unsafe .passUnretained(self.root.storage) var offset: Int = 0 - while let currentNode = node { - let index: Index? = currentNode._withUnsafeGuaranteedRef { storage in - storage.read { handle in - let keySlot = handle.startSlot(forKey: key) + while let currentNode = unsafe node { + let index: Index? = unsafe currentNode._withUnsafeGuaranteedRef { storage in + unsafe storage.read { handle in + let keySlot = unsafe handle.startSlot(forKey: key) offset += keySlot - if keySlot < handle.elementCount && handle[keyAt: keySlot] == key { + if unsafe keySlot < handle.elementCount && handle[keyAt: keySlot] == key { if !handle.isLeaf { for i in 0...keySlot { - offset += handle[childAt: i].storage.header.subtreeCount + offset += unsafe handle[childAt: i].storage.header.subtreeCount } } - return Index( + return unsafe Index( node: .passUnretained(storage), slot: keySlot, childSlots: childSlots, @@ -363,14 +369,14 @@ extension _BTree { ) } else { if handle.isLeaf { - node = nil + unsafe node = nil } else { for i in 0.. Index { - assert(offset <= self.count, "Index out of bounds.") + assert(offset <= self.count, "Index out of bounds") // Return nil path if at the end of the tree if offset == self.count { @@ -399,14 +405,14 @@ extension _BTree { var childSlots = Index.Offsets(repeating: 0) - var node: Unmanaged = .passUnretained(self.root.storage) + var node: Unmanaged = unsafe .passUnretained(self.root.storage) var startIndex = 0 while true { - let index: Index? = node._withUnsafeGuaranteedRef { storage in - storage.read({ handle in + let index: Index? = unsafe node._withUnsafeGuaranteedRef { storage in + unsafe storage.read({ handle in if handle.isLeaf { - return Index( + return unsafe Index( node: node, slot: offset - startIndex, childSlots: childSlots, @@ -415,19 +421,19 @@ extension _BTree { ) } - for childSlot in 0.. Unmanaged? { - node.read({ handle in - let slot = handle.startSlot(forKey: key) + unsafe node.read({ handle in + let slot = unsafe handle.startSlot(forKey: key) if handle.isLeaf { - if slot < handle.elementCount { + if unsafe slot < handle.elementCount { offset += slot targetSlot = slot - return .passUnretained(node.storage) + return unsafe .passUnretained(node.storage) } return nil } @@ -476,32 +482,32 @@ extension _BTree { // child[slot] starts after `slot` elements and `slot` preceding subtrees. offset += slot for i in 0..= key. Try child[slot] for an earlier occurrence first. - let elemOffset = offset + handle[childAt: slot].read({ $0.subtreeCount }) + let elemOffset = unsafe offset + handle[childAt: slot]._subtreeCount let savedDepth = childSlots.depth childSlots.append(UInt16(slot)) - if let foundEarlier = search(in: handle[childAt: slot]) { - return foundEarlier + if let foundEarlier = unsafe search(in: handle[childAt: slot]) { + return unsafe foundEarlier } childSlots.depth = savedDepth targetSlot = slot offset = elemOffset - return .passUnretained(node.storage) + return unsafe .passUnretained(node.storage) } else { // key > all elements here: descend into the rightmost child. childSlots.append(UInt16(slot)) - return search(in: handle[childAt: slot]) + return unsafe search(in: handle[childAt: slot]) } }) } - if let targetChild = search(in: self.root) { - return Index( + if let targetChild = unsafe search(in: self.root) { + return unsafe Index( node: targetChild, slot: targetSlot, childSlots: childSlots, @@ -521,14 +527,14 @@ extension _BTree { var offset = 0 func search(in node: Node) -> Unmanaged? { - node.read({ handle in - let slot = handle.endSlot(forKey: key) - 1 + unsafe node.read { handle in + let slot = unsafe handle.endSlot(forKey: key) - 1 if handle.isLeaf { if slot >= 0 { offset += slot targetSlot = slot - return .passUnretained(node.storage) + return unsafe .passUnretained(node.storage) } return nil } @@ -538,9 +544,9 @@ extension _BTree { // element still <= key. offset += slot for i in 0.. { @inlinable @inline(__always) @@ -53,7 +54,7 @@ internal struct _FixedSizeArray { @inline(__always) internal mutating func append(_ value: __owned Element) { assert(depth < _FixedSizeArray.maxSize, - "Out of bounds access in fixed sized array.") + "Out of bounds access in fixed sized array") defer { self.depth &+= 1 } self[self.depth] = value } @@ -92,26 +93,26 @@ internal struct _FixedSizeArray { internal subscript(_ position: Int8) -> Element { get { assert(position <= depth && depth <= _FixedSizeArray.maxSize, - "Out of bounds access in fixed sized array.") + "Out of bounds access in fixed sized array") return withUnsafeBytes(of: self.values) { values in - let p = values.baseAddress!.assumingMemoryBound(to: Element.self) - return p.advanced(by: Int(position)).pointee + let p = unsafe values.baseAddress!.assumingMemoryBound(to: Element.self) + return unsafe p.advanced(by: Int(position)).pointee } } _modify { assert(position <= depth && depth <= _FixedSizeArray.maxSize, - "Out of bounds access in fixed sized array.") + "Out of bounds access in fixed sized array") let ptr: UnsafeMutablePointer = withUnsafeMutableBytes(of: &self.values) { values in - let p = values.baseAddress!.assumingMemoryBound(to: Element.self) - return p.advanced(by: Int(position)) + let p = unsafe values.baseAddress!.assumingMemoryBound(to: Element.self) + return unsafe p.advanced(by: Int(position)) } - var value = ptr.move() - defer { ptr.initialize(to: value) } + var value = unsafe ptr.move() + defer { unsafe ptr.initialize(to: value) } yield &value } } diff --git a/Sources/SortedCollections/BTree/_Node+CustomDebugString.swift b/Sources/SortedCollections/BTree/_Node+CustomDebugString.swift index df09451d..ab84ff53 100644 --- a/Sources/SortedCollections/BTree/_Node+CustomDebugString.swift +++ b/Sources/SortedCollections/BTree/_Node+CustomDebugString.swift @@ -16,7 +16,7 @@ extension _Node: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - self.read { $0.debugDescription } + unsafe self.read { unsafe $0.debugDescription } } } diff --git a/Sources/SortedCollections/BTree/_Node+Testing.swift b/Sources/SortedCollections/BTree/_Node+Testing.swift index b4dd5d06..9fd337bf 100644 --- a/Sources/SortedCollections/BTree/_Node+Testing.swift +++ b/Sources/SortedCollections/BTree/_Node+Testing.swift @@ -20,45 +20,45 @@ extension _Node { children: [_Node]? = nil, capacity: Int ) where C.Element == Element { - precondition(keyValuePairs.count <= capacity, "Too many key-value pairs.") + precondition(keyValuePairs.count <= capacity, "Too many key-value pairs") self.init(withCapacity: capacity, isLeaf: children == nil) - self.update { handle in + unsafe self.update { handle in let sortedKeyValuePairs = keyValuePairs.sorted(by: { $0.key < $1.key }) for (index, pair) in sortedKeyValuePairs.enumerated() { let (key, value) = pair - handle.keys.advanced(by: index).initialize(to: key) - handle.values?.advanced(by: index).initialize(to: value) + unsafe handle.keys.advanced(by: index).initialize(to: key) + unsafe handle.values?.advanced(by: index).initialize(to: value) } if let children = children { for (index, child) in children.enumerated() { - handle.children!.advanced(by: index).initialize(to: child) + unsafe handle.children!.advanced(by: index).initialize(to: child) } - handle.depth = handle[childAt: 0].storage.header.depth + 1 + unsafe handle.depth = handle[childAt: 0].storage.header.depth + 1 } - let totalChildElements = children?.reduce(0, { $0 + $1.read({ $0.subtreeCount }) }) + let totalChildElements = children?.reduce(0, { $0 + $1._subtreeCount }) - handle.elementCount = keyValuePairs.count - handle.subtreeCount = keyValuePairs.count + (totalChildElements ?? 0) + unsafe handle.elementCount = keyValuePairs.count + unsafe handle.subtreeCount = keyValuePairs.count + (totalChildElements ?? 0) } } /// Converts a node to a single array. package func toArray() -> [Element] { - self.read { handle in + unsafe self.read { handle in if handle.isLeaf { - return Array((0..?, - children: UnsafeMutablePointer<_Node>? - ) { - self._internalCounts = 0 - self.values = values - self.children = children - self.subtreeCount = subtreeCount - - self.capacity = capacity - self.count = count - self.depth = depth - } - /// Packed integer to store all node counts. /// /// This is represented as: @@ -46,16 +28,52 @@ extension _Node { /// count depth /// @usableFromInline + @safe internal var _internalCounts: UInt64 + + /// The total amount of elements contained underneath this node + @usableFromInline + @safe + package var subtreeCount: Int + + /// Pointer to the buffer containing the corresponding values. + @usableFromInline + @unsafe + package var values: UnsafeMutablePointer? + + /// Pointer to the buffer containing the elements. + @usableFromInline + @unsafe + package var children: UnsafeMutablePointer<_Node>? + + @inlinable + internal init( + capacity: Int, + count: Int, + subtreeCount: Int, + depth: Int, + values: UnsafeMutablePointer?, + children: UnsafeMutablePointer<_Node>? + ) { + self._internalCounts = 0 + unsafe self.values = values + unsafe self.children = children + self.subtreeCount = subtreeCount + + self.capacity = capacity + self.count = count + self.depth = depth + } /// Refers to the amount of keys in the node. @inlinable @inline(__always) + @safe package var count: Int { get { Int((_internalCounts & 0xFFFFFFF000000000) >> 40) } set { - assert(0 <= newValue && newValue <= 0xFFFFFFF, "Invalid count.") - assert(newValue <= capacity, "Count cannot exceed capacity.") + assert(0 <= newValue && newValue <= 0xFFFFFFF, "Invalid count") + assert(newValue <= capacity, "Count cannot exceed capacity") _internalCounts &= ~0xFFFFFFF000000000 _internalCounts |= UInt64(newValue) << 40 } @@ -64,11 +82,12 @@ extension _Node { /// The total amount of keys possible to store within the node. @inlinable @inline(__always) + @safe package var capacity: Int { get { Int((_internalCounts & 0x0000000FFFFFFF00) >> 8) } set { - assert(0 <= newValue && newValue <= 0xFFFFFFF, "Invalid capacity.") - assert(newValue >= count, "Capacity cannot be below count.") + assert(0 <= newValue && newValue <= 0xFFFFFFF, "Invalid capacity") + assert(newValue >= count, "Capacity cannot be below count") _internalCounts &= ~0x0000000FFFFFFF00 _internalCounts |= UInt64(newValue) << 8 } @@ -77,26 +96,15 @@ extension _Node { /// The depth of the node represented as the number of nodes below the current one. @inlinable @inline(__always) + @safe package var depth: Int { get { Int(_internalCounts & 0x00000000000000FF) } set { - assert(0 <= newValue && newValue <= 0xFF, "Invalid depth.") + assert(0 <= newValue && newValue <= 0xFF, "Invalid depth") _internalCounts &= ~0x00000000000000FF _internalCounts |= UInt64(newValue) } } - - /// The total amount of elements contained underneath this node - @usableFromInline - package var subtreeCount: Int - - /// Pointer to the buffer containing the corresponding values. - @usableFromInline - package var values: UnsafeMutablePointer? - - /// Pointer to the buffer containing the elements. - @usableFromInline - package var children: UnsafeMutablePointer<_Node>? } /// Represents the underlying data for a node. @@ -118,6 +126,7 @@ extension _Node { /// that can be passed to APIs. @usableFromInline @_fixed_layout // Not really! This module isn't ABI stable. + @safe // FIXME: Really? internal class Storage: ManagedBuffer<_Node.Header, Key> { /// Allows **read-only** access to the underlying data behind the node. /// @@ -125,16 +134,17 @@ extension _Node { /// - Returns: The value the closure body returns, if any. @inlinable @inline(__always) + @unsafe internal func read(_ body: (UnsafeHandle) throws -> R) rethrows -> R { - return try self.withUnsafeMutablePointers { header, keys in - let handle = UnsafeHandle( + return unsafe try self.withUnsafeMutablePointers { header, keys in + let handle = unsafe UnsafeHandle( keys: keys, values: header.pointee.values, children: header.pointee.children, header: header, isMutable: false ) - return try body(handle) + return unsafe try body(handle) } } @@ -151,10 +161,11 @@ extension _Node { /// - Warning: The underlying storage **must** be unique. @inlinable @inline(__always) + @unsafe internal func updateGuaranteedUnique( _ body: (UnsafeHandle) throws -> R ) rethrows -> R { - try self.read { try body(UnsafeHandle(mutating: $0)) } + unsafe try self.read { unsafe try body(UnsafeHandle(mutating: $0)) } } /// Creates a new storage object. @@ -167,8 +178,8 @@ extension _Node { withCapacity capacity: Int, isLeaf: Bool ) -> Storage { - let storage = Storage.create(minimumCapacity: capacity) { _ in - Header( + let storage = unsafe Storage.create(minimumCapacity: capacity) { _ in + unsafe Header( capacity: capacity, count: 0, subtreeCount: 0, @@ -181,7 +192,7 @@ extension _Node { ) } - return unsafeDowncast(storage, to: Storage.self) + return unsafe unsafeDowncast(storage, to: Storage.self) } /// Copies an existing storage to a new storage. @@ -190,33 +201,33 @@ extension _Node { @inlinable @inline(__always) internal func copy() -> Storage { - let capacity = self.header.capacity - let count = self.header.count - let subtreeCount = self.header.subtreeCount - let depth = self.header.depth - let isLeaf = self.header.children == nil - + let capacity = unsafe self.header.capacity + let count = unsafe self.header.count + let subtreeCount = unsafe self.header.subtreeCount + let depth = unsafe self.header.depth + let isLeaf = unsafe self.header.children == nil + let newStorage = Storage.create(withCapacity: capacity, isLeaf: isLeaf) - newStorage.header.count = count - newStorage.header.subtreeCount = subtreeCount - newStorage.header.depth = depth - - self.withUnsafeMutablePointerToElements { oldKeys in - newStorage.withUnsafeMutablePointerToElements { newKeys in - newKeys.initialize(from: oldKeys, count: count) + unsafe newStorage.header.count = count + unsafe newStorage.header.subtreeCount = subtreeCount + unsafe newStorage.header.depth = depth + + unsafe self.withUnsafeMutablePointerToElements { oldKeys in + unsafe newStorage.withUnsafeMutablePointerToElements { newKeys in + unsafe newKeys.initialize(from: oldKeys, count: count) } } if _Node.hasValues { - newStorage.header.values.unsafelyUnwrapped + unsafe newStorage.header.values.unsafelyUnwrapped .initialize( from: self.header.values.unsafelyUnwrapped, count: count ) } - newStorage.header.children? + unsafe newStorage.header.children? .initialize( from: self.header.children.unsafelyUnwrapped, count: count + 1 @@ -227,22 +238,22 @@ extension _Node { @inlinable deinit { - self.withUnsafeMutablePointers { header, elements in - let count = header.pointee.count - + unsafe self.withUnsafeMutablePointers { header, elements in + let count = unsafe header.pointee.count + if _Node.hasValues { - let values = header.pointee.values.unsafelyUnwrapped - values.deinitialize(count: count) - values.deallocate() + let values = unsafe header.pointee.values.unsafelyUnwrapped + unsafe values.deinitialize(count: count) + unsafe values.deallocate() } - if let children = header.pointee.children { - children.deinitialize(count: count + 1) - children.deallocate() + if let children = unsafe header.pointee.children { + unsafe children.deinitialize(count: count + 1) + unsafe children.deallocate() } - elements.deinitialize(count: header.pointee.count) + unsafe elements.deinitialize(count: header.pointee.count) } } } diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift index ccd48d78..1c042036 100644 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+CustomDebugStringConvertible.swift @@ -19,11 +19,11 @@ extension _Node.UnsafeHandle: CustomDebugStringConvertible { #if DEBUG private enum PrintPosition { case start, end, middle } private func indentDescription(_ _node: _Node.UnsafeHandle, position: PrintPosition) -> String { - let label = "(\(_node.elementCount)/\(_node.subtreeCount) \(_node.depth))" - + let label = unsafe "(\(_node.elementCount)/\(_node.subtreeCount) \(_node.depth))" + let spaces = String(repeating: " ", count: label.count) - let lines = describeNode(_node).split(separator: "\n") + let lines = unsafe describeNode(_node).split(separator: "\n") return lines.enumerated().map({ index, line in var lineToInsert = line let middle = (lines.count - 1) / 2 @@ -59,11 +59,11 @@ extension _Node.UnsafeHandle: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. private func describeNode(_ _node: _Node.UnsafeHandle) -> String { - if _node.elementCount == 0 { + if unsafe _node.elementCount == 0 { var result = "" if !_node.isLeaf { - _node[childAt: 0].read { handle in - result += indentDescription(handle, position: .start) + "\n" + unsafe _node[childAt: 0].read { handle in + result += unsafe indentDescription(handle, position: .start) + "\n" } result += "┗━ << EMPTY >>" @@ -74,19 +74,19 @@ extension _Node.UnsafeHandle: CustomDebugStringConvertible { } var result = "" - for slot in 0..<_node.elementCount { + for slot in unsafe 0..<_node.elementCount { if !_node.isLeaf { - let child = _node[childAt: slot] - let childDescription = child.read { - indentDescription($0, position: slot == 0 ? .start : .middle) + let child = unsafe _node[childAt: slot] + let childDescription = unsafe child.read { + unsafe indentDescription($0, position: slot == 0 ? .start : .middle) } result += childDescription + "\n" } if _node.isLeaf { - if _node.elementCount == 1 { + if unsafe _node.elementCount == 1 { result += "╺━ " - } else if slot == _node.elementCount - 1 { + } else if unsafe slot == _node.elementCount - 1 { result += "┗━ " } else if slot == 0 { result += "┏━ " @@ -98,15 +98,15 @@ extension _Node.UnsafeHandle: CustomDebugStringConvertible { } if _Node.hasValues { - debugPrint(_node[keyAt: slot], terminator: ": ", to: &result) - debugPrint(_node[valueAt: slot], terminator: "", to: &result) + debugPrint(unsafe _node[keyAt: slot], terminator: ": ", to: &result) + debugPrint(unsafe _node[valueAt: slot], terminator: "", to: &result) } else { - debugPrint(_node[keyAt: slot], terminator: "", to: &result) + debugPrint(unsafe _node[keyAt: slot], terminator: "", to: &result) } - if !_node.isLeaf && slot == _node.elementCount - 1 { - let childDescription = _node[childAt: slot + 1].read { - indentDescription($0, position: .end) + if unsafe !_node.isLeaf && slot == _node.elementCount - 1 { + let childDescription = unsafe _node[childAt: slot + 1].read { + unsafe indentDescription($0, position: .end) } result += "\n" + childDescription } @@ -118,7 +118,7 @@ extension _Node.UnsafeHandle: CustomDebugStringConvertible { /// A textual representation of this instance, suitable for debugging. public var debugDescription: String { - return indentDescription(self, position: .end) + return unsafe indentDescription(self, position: .end) } #else /// A textual representation of this instance, suitable for debugging. diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift index 2fb2564e..3cec498b 100644 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Deletion.swift @@ -29,30 +29,30 @@ extension _Node.UnsafeHandle { internal func removeAnyElement(forKey key: Key) -> _Node.Element? { assertMutable() - let slot = self.startSlot(forKey: key) - - if slot < self.elementCount && self[keyAt: slot] == key { + let slot = unsafe self.startSlot(forKey: key) + + if unsafe slot < self.elementCount && self[keyAt: slot] == key { // We have found the key if self.isLeaf { // Deletion within a leaf // removeElement(atSlot:) automatically adjusts node counts. - return self.removeElement(atSlot: slot) + return unsafe self.removeElement(atSlot: slot) } else { // Deletion within an internal node // TODO: potentially be smarter about using the predecessor or successor. - let predecessor = self[childAt: slot].update { $0.popLastElement() } - + let predecessor = unsafe self[childAt: slot].update { unsafe $0.popLastElement() } + // Reduce the element count. - self.subtreeCount -= 1 - + unsafe self.subtreeCount -= 1 + // Replace the current element with the predecessor. - let element = self.exchangeElement(atSlot: slot, with: predecessor) - + let element = unsafe self.exchangeElement(atSlot: slot, with: predecessor) + // Balance the predecessor child slot, as the pop operation may have // brought it out of balance. - self.balance(atSlot: slot) - + unsafe self.balance(atSlot: slot) + return element } } else { @@ -61,10 +61,10 @@ extension _Node.UnsafeHandle { // not exist. return nil } else { - assert(slot < self.childCount, "Attempt to remove from invalid child") - - let removedElement = self[childAt: slot].update({ - $0.removeAnyElement(forKey: key) + assert(unsafe slot < self.childCount, "Attempt to remove from invalid child") + + let removedElement = unsafe self[childAt: slot].update({ + unsafe $0.removeAnyElement(forKey: key) }) guard let removedElement = removedElement else { @@ -72,14 +72,14 @@ extension _Node.UnsafeHandle { return nil } - self.subtreeCount -= 1 - + unsafe self.subtreeCount -= 1 + // TODO: performing the remove and then balancing may result in an // extra memmove being performed. // Determine if the child needs to be rebalanced - self.balance(atSlot: slot) - + unsafe self.balance(atSlot: slot) + return removedElement } } @@ -96,49 +96,49 @@ extension _Node.UnsafeHandle { @inline(__always) internal func remove(at offset: Int) -> _Node.Element { assertMutable() - assert(0 <= offset && offset < self.subtreeCount, - "Cannot remove with out-of-bounds offset.") + assert(unsafe 0 <= offset && offset < self.subtreeCount, + "Cannot remove with out-of-bounds offset") if self.isLeaf { - return self.removeElement(atSlot: offset) + return unsafe self.removeElement(atSlot: offset) } // Removing from within an internal node var startIndex = 0 - for childSlot in 0.. _Node.Element { assertMutable() - + if self.isLeaf { // At a leaf, it is trivial to pop the last element // popLastElement(at:) automatically updates the counts. - return self.removeElement(atSlot: self.elementCount - 1) + return unsafe self.removeElement(atSlot: unsafe self.elementCount - 1) } // Remove the subtree's element - let poppedElement = self[childAt: self.childCount - 1].update { - $0.popLastElement() + let poppedElement = unsafe self[childAt: self.childCount - 1].update { + unsafe $0.popLastElement() } - self.subtreeCount -= 1 - - self.balance(atSlot: self.childCount - 1) + unsafe self.subtreeCount -= 1 + + unsafe self.balance(atSlot: self.childCount - 1) return poppedElement } } @@ -211,27 +211,30 @@ extension _Node.UnsafeHandle { @inlinable internal func balance(atSlot slot: Int) { assertMutable() - assert(0 <= slot && slot < self.childCount, - "Cannot balance out-of-bounds slot.") - assert(!self.isLeaf, "Cannot balance leaf.") + assert(unsafe 0 <= slot && slot < self.childCount, + "Cannot balance out-of-bounds slot") + assert(!self.isLeaf, "Cannot balance leaf") // No need to balance if the node is already balanced - if self[childAt: slot].read({ $0.isBalanced }) { return } - - if slot > 0 && self[childAt: slot - 1].read({ $0.isShrinkable }) { + if unsafe self[childAt: slot].read({ unsafe $0.isBalanced }) { return } + + if unsafe slot > 0 && self[childAt: slot - 1].read({ unsafe $0.isShrinkable }) { // We can rotate from the left node to the right node - self.rotateRight(atSlot: slot - 1) - } else if slot < self.childCount - 1 && - self[childAt: slot + 1].read({ $0.isShrinkable }) { + unsafe self.rotateRight(atSlot: slot - 1) + } + else if + unsafe slot < self.childCount - 1 + && self[childAt: slot + 1].read({ unsafe $0.isShrinkable }) + { // We can rotate from the right node to the left node - self.rotateLeft(atSlot: slot) - } else if slot == self.childCount - 1 { + unsafe self.rotateLeft(atSlot: slot) + } else if unsafe slot == self.childCount - 1 { // In the special case the deficient child at the end, // it'll be merged with it's left sibling. - self.collapse(atSlot: slot - 1) + unsafe self.collapse(atSlot: slot - 1) } else { // Otherwise collapse the child with its right sibling. - self.collapse(atSlot: slot) + unsafe self.collapse(atSlot: slot) } } @@ -245,21 +248,21 @@ extension _Node.UnsafeHandle { @inline(__always) package func rotateRight(atSlot slot: Int) { assertMutable() - assert(0 <= slot && slot < self.elementCount, - "Cannot rotate out-of-bounds slot.") + assert(unsafe 0 <= slot && slot < self.elementCount, + "Cannot rotate out-of-bounds slot") - self[childAt: slot].update { leftChild in - assert(leftChild.elementCount > 0, "Cannot rotate from empty node.") - + unsafe self[childAt: slot].update { leftChild in + assert(unsafe leftChild.elementCount > 0, "Cannot rotate from empty node") + // Move the old parent down to the right node - self[childAt: slot + 1].update { rightChild in - assert(rightChild.elementCount < rightChild.capacity, - "Rotating into full node.") + unsafe self[childAt: slot + 1].update { rightChild in + assert(unsafe rightChild.elementCount < rightChild.capacity, + "Rotating into full node") assert(leftChild.isLeaf == rightChild.isLeaf, - "Encountered subtrees of conflicting depth.") + "Encountered subtrees of conflicting depth") // Shift the rest of the elements right - rightChild.moveInitializeElements( + unsafe rightChild.moveInitializeElements( count: rightChild.elementCount, fromSlot: 0, toSlot: 1, of: rightChild @@ -267,10 +270,10 @@ extension _Node.UnsafeHandle { // Extract the parent's current element and move it down to the right // node - let oldParentElement = self.moveElement(atSlot: slot) + let oldParentElement = unsafe self.moveElement(atSlot: slot) if !rightChild.isLeaf { // Move the corresponding children to the right - rightChild.moveInitializeChildren( + unsafe rightChild.moveInitializeChildren( count: rightChild.childCount, fromSlot: 0, toSlot: 1, of: rightChild @@ -281,28 +284,28 @@ extension _Node.UnsafeHandle { // removeChild(atSlot:) takes care of adjusting the total element // counts. let newLeftChild: _Node = - leftChild.removeChild(atSlot: leftChild.childCount - 1) - + unsafe leftChild.removeChild(atSlot: leftChild.childCount - 1) + // Move the left child if applicable to the right node. - rightChild.initializeElement( + unsafe rightChild.initializeElement( atSlot: 0, to: oldParentElement, withLeftChild: newLeftChild ) - rightChild.subtreeCount += newLeftChild.read({ $0.subtreeCount }) + unsafe rightChild.subtreeCount += newLeftChild._subtreeCount } else { // Move the left child if applicable to the right node. - rightChild.initializeElement(atSlot: 0, to: oldParentElement) + unsafe rightChild.initializeElement(atSlot: 0, to: oldParentElement) } // Move the left node's key up to the parent // removeElement(atSlot:) takes care of adjusting the node counts. let newParentElement = - leftChild.removeElement(atSlot: leftChild.elementCount - 1) - self.initializeElement(atSlot: slot, to: newParentElement) - + unsafe leftChild.removeElement(atSlot: leftChild.elementCount - 1) + unsafe self.initializeElement(atSlot: slot, to: newParentElement) + // Adjust the element counts as applicable - rightChild.elementCount += 1 - rightChild.subtreeCount += 1 + unsafe rightChild.elementCount += 1 + unsafe rightChild.subtreeCount += 1 } } } @@ -317,49 +320,48 @@ extension _Node.UnsafeHandle { @inline(__always) package func rotateLeft(atSlot slot: Int) { assertMutable() - assert(0 <= slot && slot < self.elementCount, - "Cannot rotate out-of-bounds slot.") + assert(unsafe 0 <= slot && slot < self.elementCount, + "Cannot rotate out-of-bounds slot") - self[childAt: slot].update { leftChild in - assert(leftChild.elementCount < leftChild.capacity, - "Rotating into full node.") + unsafe self[childAt: slot].update { leftChild in + assert(unsafe leftChild.elementCount < leftChild.capacity, + "Rotating into full node") // Move the old parent down to the right node - self[childAt: slot + 1].update { rightChild in - assert(rightChild.elementCount > 0, "Cannot rotate from empty node.") + unsafe self[childAt: slot + 1].update { rightChild in + assert(unsafe rightChild.elementCount > 0, "Cannot rotate from empty node") assert(leftChild.isLeaf == rightChild.isLeaf, - "Encountered subtrees of conflicting depth.") + "Encountered subtrees of conflicting depth") // Move the right child if applicable to the left node. // We'll extract the first child of the right node, if it exists, // in order to cycle it. // Then, cycle the parent's element down to the left child - let oldParentElement = self.moveElement(atSlot: slot) + let oldParentElement = unsafe self.moveElement(atSlot: slot) if !leftChild.isLeaf { // removeChild(atSlot:) takes care of adjusting the node counts. - let newRightChild = rightChild.removeChild(atSlot: 0) - - leftChild.initializeElement( + let newRightChild = unsafe rightChild.removeChild(atSlot: 0) + + unsafe leftChild.initializeElement( atSlot: leftChild.elementCount, to: oldParentElement, - withRightChild: newRightChild - ) - + withRightChild: newRightChild) + // Adjust the total element counts - leftChild.subtreeCount += newRightChild.read({ $0.subtreeCount }) + unsafe leftChild.subtreeCount += newRightChild._subtreeCount } else { - leftChild.initializeElement( + unsafe leftChild.initializeElement( atSlot: leftChild.elementCount, to: oldParentElement ) } // Cycle the right child's element up to the parent. // removeElement(atSlot:) takes care of adjusting the node counts. - let newParentElement = rightChild.removeElement(atSlot: 0) - self.initializeElement(atSlot: slot, to: newParentElement) + let newParentElement = unsafe rightChild.removeElement(atSlot: 0) + unsafe self.initializeElement(atSlot: slot, to: newParentElement) - leftChild.elementCount += 1 - leftChild.subtreeCount += 1 + unsafe leftChild.elementCount += 1 + unsafe leftChild.subtreeCount += 1 } } } @@ -393,24 +395,23 @@ extension _Node.UnsafeHandle { @inlinable package func collapse(atSlot slot: Int) { assertMutable() - assert(0 <= slot && slot < self.elementCount, + assert(unsafe 0 <= slot && slot < self.elementCount, "Cannot collapse out-of-bounds slot") - assert(!self.isLeaf, "Cannot collapse a slot of a leaf node.") + assert(!self.isLeaf, "Cannot collapse a slot of a leaf node") - self[childAt: slot].update { leftChild in - var rightChild = self.moveChild(atSlot: slot + 1) - + unsafe self[childAt: slot].update { leftChild in + var rightChild = unsafe self.moveChild(atSlot: slot + 1) + // TODO: create optimized version that avoids a CoW copy for when the // right child is shared. - rightChild.update { rightChild in + unsafe rightChild.update { rightChild in // Ensure the left handle is large enough to contain all the items assert( - leftChild.capacity >= + unsafe leftChild.capacity >= leftChild.elementCount + rightChild.elementCount + 1, - "Left child undersized to contain collapsed subtree." - ) + "Left child undersized to contain collapsed subtree.") assert(leftChild.isLeaf == rightChild.isLeaf, - "Encountered subtrees of conflicting depth.") + "Encountered subtrees of conflicting depth") // Move the remaining children // ┌─┬─┬─┬─┐ @@ -418,11 +419,10 @@ extension _Node.UnsafeHandle { // └─┴─┴┬┴─┘ // ▲ │ // └─┘ - self.moveInitializeChildren( + unsafe self.moveInitializeChildren( count: self.elementCount - slot - 1, fromSlot: slot + 2, - toSlot: slot + 1, of: self - ) + toSlot: slot + 1, of: self) // Move the element from the parent into the the left child // @@ -439,15 +439,14 @@ extension _Node.UnsafeHandle { // └─┴─┴─┴─┴─┘ // The removeElement(atSlot:) takes care of adjusting the element // count on the parent. - leftChild.initializeElement( + unsafe leftChild.initializeElement( atSlot: leftChild.elementCount, - to: self.removeElement(atSlot: slot) - ) + to: self.removeElement(atSlot: slot)) // Increment the total element count since we merely moved the // parent element within the same subtree - self.subtreeCount += 1 - + unsafe self.subtreeCount += 1 + // TODO: might be more optimal to memcpy the right child, and avoid // potentially creating a CoW copy of it. @@ -464,31 +463,29 @@ extension _Node.UnsafeHandle { // ┌─┬─┬─┬─┬─┐ // │1│3│5│7│9│ // └─┴─┴─┴─┴─┘ - rightChild.moveInitializeElements( + unsafe rightChild.moveInitializeElements( count: rightChild.elementCount, fromSlot: 0, - toSlot: leftChild.elementCount + 1, of: leftChild - ) + toSlot: leftChild.elementCount + 1, of: leftChild) // Move the children of the right node to the left node if !rightChild.isLeaf { - rightChild.moveInitializeChildren( + unsafe rightChild.moveInitializeChildren( count: rightChild.childCount, fromSlot: 0, - toSlot: leftChild.elementCount + 1, of: leftChild - ) + toSlot: leftChild.elementCount + 1, of: leftChild) } // Adjust the child counts - leftChild.elementCount += rightChild.elementCount + 1 - leftChild.subtreeCount += rightChild.subtreeCount + 1 - + unsafe leftChild.elementCount += rightChild.elementCount + 1 + unsafe leftChild.subtreeCount += rightChild.subtreeCount + 1 + // Clear out the child counts for the right handle // TODO: As part of deletion, we probably already visited the right // node, so it's possible we just created a CoW copy of it, only do // deallocate it. Not a big deal but an inefficiency to note. - rightChild.elementCount = 0 - rightChild.drop() + unsafe rightChild.elementCount = 0 + unsafe rightChild.drop() } } } diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift index 784c7d6d..e7903087 100644 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle+Insertion.swift @@ -57,25 +57,25 @@ extension _Node.UnsafeHandle { ) -> UpdateResult { assertMutable() - let insertionIndex = self.endSlot(forKey: key) + let insertionIndex = unsafe self.endSlot(forKey: key) - if 0 < insertionIndex && insertionIndex <= self.elementCount && + if unsafe 0 < insertionIndex && insertionIndex <= self.elementCount && self[keyAt: insertionIndex - 1] == key { if updatingKey { // TODO: Potential transient ARC traffic here. - let oldKey = self.keys.advanced(by: insertionIndex - 1).pointee - + let oldKey = unsafe self.keys.advanced(by: insertionIndex - 1).pointee + let oldValue: Value if _Node.hasValues { - oldValue = self.pointerToValue(atSlot: insertionIndex - 1).move() - self.pointerToValue(atSlot: insertionIndex - 1).initialize(to: value) + oldValue = unsafe self.pointerToValue(atSlot: insertionIndex - 1).move() + unsafe self.pointerToValue(atSlot: insertionIndex - 1).initialize(to: value) } else { oldValue = _Node.dummyValue } return .updated(previousElement: (oldKey, oldValue)) } else { - let oldElement = self.exchangeElement( + let oldElement = unsafe self.exchangeElement( atSlot: insertionIndex - 1, with: (key, value) ) @@ -87,25 +87,25 @@ extension _Node.UnsafeHandle { // We need to try to insert as deep as possible as first, and have the splinter // bubble up. if self.isLeaf { - let maybeSplinter = self.insertElement( + let maybeSplinter = unsafe self.insertElement( (key, value), withRightChild: nil, atSlot: insertionIndex ) return UpdateResult(from: maybeSplinter) } else { - let result = self[childAt: insertionIndex].update { - $0.updateAnyValue(value, forKey: key, updatingKey: updatingKey) + let result = unsafe self[childAt: insertionIndex].update { + unsafe $0.updateAnyValue(value, forKey: key, updatingKey: updatingKey) } switch result { case .updated: return result case .splintered(let splinter): - let splinter = self.insertSplinter(splinter, atSlot: insertionIndex) + let splinter = unsafe self.insertSplinter(splinter, atSlot: insertionIndex) return UpdateResult(from: splinter) case .inserted: - self.subtreeCount += 1 + unsafe self.subtreeCount += 1 return .inserted } } @@ -133,165 +133,149 @@ extension _Node.UnsafeHandle { ) -> _Node.Splinter? { assertMutable() assert(self.isLeaf == (rightChild == nil), - "A child can only be inserted iff the node is a leaf.") + "A child can only be inserted iff the node is a leaf") // If we have a full B-Tree, we'll need to splinter - if self.elementCount == self.capacity { + if unsafe self.elementCount == self.capacity { // Right median == left median for BTrees with odd capacity - let rightMedian = self.elementCount / 2 - let leftMedian = (self.elementCount - 1) / 2 - + let rightMedian = unsafe self.elementCount / 2 + let leftMedian = unsafe (self.elementCount - 1) / 2 + var splinterElement: _Node.Element - var rightNode = _Node(withCapacity: self.capacity, isLeaf: self.isLeaf) - + var rightNode = _Node(withCapacity: unsafe self.capacity, isLeaf: self.isLeaf) + if insertionSlot == rightMedian { splinterElement = element let leftElementCount = rightMedian - let rightElementCount = self.elementCount - rightMedian + let rightElementCount = unsafe self.elementCount - rightMedian - rightNode.update { rightHandle in - self.moveInitializeElements( + unsafe rightNode.update { rightHandle in + unsafe self.moveInitializeElements( count: rightElementCount, fromSlot: rightMedian, - toSlot: 0, of: rightHandle - ) + toSlot: 0, of: rightHandle) if !self.isLeaf { - rightHandle.children.unsafelyUnwrapped + unsafe rightHandle.children.unsafelyUnwrapped .initialize(to: rightChild.unsafelyUnwrapped) - self.moveInitializeChildren( + unsafe self.moveInitializeChildren( count: rightElementCount, fromSlot: rightMedian + 1, - toSlot: 1, of: rightHandle - ) + toSlot: 1, of: rightHandle) } - self.elementCount = leftElementCount - rightHandle.elementCount = rightElementCount - rightHandle.depth = self.depth - - self._adjustSubtreeCount(afterSplittingTo: rightHandle) + unsafe self.elementCount = leftElementCount + unsafe rightHandle.elementCount = rightElementCount + unsafe rightHandle.depth = self.depth + + unsafe self._adjustSubtreeCount(afterSplittingTo: rightHandle) } } else if insertionSlot > rightMedian { // This branch is almost certainly correct - splinterElement = self.moveElement(atSlot: rightMedian) - + splinterElement = unsafe self.moveElement(atSlot: rightMedian) + let insertionSlotInRightNode = insertionSlot - (rightMedian + 1) - rightNode.update { rightHandle in - self.moveInitializeElements( + unsafe rightNode.update { rightHandle in + unsafe self.moveInitializeElements( count: insertionSlotInRightNode, fromSlot: rightMedian + 1, - toSlot: 0, of: rightHandle - ) + toSlot: 0, of: rightHandle) - self.moveInitializeElements( + unsafe self.moveInitializeElements( count: self.elementCount - insertionSlot, fromSlot: insertionSlot, - toSlot: insertionSlotInRightNode + 1, of: rightHandle - ) + toSlot: insertionSlotInRightNode + 1, of: rightHandle) if !self.isLeaf { - self.moveInitializeChildren( + unsafe self.moveInitializeChildren( count: insertionSlot - rightMedian, fromSlot: rightMedian + 1, - toSlot: 0, of: rightHandle - ) + toSlot: 0, of: rightHandle) - self.moveInitializeChildren( + unsafe self.moveInitializeChildren( count: self.elementCount - insertionSlot, fromSlot: insertionSlot + 1, - toSlot: insertionSlotInRightNode + 2, of: rightHandle - ) + toSlot: insertionSlotInRightNode + 2, of: rightHandle) } - rightHandle.initializeElement( + unsafe rightHandle.initializeElement( atSlot: insertionSlotInRightNode, to: element, - withRightChild: rightChild - ) + withRightChild: rightChild) - rightHandle.elementCount = self.elementCount - rightMedian - self.elementCount = rightMedian - rightHandle.depth = self.depth - - self._adjustSubtreeCount(afterSplittingTo: rightHandle) + unsafe rightHandle.elementCount = self.elementCount - rightMedian + unsafe self.elementCount = rightMedian + unsafe rightHandle.depth = self.depth + + unsafe self._adjustSubtreeCount(afterSplittingTo: rightHandle) } } else { // insertionSlot < rightMedian - splinterElement = self.moveElement(atSlot: leftMedian) - - rightNode.update { rightHandle in - self.moveInitializeElements( + splinterElement = unsafe self.moveElement(atSlot: leftMedian) + + unsafe rightNode.update { rightHandle in + unsafe self.moveInitializeElements( count: self.elementCount - leftMedian - 1, fromSlot: leftMedian + 1, - toSlot: 0, of : rightHandle - ) + toSlot: 0, of : rightHandle) - self.moveInitializeElements( + unsafe self.moveInitializeElements( count: leftMedian - insertionSlot, fromSlot: insertionSlot, - toSlot: insertionSlot + 1, of: self - ) + toSlot: insertionSlot + 1, of: self) if !self.isLeaf { - self.moveInitializeChildren( + unsafe self.moveInitializeChildren( count: self.elementCount - leftMedian, fromSlot: leftMedian + 1, - toSlot: 0, of: rightHandle - ) + toSlot: 0, of: rightHandle) - self.moveInitializeChildren( + unsafe self.moveInitializeChildren( count: leftMedian - insertionSlot, fromSlot: insertionSlot + 1, - toSlot: insertionSlot + 2, of: self - ) + toSlot: insertionSlot + 2, of: self) } - self.initializeElement( + unsafe self.initializeElement( atSlot: insertionSlot, - to: element, withRightChild: rightChild - ) + to: element, withRightChild: rightChild) - rightHandle.elementCount = self.elementCount - leftMedian - 1 - self.elementCount = leftMedian + 1 - rightHandle.depth = self.depth - - self._adjustSubtreeCount(afterSplittingTo: rightHandle) + unsafe rightHandle.elementCount = self.elementCount - leftMedian - 1 + unsafe self.elementCount = leftMedian + 1 + unsafe rightHandle.depth = self.depth + + unsafe self._adjustSubtreeCount(afterSplittingTo: rightHandle) } } return _Node.Splinter( element: splinterElement, - rightChild: rightNode - ) + rightChild: rightNode) } else { // TODO: potentially extract out this logic to reduce code duplication. // Shift over elements near the insertion slot. - self.moveInitializeElements( + unsafe self.moveInitializeElements( count: self.elementCount - insertionSlot, fromSlot: insertionSlot, - toSlot: insertionSlot + 1, of: self - ) + toSlot: insertionSlot + 1, of: self) if !self.isLeaf { - self.moveInitializeChildren( + unsafe self.moveInitializeChildren( count: self.childCount - insertionSlot - 1, fromSlot: insertionSlot + 1, - toSlot: insertionSlot + 2, of: self - ) + toSlot: insertionSlot + 2, of: self) } - self.initializeElement( + unsafe self.initializeElement( atSlot: insertionSlot, - to: element, withRightChild: rightChild - ) - - self.elementCount += 1 - self.subtreeCount += 1 + to: element, withRightChild: rightChild) + unsafe self.elementCount += 1 + unsafe self.subtreeCount += 1 + return nil } } @@ -313,11 +297,10 @@ extension _Node.UnsafeHandle { _ splinter: _Node.Splinter, atSlot insertionSlot: Int ) -> _Node.Splinter? { - return self.insertElement( + return unsafe self.insertElement( splinter.element, withRightChild: splinter.rightChild, - atSlot: insertionSlot - ) + atSlot: insertionSlot) } /// Recomputes the total amount of elements in two nodes. @@ -337,23 +320,23 @@ extension _Node.UnsafeHandle { assertMutable() rightHandle.assertMutable() - let originalTotalElements = self.subtreeCount + rightHandle.subtreeCount + let originalTotalElements = unsafe self.subtreeCount + rightHandle.subtreeCount var totalChildElements = 0 if !self.isLeaf { // Calculate total amount of child elements // TODO: potentially evaluate min(left.children, right.children), // but the cost of the branch will likely exceed the cost of 1 comparison - for i in 0..= 0, - "Cannot have negative number of child elements.") + "Cannot have negative number of child elements") - self.subtreeCount = self.elementCount + totalChildElements - rightHandle.subtreeCount = originalTotalElements - self.subtreeCount + unsafe self.subtreeCount = self.elementCount + totalChildElements + unsafe rightHandle.subtreeCount = originalTotalElements - self.subtreeCount } /// Concatenates a node of the same depth to end of the current node, potentially splintering. @@ -374,144 +357,132 @@ extension _Node.UnsafeHandle { separatedBy separator: __owned _Node.Element ) -> _Node.Splinter? { assertMutable() - let separator: _Node.Element? = rightNode.update { rightHandle in - assert(self.elementCount + rightHandle.elementCount <= 2 * self.capacity, - "Parameters are too large to concatenate.") - assert(self.depth == rightHandle.depth, + let separator: _Node.Element? = unsafe rightNode.update { rightHandle in + assert(unsafe self.elementCount + rightHandle.elementCount <= 2 * self.capacity, + "Parameters are too large to concatenate") + assert(unsafe self.depth == rightHandle.depth, "Cannot concatenate nodes of varying depths. See appendNode(_:separatedBy:)") - let totalElementCount = self.elementCount + rightHandle.elementCount + 1 - + let totalElementCount = unsafe self.elementCount + rightHandle.elementCount + 1 + // Identify if a splinter needs to occur - if totalElementCount > self.capacity { + if unsafe totalElementCount > self.capacity { // A splinter needs to occur // Split evenly (right biased). let separatorSlot = totalElementCount / 2 // Identify who needs to splinter - if separatorSlot == self.elementCount { + if unsafe separatorSlot == self.elementCount { // The nice case when the separator is the splinter return separator - } else if separatorSlot < self.elementCount { + } else if unsafe separatorSlot < self.elementCount { // Move elements from the left node to the right node - let splinterSeparator = self.moveElement(atSlot: separatorSlot) - - let shiftedElementCount = self.elementCount - separatorSlot - 1 - - rightHandle.moveInitializeElements( + let splinterSeparator = unsafe self.moveElement(atSlot: separatorSlot) + + let shiftedElementCount = unsafe self.elementCount - separatorSlot - 1 + + unsafe rightHandle.moveInitializeElements( count: rightHandle.elementCount, fromSlot: 0, toSlot: shiftedElementCount + 1, - of: rightHandle - ) + of: rightHandle) - rightHandle.initializeElement( + unsafe rightHandle.initializeElement( atSlot: shiftedElementCount, - to: separator - ) + to: separator) - self.moveInitializeElements( + unsafe self.moveInitializeElements( count: shiftedElementCount, fromSlot: separatorSlot + 1, toSlot: 0, - of: rightHandle - ) + of: rightHandle) if !self.isLeaf { - rightHandle.moveInitializeChildren( + unsafe rightHandle.moveInitializeChildren( count: rightHandle.childCount, fromSlot: 0, toSlot: shiftedElementCount + 1, - of: rightHandle - ) + of: rightHandle) - self.moveInitializeChildren( + unsafe self.moveInitializeChildren( count: shiftedElementCount + 1, fromSlot: separatorSlot + 1, toSlot: 0, - of: rightHandle - ) + of: rightHandle) } // TODO: adjust counts - self.elementCount = separatorSlot - rightHandle.elementCount = totalElementCount - separatorSlot - 1 - - self._adjustSubtreeCount(afterSplittingTo: rightHandle) - + unsafe self.elementCount = separatorSlot + unsafe rightHandle.elementCount = totalElementCount - separatorSlot - 1 + + unsafe self._adjustSubtreeCount(afterSplittingTo: rightHandle) + return splinterSeparator } else { // separatorSlot > self.elementCount // Move elements from the right node to the left node - let separatorSlotInRightHandle = separatorSlot - self.elementCount - 1 + let separatorSlotInRightHandle = unsafe separatorSlot - self.elementCount - 1 let splinterSeparator = - rightHandle.moveElement(atSlot: separatorSlotInRightHandle) - - self.initializeElement( + unsafe rightHandle.moveElement(atSlot: separatorSlotInRightHandle) + + unsafe self.initializeElement( atSlot: self.elementCount, - to: separator - ) + to: separator) - rightHandle.moveInitializeElements( + unsafe rightHandle.moveInitializeElements( count: separatorSlotInRightHandle, fromSlot: 0, toSlot: self.elementCount + 1, - of: self - ) + of: self) - rightHandle.moveInitializeElements( + unsafe rightHandle.moveInitializeElements( count: rightHandle.elementCount - (separatorSlotInRightHandle + 1), fromSlot: separatorSlotInRightHandle + 1, toSlot: 0, - of: rightHandle - ) + of: rightHandle) if !self.isLeaf { - rightHandle.moveInitializeChildren( + unsafe rightHandle.moveInitializeChildren( count: separatorSlotInRightHandle + 1, fromSlot: 0, toSlot: self.childCount, - of: self - ) + of: self) } - self.elementCount = separatorSlot - rightHandle.elementCount = totalElementCount - separatorSlot - 1 - - self._adjustSubtreeCount(afterSplittingTo: rightHandle) - + unsafe self.elementCount = separatorSlot + unsafe rightHandle.elementCount = totalElementCount - separatorSlot - 1 + + unsafe self._adjustSubtreeCount(afterSplittingTo: rightHandle) + return splinterSeparator } } else { // A simple merge can be performed - self.initializeElement( + unsafe self.initializeElement( atSlot: self.elementCount, - to: separator - ) - - rightHandle.moveInitializeElements( + to: separator) + + unsafe rightHandle.moveInitializeElements( count: rightHandle.elementCount, fromSlot: 0, toSlot: self.elementCount + 1, - of: self - ) + of: self) if !self.isLeaf { - rightHandle.moveInitializeChildren( + unsafe rightHandle.moveInitializeChildren( count: rightHandle.childCount, fromSlot: 0, toSlot: self.childCount, - of: self - ) + of: self) } - self.elementCount += rightHandle.elementCount + 1 - self.subtreeCount += rightHandle.subtreeCount + 1 - - rightHandle.elementCount = 0 - rightHandle.drop() - + unsafe self.elementCount += rightHandle.elementCount + 1 + unsafe self.subtreeCount += rightHandle.subtreeCount + 1 + + unsafe rightHandle.elementCount = 0 + unsafe rightHandle.drop() + return nil } } diff --git a/Sources/SortedCollections/BTree/_Node.UnsafeHandle.swift b/Sources/SortedCollections/BTree/_Node.UnsafeHandle.swift index dcff3241..44b57db7 100644 --- a/Sources/SortedCollections/BTree/_Node.UnsafeHandle.swift +++ b/Sources/SortedCollections/BTree/_Node.UnsafeHandle.swift @@ -41,6 +41,7 @@ extension _Node { /// Check ``_Node.hasValues`` before performing such operations. Note that element-wise /// operations of the handle already perform such value checks and this step is not necessary. @usableFromInline + @unsafe package struct UnsafeHandle { @usableFromInline package let header: UnsafeMutablePointer
@@ -54,6 +55,12 @@ extension _Node { @usableFromInline package let children: UnsafeMutablePointer<_Node>? +#if COLLECTIONS_INTERNAL_CHECKS + @usableFromInline + @safe + internal let _isMutable: Bool +#endif + @inlinable @inline(__always) internal init( @@ -63,24 +70,19 @@ extension _Node { header: UnsafeMutablePointer
, isMutable: Bool ) { - self.keys = keys - self.values = values - self.children = children - self.header = header - + unsafe self.keys = keys + unsafe self.values = values + unsafe self.children = children + unsafe self.header = header + #if COLLECTIONS_INTERNAL_CHECKS self._isMutable = isMutable #endif } - // MARK: Mutability Checks - #if COLLECTIONS_INTERNAL_CHECKS - @usableFromInline - internal let _isMutable: Bool - #endif - @inlinable @inline(__always) + @safe internal var isMutable: Bool { #if COLLECTIONS_INTERNAL_CHECKS return _isMutable @@ -96,6 +98,7 @@ extension _Node { /// Note that this is a noop in release builds. @inlinable @inline(__always) + @safe internal func assertMutable() { #if COLLECTIONS_INTERNAL_CHECKS assert(self._isMutable, @@ -109,7 +112,7 @@ extension _Node { @usableFromInline internal func checkInvariants() { assert(depth != 0 || self.isLeaf, - "Cannot have non-leaf of zero depth.") + "Cannot have non-leaf of zero depth") } #else @inlinable @@ -122,7 +125,7 @@ extension _Node { @inlinable @inline(__always) internal init(mutating handle: UnsafeHandle) { - self.init( + unsafe self.init( keys: handle.keys, values: handle.values, children: handle.children, @@ -134,23 +137,31 @@ extension _Node { // MARK: Convenience properties @inlinable @inline(__always) - internal var capacity: Int { header.pointee.capacity } - + internal var capacity: Int { unsafe header.pointee.capacity } + /// The number of elements immediately stored in the node @inlinable @inline(__always) package var elementCount: Int { - get { header.pointee.count } - nonmutating set { assertMutable(); header.pointee.count = newValue } + get { + unsafe header.pointee.count + } + nonmutating set { + assertMutable() + unsafe header.pointee.count = newValue + } } /// The total number of elements that this node directly or indirectly stores @inlinable @inline(__always) package var subtreeCount: Int { - get { header.pointee.subtreeCount } + get { + unsafe header.pointee.subtreeCount + } nonmutating set { - assertMutable(); header.pointee.subtreeCount = newValue + assertMutable() + unsafe header.pointee.subtreeCount = newValue } } @@ -158,9 +169,12 @@ extension _Node { @inlinable @inline(__always) package var depth: Int { - get { header.pointee.depth } + get { + unsafe header.pointee.depth + } nonmutating set { - assertMutable(); header.pointee.depth = newValue + assertMutable() + unsafe header.pointee.depth = newValue } } @@ -169,8 +183,8 @@ extension _Node { @inlinable @inline(__always) package var childCount: Int { - assert(!isLeaf, "Cannot access the child count on a leaf.") - return elementCount &+ 1 + assert(!isLeaf, "Cannot access the child count on a leaf") + return unsafe elementCount &+ 1 } /// Whether the node is the bottom-most node (a leaf) within its tree. @@ -179,29 +193,30 @@ extension _Node { /// calling certain operations which depend on children may trap. @inlinable @inline(__always) - package var isLeaf: Bool { children == nil } - + @safe + package var isLeaf: Bool { unsafe children == nil } + /// A lower bound on the amount of keys we would want a node to contain. /// /// Defined as `ceil(capacity/2) - 1`. @inlinable @inline(__always) - package var minimumElementCount: Int { capacity / 2 } + package var minimumElementCount: Int { unsafe capacity / 2 } /// Whether an element can be removed without triggering a rebalance. @inlinable @inline(__always) - package var isShrinkable: Bool { elementCount > minimumElementCount } + package var isShrinkable: Bool { unsafe elementCount > minimumElementCount } /// Whether the node contains at least the minimum number of keys. @inlinable @inline(__always) - package var isBalanced: Bool { elementCount >= minimumElementCount } + package var isBalanced: Bool { unsafe elementCount >= minimumElementCount } /// Whether the immediate node does not have space for an additional element @inlinable @inline(__always) - package var isFull: Bool { elementCount == capacity } + package var isFull: Bool { unsafe elementCount == capacity } /// Checks uniqueness of a child. @@ -210,8 +225,8 @@ extension _Node { @inlinable @inline(__always) package func isChildUnique(atSlot slot: Int) -> Bool { - assert(!self.isLeaf, "Cannot access children on leaf.") - return isKnownUniquelyReferenced( + assert(!self.isLeaf, "Cannot access children on leaf") + return unsafe isKnownUniquelyReferenced( &self.pointerToChild(atSlot: slot).pointee._storage ) } @@ -224,9 +239,9 @@ extension _Node { @inline(__always) package func drop() { assertMutable() - assert(self.elementCount == 0, "Cannot drop non-empty node") - self.header.pointee.children?.deallocate() - self.header.pointee.children = nil + assert(unsafe self.elementCount == 0, "Cannot drop non-empty node") + unsafe self.header.pointee.children?.deallocate() + unsafe self.header.pointee.children = nil } } } @@ -237,12 +252,13 @@ extension _Node.UnsafeHandle { @inline(__always) package subscript(elementAt slot: Int) -> _Node.Element { get { - assert(0 <= slot && slot < self.elementCount, - "Node element subscript out of bounds.") + assert( + unsafe 0 <= slot && slot < self.elementCount, + "Node element subscript out of bounds") if _Node.hasValues { - return (key: self[keyAt: slot], value: self[valueAt: slot]) + return unsafe (key: self[keyAt: slot], value: self[valueAt: slot]) } else { - return (key: self[keyAt: slot], value: _Node.dummyValue) + return unsafe (key: self[keyAt: slot], value: _Node.dummyValue) } } } @@ -253,18 +269,20 @@ extension _Node.UnsafeHandle { package func pointerToKey( atSlot slot: Int ) -> UnsafeMutablePointer { - assert(0 <= slot && slot < self.elementCount, - "Node key slot out of bounds.") - return self.keys.advanced(by: slot) + assert( + unsafe 0 <= slot && slot < self.elementCount, + "Node key slot out of bounds") + return unsafe self.keys.advanced(by: slot) } @inlinable @inline(__always) package subscript(keyAt slot: Int) -> Key { get { - assert(0 <= slot && slot < self.elementCount, - "Node key subscript out of bounds.") - return self.keys[slot] + assert( + unsafe 0 <= slot && slot < self.elementCount, + "Node key subscript out of bounds") + return unsafe self.keys[slot] } } @@ -274,30 +292,31 @@ extension _Node.UnsafeHandle { package func pointerToValue( atSlot slot: Int ) -> UnsafeMutablePointer { - assert(0 <= slot && slot < elementCount, - "Node value slot out of bounds.") - assert(_Node.hasValues, "Node does not have value buffer.") - return values.unsafelyUnwrapped.advanced(by: slot) + assert( + unsafe 0 <= slot && slot < elementCount, + "Node value slot out of bounds") + assert(_Node.hasValues, "Node does not have value buffer") + return unsafe values.unsafelyUnwrapped.advanced(by: slot) } @inlinable @inline(__always) package subscript(valueAt slot: Int) -> Value { get { - assert(0 <= slot && slot < self.elementCount, - "Node values subscript out of bounds.") - assert(_Node.hasValues, "Node does not have value buffer.") - return self.pointerToValue(atSlot: slot).pointee + assert(unsafe 0 <= slot && slot < self.elementCount, + "Node values subscript out of bounds") + assert(_Node.hasValues, "Node does not have value buffer") + return unsafe self.pointerToValue(atSlot: slot).pointee } nonmutating _modify { assertMutable() - assert(0 <= slot && slot < self.elementCount, - "Node values subscript out of bounds.") - assert(_Node.hasValues, "Node does not have value buffer.") - var value = self.pointerToValue(atSlot: slot).move() + assert(unsafe 0 <= slot && slot < self.elementCount, + "Node values subscript out of bounds") + assert(_Node.hasValues, "Node does not have value buffer") + var value = unsafe self.pointerToValue(atSlot: slot).move() + defer { unsafe self.pointerToValue(atSlot: slot).initialize(to: value) } yield &value - self.pointerToValue(atSlot: slot).initialize(to: value) } } @@ -306,10 +325,10 @@ extension _Node.UnsafeHandle { package func pointerToChild( atSlot slot: Int ) -> UnsafeMutablePointer<_Node> { - assert(0 <= slot && slot < self.childCount, - "Node child slot out of bounds.") - assert(!isLeaf, "Cannot access children of leaf node.") - return self.children.unsafelyUnwrapped.advanced(by: slot) + assert(unsafe 0 <= slot && slot < self.childCount, + "Node child slot out of bounds") + assert(!isLeaf, "Cannot access children of leaf node") + return unsafe self.children.unsafelyUnwrapped.advanced(by: slot) } /// Returns the child at a given slot as a Node object @@ -318,20 +337,20 @@ extension _Node.UnsafeHandle { @inline(__always) package subscript(childAt slot: Int) -> _Node { get { - assert(!isLeaf, "Cannot access children of leaf node.") - assert(0 <= slot && slot < self.childCount, + assert(!isLeaf, "Cannot access children of leaf node") + assert(unsafe 0 <= slot && slot < self.childCount, "Node child subscript out of bounds") - return self.children.unsafelyUnwrapped[slot] + return unsafe self.children.unsafelyUnwrapped[slot] } nonmutating _modify { assertMutable() - assert(!isLeaf, "Cannot modify children of leaf node.") - assert(0 <= slot && slot < self.childCount, + assert(!isLeaf, "Cannot modify children of leaf node") + assert(unsafe 0 <= slot && slot < self.childCount, "Node child subscript out of bounds") - var child = self.children.unsafelyUnwrapped.advanced(by: slot).move() + var child = unsafe self.children.unsafelyUnwrapped.advanced(by: slot).move() defer { - self.children.unsafelyUnwrapped.advanced(by: slot).initialize(to: child) + unsafe self.children.unsafelyUnwrapped.advanced(by: slot).initialize(to: child) } yield &child } @@ -348,13 +367,13 @@ extension _Node.UnsafeHandle { @inlinable package func startSlot(forKey key: Key) -> Int { var start: Int = 0 - var end: Int = self.elementCount - + var end: Int = unsafe self.elementCount + while end > start { let mid = (end &- start) / 2 &+ start // TODO: make this info a conditional_mov - if key <= self.keys[mid] { + if unsafe key <= self.keys[mid] { end = mid } else { start = mid &+ 1 @@ -372,12 +391,12 @@ extension _Node.UnsafeHandle { @inlinable package func endSlot(forKey key: Key) -> Int { var start: Int = 0 - var end: Int = self.elementCount - + var end: Int = unsafe self.elementCount + while end > start { let mid = (end &- start) / 2 &+ start - if key >= self.keys[mid] { + if unsafe key >= self.keys[mid] { start = mid &+ 1 } else { end = mid @@ -409,22 +428,22 @@ extension _Node.UnsafeHandle { toSlot destinationSlot: Int, of target: _Node.UnsafeHandle ) { - assert(sourceSlot >= 0, "Move source slot must be positive.") - assert(destinationSlot >= 0, "Move destination slot must be positive.") - assert(count >= 0, "Amount of elements to move be positive.") - assert(sourceSlot + count <= self.capacity, - "Cannot move elements beyond source buffer capacity.") - assert(destinationSlot + count <= target.capacity, - "Cannot move elements beyond destination buffer capacity.") + assert(sourceSlot >= 0, "Move source slot must be positive") + assert(destinationSlot >= 0, "Move destination slot must be positive") + assert(count >= 0, "Amount of elements to move be positive") + assert(unsafe sourceSlot + count <= self.capacity, + "Cannot move elements beyond source buffer capacity") + assert(unsafe destinationSlot + count <= target.capacity, + "Cannot move elements beyond destination buffer capacity") self.assertMutable() target.assertMutable() - target.keys.advanced(by: destinationSlot) + unsafe target.keys.advanced(by: destinationSlot) .moveInitialize(from: self.keys.advanced(by: sourceSlot), count: count) if _Node.hasValues { - target.values.unsafelyUnwrapped.advanced(by: destinationSlot) + unsafe target.values.unsafelyUnwrapped.advanced(by: destinationSlot) .moveInitialize( from: self.values.unsafelyUnwrapped.advanced(by: sourceSlot), count: count @@ -452,13 +471,13 @@ extension _Node.UnsafeHandle { toSlot destinationSlot: Int, of target: _Node.UnsafeHandle ) { - assert(sourceSlot >= 0, "Move source slot must be positive.") - assert(destinationSlot >= 0, "Move destination slot must be positive.") - assert(count >= 0, "Amount of children to move be positive.") - assert(sourceSlot + count <= self.capacity + 1, - "Cannot move children beyond source buffer capacity.") - assert(destinationSlot + count <= target.capacity + 1, - "Cannot move children beyond destination buffer capacity.") + assert(sourceSlot >= 0, "Move source slot must be positive") + assert(destinationSlot >= 0, "Move destination slot must be positive") + assert(count >= 0, "Amount of children to move be positive") + assert(unsafe sourceSlot + count <= self.capacity + 1, + "Cannot move children beyond source buffer capacity") + assert(unsafe destinationSlot + count <= target.capacity + 1, + "Cannot move children beyond destination buffer capacity") assert(!target.isLeaf, "Cannot move children to a leaf node") assert(!self.isLeaf, "Cannot move children from a leaf node") @@ -466,9 +485,9 @@ extension _Node.UnsafeHandle { target.assertMutable() let sourcePointer = - self.children.unsafelyUnwrapped.advanced(by: sourceSlot) - - target.children.unsafelyUnwrapped.advanced(by: destinationSlot) + unsafe self.children.unsafelyUnwrapped.advanced(by: sourceSlot) + + unsafe target.children.unsafelyUnwrapped.advanced(by: destinationSlot) .moveInitialize(from: sourcePointer, count: count) } @@ -491,15 +510,15 @@ extension _Node.UnsafeHandle { withRightChild rightChild: _Node? ) { assertMutable() - assert(0 <= slot && slot < self.capacity, - "Cannot insert beyond node capacity.") + assert(unsafe 0 <= slot && slot < self.capacity, + "Cannot insert beyond node capacity") assert(self.isLeaf == (rightChild == nil), - "A child can only be inserted iff the node is a leaf.") - - self.initializeElement(atSlot: slot, to: element) + "A child can only be inserted iff the node is a leaf") + unsafe self.initializeElement(atSlot: slot, to: element) + if let rightChild = rightChild { - self.children.unsafelyUnwrapped + unsafe self.children.unsafelyUnwrapped .advanced(by: slot + 1) .initialize(to: rightChild) } @@ -524,15 +543,15 @@ extension _Node.UnsafeHandle { withLeftChild leftChild: _Node? ) { assertMutable() - assert(0 <= slot && slot < self.capacity, - "Cannot insert beyond node capacity.") + assert(unsafe 0 <= slot && slot < self.capacity, + "Cannot insert beyond node capacity") assert(self.isLeaf == (leftChild == nil), - "A child can only be inserted iff the node is a leaf.") - - self.initializeElement(atSlot: slot, to: element) + "A child can only be inserted iff the node is a leaf") + unsafe self.initializeElement(atSlot: slot, to: element) + if let leftChild = leftChild { - self.children.unsafelyUnwrapped + unsafe self.children.unsafelyUnwrapped .advanced(by: slot) .initialize(to: leftChild) } @@ -548,12 +567,12 @@ extension _Node.UnsafeHandle { @inline(__always) package func initializeElement(atSlot slot: Int, to element: _Node.Element) { assertMutable() - assert(0 <= slot && slot < self.capacity, - "Cannot insert beyond node capacity.") + assert(unsafe 0 <= slot && slot < self.capacity, + "Cannot insert beyond node capacity") - self.keys.advanced(by: slot).initialize(to: element.key) + unsafe self.keys.advanced(by: slot).initialize(to: element.key) if _Node.hasValues { - self.values.unsafelyUnwrapped.advanced(by: slot).initialize(to: element.value) + unsafe self.values.unsafelyUnwrapped.advanced(by: slot).initialize(to: element.value) } } @@ -572,10 +591,10 @@ extension _Node.UnsafeHandle { @inline(__always) package func moveElement(atSlot slot: Int) -> _Node.Element { assertMutable() - assert(0 <= slot && slot < self.elementCount, - "Attempted to move out-of-bounds element.") + assert(unsafe 0 <= slot && slot < self.elementCount, + "Attempted to move out-of-bounds element") - return ( + return unsafe ( key: self.pointerToKey(atSlot: slot).move(), value: _Node.hasValues ? self.pointerToValue(atSlot: slot).move() @@ -595,11 +614,11 @@ extension _Node.UnsafeHandle { @inline(__always) package func moveChild(atSlot slot: Int) -> _Node { assertMutable() - assert(!self.isLeaf, "Can only move a child on a non-leaf node.") - assert(0 <= slot && slot < self.childCount, - "Attempted to move out-of-bounds child.") + assert(!self.isLeaf, "Can only move a child on a non-leaf node") + assert(unsafe 0 <= slot && slot < self.childCount, + "Attempted to move out-of-bounds child") - return self.children.unsafelyUnwrapped.advanced(by: slot).move() + return unsafe self.children.unsafelyUnwrapped.advanced(by: slot).move() } /// Appends a new element. @@ -607,14 +626,14 @@ extension _Node.UnsafeHandle { @inline(__always) package func appendElement(_ element: _Node.Element) { assertMutable() - assert(elementCount < capacity, "Cannot append into full node") - assert(elementCount == 0 || self[keyAt: elementCount - 1] <= element.key, - "Cannot append out-of-order element.") + assert(unsafe elementCount < capacity, "Cannot append into full node") + assert(unsafe elementCount == 0 || self[keyAt: elementCount - 1] <= element.key, + "Cannot append out-of-order element") - initializeElement(atSlot: elementCount, to: element) - - elementCount += 1 - subtreeCount += 1 + unsafe initializeElement(atSlot: elementCount, to: element) + + unsafe elementCount += 1 + unsafe subtreeCount += 1 } @@ -623,21 +642,22 @@ extension _Node.UnsafeHandle { @inline(__always) package func appendElement( _ element: _Node.Element, - withRightChild rightChild: _Node) { + withRightChild rightChild: _Node + ) { assertMutable() - assert(!self.isLeaf, "Cannot append on leaf.") - assert(elementCount < capacity, "Cannot append into full node") - assert(elementCount == 0 || self[keyAt: elementCount - 1] <= element.key, - "Cannot append out-of-order element.") + assert(!self.isLeaf, "Cannot append on leaf") + assert(unsafe elementCount < capacity, "Cannot append into full node") + assert(unsafe elementCount == 0 || self[keyAt: elementCount - 1] <= element.key, + "Cannot append out-of-order element") - initializeElement( + unsafe initializeElement( atSlot: elementCount, to: element, withRightChild: rightChild ) - elementCount += 1 - subtreeCount += 1 + rightChild.storage.header.subtreeCount + unsafe elementCount += 1 + unsafe subtreeCount += 1 + rightChild.storage.header.subtreeCount } /// Swaps the element at a given slot, returning the old one. @@ -653,11 +673,11 @@ extension _Node.UnsafeHandle { with newElement: _Node.Element ) -> _Node.Element { assertMutable() - assert(0 <= slot && slot < self.elementCount, - "Attempted to swap out-of-bounds element.") + assert(unsafe 0 <= slot && slot < self.elementCount, + "Attempted to swap out-of-bounds element") - let oldElement = self.moveElement(atSlot: slot) - self.initializeElement(atSlot: slot, to: newElement) + let oldElement = unsafe self.moveElement(atSlot: slot) + unsafe self.initializeElement(atSlot: slot, to: newElement) return oldElement } @@ -674,12 +694,12 @@ extension _Node.UnsafeHandle { with newChild: _Node ) -> _Node { assertMutable() - assert(!self.isLeaf, "Cannot exchange children on a leaf node.") - assert(0 <= slot && slot < self.childCount, - "Attempted to swap out-of-bounds element.") + assert(!self.isLeaf, "Cannot exchange children on a leaf node") + assert(unsafe 0 <= slot && slot < self.childCount, + "Attempted to swap out-of-bounds element") - let oldChild = self.moveChild(atSlot: slot) - self.pointerToChild(atSlot: slot).initialize(to: newChild) + let oldChild = unsafe self.moveChild(atSlot: slot) + unsafe self.pointerToChild(atSlot: slot).initialize(to: newChild) return oldChild } @@ -702,20 +722,19 @@ extension _Node.UnsafeHandle { @inline(__always) package func removeChild(atSlot slot: Int) -> _Node { assertMutable() - assert(0 <= slot && slot < self.childCount, - "Attempt to remove out-of-bounds child.") - - let child = self.moveChild(atSlot: slot) + assert(unsafe 0 <= slot && slot < self.childCount, + "Attempt to remove out-of-bounds child") + let child = unsafe self.moveChild(atSlot: slot) + // Shift everything else over to the left - self.moveInitializeChildren( + unsafe self.moveInitializeChildren( count: self.childCount - slot - 1, fromSlot: slot + 1, - toSlot: slot, of: self - ) - - self.subtreeCount -= child.read({ $0.subtreeCount }) + toSlot: slot, of: self) + unsafe self.subtreeCount -= child._subtreeCount + return child } @@ -734,21 +753,21 @@ extension _Node.UnsafeHandle { @discardableResult package func removeElement(atSlot slot: Int) -> _Node.Element { assertMutable() - assert(0 <= slot && slot < self.elementCount, - "Attempt to remove out-of-bounds element.") - - let element = self.moveElement(atSlot: slot) + assert(unsafe 0 <= slot && slot < self.elementCount, + "Attempt to remove out-of-bounds element") + let element = unsafe self.moveElement(atSlot: slot) + // Shift everything else over to the left - self.moveInitializeElements( + unsafe self.moveInitializeElements( count: self.elementCount - slot - 1, fromSlot: slot + 1, toSlot: slot, of: self ) - self.elementCount -= 1 - self.subtreeCount -= 1 - + unsafe self.elementCount -= 1 + unsafe self.subtreeCount -= 1 + return element } @@ -769,21 +788,21 @@ extension _Node.UnsafeHandle { @discardableResult package func removeElementWithoutValue(atSlot slot: Int) -> Key { assertMutable() - assert(0 <= slot && slot < self.elementCount, - "Attempt to remove out-of-bounds element.") - - let key = self.pointerToKey(atSlot: slot).move() + assert(unsafe 0 <= slot && slot < self.elementCount, + "Attempt to remove out-of-bounds element") + let key = unsafe self.pointerToKey(atSlot: slot).move() + // Shift everything else over to the left - self.moveInitializeElements( + unsafe self.moveInitializeElements( count: self.elementCount - slot - 1, fromSlot: slot + 1, toSlot: slot, of: self ) - self.elementCount -= 1 - self.subtreeCount -= 1 - + unsafe self.elementCount -= 1 + unsafe self.subtreeCount -= 1 + return key } } diff --git a/Sources/SortedCollections/BTree/_Node.swift b/Sources/SortedCollections/BTree/_Node.swift index c85055cb..d4fc7df4 100644 --- a/Sources/SortedCollections/BTree/_Node.swift +++ b/Sources/SortedCollections/BTree/_Node.swift @@ -34,6 +34,7 @@ /// Refer to ``_Node.UnsafeHandle`` for the APIs available when operating on a node in such a /// manner. @usableFromInline +@safe package struct _Node { @usableFromInline package typealias Element = (key: Key, value: Value) @@ -49,8 +50,8 @@ package struct _Node { /// Strong reference to the node's underlying data @inlinable @inline(__always) - internal var storage: Storage { _storage.unsafelyUnwrapped } - + internal var storage: Storage { unsafe _storage.unsafelyUnwrapped } + /// An instance of a ``_Node`` with no underlying storage allocated. /// /// Use this when you need a dummy node. It is invalid to ever attempt to read or write to this node. @@ -84,25 +85,25 @@ package struct _Node { capacity: Int ) { assert( - leftChild.storage.header.depth == rightChild.storage.header.depth, + unsafe leftChild.storage.header.depth == rightChild.storage.header.depth, "Left and right nodes of a splinter must have equal depth" ) self.init(withCapacity: capacity, isLeaf: false) - self.storage.updateGuaranteedUnique { handle in - handle.keys.initialize(to: separator.key) + unsafe self.storage.updateGuaranteedUnique { handle in + unsafe handle.keys.initialize(to: separator.key) if _Node.hasValues { - handle.values.unsafelyUnwrapped.initialize(to: separator.value) + unsafe handle.values.unsafelyUnwrapped.initialize(to: separator.value) } - handle.children.unsafelyUnwrapped.initialize(to: leftChild) - handle.children.unsafelyUnwrapped.advanced(by: 1).initialize(to: rightChild) - - handle.elementCount = 1 - handle.subtreeCount = 1 + + unsafe handle.children.unsafelyUnwrapped.initialize(to: leftChild) + unsafe handle.children.unsafelyUnwrapped.advanced(by: 1).initialize(to: rightChild) + + unsafe handle.elementCount = 1 + unsafe handle.subtreeCount = 1 + leftChild.storage.header.subtreeCount + rightChild.storage.header.subtreeCount - handle.depth = leftChild.storage.header.depth + 1 + unsafe handle.depth = leftChild.storage.header.depth + 1 } } @@ -113,53 +114,53 @@ package struct _Node { mappingFrom existingNode: _Node, _ transform: (T) throws -> Value ) rethrows { - let isLeaf = existingNode.storage.header.children == nil + let isLeaf = unsafe existingNode.storage.header.children == nil _storage = .create( - withCapacity: existingNode.storage.header.capacity, + withCapacity: unsafe existingNode.storage.header.capacity, isLeaf: isLeaf ) - let elementCount = existingNode.storage.header.count - storage.header.count = elementCount - storage.header.subtreeCount = existingNode.storage.header.subtreeCount - - storage.withUnsafeMutablePointerToElements { keys in - existingNode.storage.withUnsafeMutablePointerToElements { sourceKeys in - keys.initialize(from: sourceKeys, count: existingNode.storage.header.count) + let elementCount = unsafe existingNode.storage.header.count + unsafe storage.header.count = elementCount + unsafe storage.header.subtreeCount = existingNode.storage.header.subtreeCount + + unsafe storage.withUnsafeMutablePointerToElements { keys in + unsafe existingNode.storage.withUnsafeMutablePointerToElements { sourceKeys in + unsafe keys.initialize(from: sourceKeys, count: existingNode.storage.header.count) } } for i in 0...dummyValue ) - storage.header.values.unsafelyUnwrapped + unsafe storage.header.values.unsafelyUnwrapped .advanced(by: i) .initialize(to: newValue) } if !isLeaf { - let oldChild = existingNode.storage.header + let oldChild = unsafe existingNode.storage.header .children.unsafelyUnwrapped .advanced(by: i) .pointee - storage.header.children.unsafelyUnwrapped + unsafe storage.header.children.unsafelyUnwrapped .advanced(by: i) .initialize(to: try _Node(mappingFrom: oldChild, transform)) } } if !isLeaf { - let oldChild = existingNode.storage.header + let oldChild = unsafe existingNode.storage.header .children.unsafelyUnwrapped .advanced(by: elementCount) .pointee - storage.header.children.unsafelyUnwrapped + unsafe storage.header.children.unsafelyUnwrapped .advanced(by: elementCount) .initialize(to: try _Node(mappingFrom: oldChild, transform)) } @@ -193,7 +194,7 @@ package struct _Node { @inline(__always) internal static var dummyValue: Value { assert(!hasValues, "Cannot get dummy value on tree with value buffer.") - return unsafeBitCast((), to: Value.self) + return unsafe unsafeBitCast((), to: Value.self) } } @@ -219,29 +220,29 @@ extension _Node { separatedBy separator: __owned _Node.Element, capacity: Int ) -> _Node { - let leftNodeDepth = leftNode.storage.header.depth - let leftNodeSubtreeCount = leftNode.storage.header.subtreeCount - let rightNodeDepth = rightNode.storage.header.depth - let rightNodeSubtreeCount = rightNode.storage.header.subtreeCount + let leftNodeDepth = unsafe leftNode.storage.header.depth + let leftNodeSubtreeCount = unsafe leftNode.storage.header.subtreeCount + let rightNodeDepth = unsafe rightNode.storage.header.depth + let rightNodeSubtreeCount = unsafe rightNode.storage.header.subtreeCount func prepending( atDepth depth: Int, onto node: inout _Node ) -> _Node.Splinter? { if depth == 0 { - let splinter = leftNode.update { - $0.concatenateWith(node: &node, separatedBy: separator) + let splinter = unsafe leftNode.update { + unsafe $0.concatenateWith(node: &node, separatedBy: separator) } node = leftNode return splinter } else { - return node.update { handle in - let splinter = prepending(atDepth: depth - 1, onto: &handle[childAt: 0]) - handle.subtreeCount += leftNodeSubtreeCount + return unsafe node.update { handle in + let splinter = unsafe prepending(atDepth: depth - 1, onto: &handle[childAt: 0]) + unsafe handle.subtreeCount += leftNodeSubtreeCount if let splinter = splinter { - return handle.insertSplinter(splinter, atSlot: 0) + return unsafe handle.insertSplinter(splinter, atSlot: 0) } else { - handle.subtreeCount += 1 + unsafe handle.subtreeCount += 1 return nil } } @@ -252,31 +253,31 @@ extension _Node { atDepth depth: Int, onto node: _Node.UnsafeHandle ) -> _Node.Splinter? { - assert(node.depth >= depth, "Cannot graft at a depth deeper than the node.") - + assert(unsafe node.depth >= depth, "Cannot graft at a depth deeper than the node.") + if depth == 0 { // Graft at the current node - return node.concatenateWith(node: &rightNode, separatedBy: separator) + return unsafe node.concatenateWith(node: &rightNode, separatedBy: separator) } else { - let endSlot = node.childCount - 1 - let splinter = node[childAt: endSlot].update { - appending(atDepth: depth - 1, onto: $0) + let endSlot = unsafe node.childCount - 1 + let splinter = unsafe node[childAt: endSlot].update { + unsafe appending(atDepth: depth - 1, onto: $0) } - - node.subtreeCount += rightNodeSubtreeCount - + + unsafe node.subtreeCount += rightNodeSubtreeCount + if let splinter = splinter { - return node.insertSplinter(splinter, atSlot: endSlot) + return unsafe node.insertSplinter(splinter, atSlot: endSlot) } else { - node.subtreeCount += 1 + unsafe node.subtreeCount += 1 return nil } } } if leftNodeDepth >= rightNodeDepth { - let splinter = leftNode.update { - appending(atDepth: leftNodeDepth - rightNodeDepth, onto: $0) + let splinter = unsafe leftNode.update { + unsafe appending(atDepth: leftNodeDepth - rightNodeDepth, onto: $0) } if let splinter = splinter { return splinter.toNode(leftChild: leftNode, capacity: capacity) @@ -302,8 +303,9 @@ extension _Node { /// - Returns: The value the closure body returns, if any. @inlinable @inline(__always) + @unsafe package func read(_ body: (UnsafeHandle) throws -> R) rethrows -> R { - return try self.storage.read(body) + unsafe try self.storage.read(body) } /// Allows mutable access to the underlying data behind the node. @@ -312,13 +314,14 @@ extension _Node { /// - Returns: The value the closure body returns, if any. @inlinable @inline(__always) + @unsafe package mutating func update( _ body: (UnsafeHandle) throws -> R ) rethrows -> R { self.ensureUnique() - return try self.read { handle in - defer { handle.checkInvariants() } - return try body(UnsafeHandle(mutating: handle)) + return unsafe try self.read { handle in + defer { unsafe handle.checkInvariants() } + return unsafe try body(UnsafeHandle(mutating: handle)) } } @@ -329,6 +332,7 @@ extension _Node { /// - Returns: The value the closure body returns, if any. @inlinable @inline(__always) + @unsafe package mutating func update( isUnique: Bool, _ body: (UnsafeHandle) throws -> R @@ -337,9 +341,9 @@ extension _Node { self = _Node(copyingFrom: self) } - return try self.read { handle in - defer { handle.checkInvariants() } - return try body(UnsafeHandle(mutating: handle)) + return unsafe try self.read { handle in + defer { unsafe handle.checkInvariants() } + return unsafe try body(UnsafeHandle(mutating: handle)) } } @@ -353,6 +357,13 @@ extension _Node { } } +extension _Node { + @inlinable + internal var _subtreeCount: Int { + unsafe self.read { unsafe $0.subtreeCount } + } +} + // MARK: Equatable extension _Node: Equatable { /// Whether two nodes are the same underlying reference in memory. diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Codable.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Codable.swift index 078e6e6f..24cfd5e0 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Codable.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Codable.swift @@ -67,7 +67,7 @@ extension SortedDictionary: Decodable where Key: Decodable, Value: Decodable { guard previousKey == nil || previousKey! < key else { let context = DecodingError.Context( codingPath: container.codingPath, - debugDescription: "Decoded elements out of order.") + debugDescription: "Decoded elements out of order") throw DecodingError.dataCorrupted(context) } diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift index 509523cc..ea2887d5 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Initializers.swift @@ -76,7 +76,7 @@ extension SortedDictionary { var previousKey: Key? = nil for (key, value) in keysAndValues { precondition(previousKey == nil || previousKey! < key, - "Sequence out of order.") + "Sequence out of order") builder.append((key, value)) previousKey = key } @@ -104,7 +104,7 @@ extension SortedDictionary { var previousKey: Key? = nil for (key, value) in keysAndValues { precondition(previousKey == nil || previousKey! < key, - "Sequence out of order.") + "Sequence out of order") builder.append((key, value)) previousKey = key } diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Partial RangeReplaceableCollection.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Partial RangeReplaceableCollection.swift index 0581f60d..5d2af488 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Partial RangeReplaceableCollection.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Partial RangeReplaceableCollection.swift @@ -160,7 +160,8 @@ extension SortedDictionary { bounds.upperBound._index.ensureValid(forTree: self._root) bounds.lowerBound._index.ensureValid(forTree: self._root) - return self._root.removeSubrange(Range(uncheckedBounds: (bounds.lowerBound._index, bounds.upperBound._index))) + return self._root.removeSubrange( + unsafe Range(uncheckedBounds: (bounds.lowerBound._index, bounds.upperBound._index))) } /// Removes all key-value pairs from the dictionary. diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift index b7376c9f..b76d3c53 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Subscripts.swift @@ -34,23 +34,23 @@ extension SortedDictionary { } _modify { - var (cursor, found) = self._root.takeCursor(forKey: key) - + var (cursor, found) = unsafe self._root.takeCursor(forKey: key) + var value: Value? if found { - value = cursor.moveValue() + value = unsafe cursor.moveValue() } defer { if found { if let value = value { - cursor.initializeValue(to: value) + unsafe cursor.initializeValue(to: value) } else { - cursor.removeElement(hasValueHole: true) + unsafe cursor.removeElement(hasValueHole: true) } } else { if let value = value { - cursor.insertElement( + unsafe cursor.insertElement( (key, value), capacity: self._root.internalCapacity ) @@ -59,7 +59,7 @@ extension SortedDictionary { } } - cursor.apply(to: &self._root) + unsafe cursor.apply(to: &self._root) } yield &value @@ -101,26 +101,25 @@ extension SortedDictionary { } _modify { - var (cursor, found) = self._root.takeCursor(forKey: key) - + var (cursor, found) = unsafe self._root.takeCursor(forKey: key) + var value: Value if found { - value = cursor.moveValue() + value = unsafe cursor.moveValue() } else { value = defaultValue() } defer { if found { - cursor.initializeValue(to: value) + unsafe cursor.initializeValue(to: value) } else { - cursor.insertElement( + unsafe cursor.insertElement( (key, value), - capacity: self._root.internalCapacity - ) + capacity: self._root.internalCapacity) } - cursor.apply(to: &self._root) + unsafe cursor.apply(to: &self._root) } yield &value diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Values.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Values.swift index 38ef3ac2..a1f14af6 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary+Values.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary+Values.swift @@ -229,14 +229,14 @@ extension SortedDictionary.Values { position._index.ensureValid(forTree: self._base._root) // Ensure we don't attempt to dereference the endIndex - precondition(position != endIndex, "Attempt to subscript out of range index.") - - var cursor = self._base._root.takeCursor(at: position._index) - var value = cursor.moveValue() + precondition(position != endIndex, "Attempt to subscript out of range index") + var cursor = unsafe self._base._root.takeCursor(at: position._index) + var value = unsafe cursor.moveValue() + defer { - cursor.initializeValue(to: value) - cursor.apply(to: &self._base._root) + unsafe cursor.initializeValue(to: value) + unsafe cursor.apply(to: &self._base._root) } yield &value diff --git a/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift b/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift index 1d64de83..46d54b5e 100644 --- a/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift +++ b/Sources/SortedCollections/SortedDictionary/SortedDictionary.swift @@ -112,20 +112,20 @@ extension SortedDictionary { default defaultValue: @autoclosure () -> Value, _ body: (inout Value) throws -> R ) rethrows -> R { - var (cursor, found) = self._root.takeCursor(forKey: key) + var (cursor, found) = unsafe self._root.takeCursor(forKey: key) let r: R if found { - r = try cursor.updateCurrentNode { handle, slot in - try body(&handle[valueAt: slot]) + r = unsafe try cursor.updateCurrentNode { handle, slot in + unsafe try body(&handle[valueAt: slot]) } } else { var value = defaultValue() r = try body(&value) - cursor.insertElement((key, value), capacity: self._root.internalCapacity) + unsafe cursor.insertElement((key, value), capacity: self._root.internalCapacity) } - cursor.apply(to: &self._root) + unsafe cursor.apply(to: &self._root) return r } diff --git a/Sources/SortedCollections/SortedSet/SortedSet+Codable.swift b/Sources/SortedCollections/SortedSet/SortedSet+Codable.swift index a7d8d825..7b566ed2 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet+Codable.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet+Codable.swift @@ -45,7 +45,7 @@ extension SortedSet: Decodable where Element: Decodable { guard previousElement == nil || previousElement! < element else { let context = DecodingError.Context( codingPath: container.codingPath, - debugDescription: "Decoded elements out of order.") + debugDescription: "Decoded elements out of order") throw DecodingError.dataCorrupted(context) } builder.append(element) diff --git a/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift b/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift index dd69d28d..3aed7b83 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet+Initializers.swift @@ -47,7 +47,7 @@ extension SortedSet { var previousElement: Element? = nil for element in elements { precondition(previousElement == nil || previousElement! < element, - "Sequence out of order.") + "Sequence out of order") builder.append(element) previousElement = element } diff --git a/Sources/SortedCollections/SortedSet/SortedSet+Partial RangeReplaceableCollection.swift b/Sources/SortedCollections/SortedSet/SortedSet+Partial RangeReplaceableCollection.swift index 962c08b5..9f898a5a 100644 --- a/Sources/SortedCollections/SortedSet/SortedSet+Partial RangeReplaceableCollection.swift +++ b/Sources/SortedCollections/SortedSet/SortedSet+Partial RangeReplaceableCollection.swift @@ -161,7 +161,8 @@ extension SortedSet { bounds.upperBound._index.ensureValid(forTree: self._root) bounds.lowerBound._index.ensureValid(forTree: self._root) - return self._root.removeSubrange(Range(uncheckedBounds: (bounds.lowerBound._index, bounds.upperBound._index))) + return self._root.removeSubrange( + unsafe Range(uncheckedBounds: (bounds.lowerBound._index, bounds.upperBound._index))) } /// Removes all elements from the set. diff --git a/Sources/SpanPreview/InputSpan.swift b/Sources/SpanPreview/InputSpan.swift index 5e3e118a..5d837442 100644 --- a/Sources/SpanPreview/InputSpan.swift +++ b/Sources/SpanPreview/InputSpan.swift @@ -45,7 +45,7 @@ public struct InputSpan: ~Copyable, ~Escapable { @_lifetime(immortal) public init() { - _pointer = nil + unsafe _pointer = nil capacity = 0 _count = 0 } @@ -79,7 +79,7 @@ extension InputSpan where Element: ~Copyable { internal func _unsafeAddressOfElement( uncheckedOffset offset: Index ) -> UnsafeMutablePointer { - _unsafeRawAddressOfSlot( + unsafe _unsafeRawAddressOfSlot( uncheckedOffset: offset ).assumingMemoryBound(to: Element.self) } @@ -392,7 +392,7 @@ extension InputSpan where Element: ~Copyable { public mutating func removeFirst() -> Element { precondition(_count > 0, "InputSpan underflow") defer { _count &-= 1 } - return _unsafeAddressOfElement(uncheckedOffset: 0).move() + return unsafe _unsafeAddressOfElement(uncheckedOffset: 0).move() } /// Remove the last N elements of this span, returning the memory they occupy @@ -446,11 +446,11 @@ extension InputSpan where Element: ~Copyable { @_alwaysEmitIntoClient @_lifetime(self: copy self) public mutating func prepend(moving source: UnsafeMutableBufferPointer) { - self.withUnsafeMutableBufferPointer { dst, dstCount in + unsafe self.withUnsafeMutableBufferPointer { dst, dstCount in let dstEnd = dst.count &- dstCount let dstStart = dstEnd - source.count precondition(dstStart >= 0, "InputSpan capacity overflow") - dst + unsafe dst ._extracting(uncheckedFrom: dstStart, to: dstEnd) .moveInitializeAll(fromContentsOf: source) dstCount &+= source.count @@ -477,11 +477,11 @@ extension InputSpan /* where Element: Copyable */ { @inlinable @_lifetime(self: copy self) package mutating func prepend(copying source: UnsafeBufferPointer) { - self.withUnsafeMutableBufferPointer { dst, dstCount in + unsafe self.withUnsafeMutableBufferPointer { dst, dstCount in let dstEnd = dst.count &- dstCount let dstStart = dstEnd - source.count precondition(dstStart >= 0, "InputSpan capacity overflow") - dst + unsafe dst ._extracting(uncheckedFrom: dstStart, to: dstEnd) .initializeAll(fromContentsOf: source) dstCount &+= source.count @@ -492,7 +492,7 @@ extension InputSpan /* where Element: Copyable */ { @_lifetime(self: copy self) package mutating func prepend(copying source: borrowing Span) { source.withUnsafeBufferPointer { src in - self.prepend(copying: src) + unsafe self.prepend(copying: src) } } } @@ -532,7 +532,7 @@ extension InputSpan where Element: ~Copyable { public var span: Span { @_lifetime(borrow self) borrowing get { - _uncheckedSpan(in: 0 ..< _count) + unsafe _uncheckedSpan(in: 0 ..< _count) } } @@ -542,7 +542,7 @@ extension InputSpan where Element: ~Copyable { public var mutableSpan: MutableSpan { @_lifetime(&self) mutating get { - _uncheckedMutableSpan(in: 0 ..< _count) + unsafe _uncheckedMutableSpan(in: 0 ..< _count) } } } @@ -617,10 +617,10 @@ extension InputSpan where Element: ~Copyable { let buffer = unsafe _unsafeRawAddressOfSlot( uncheckedOffset: 0 ).withMemoryRebound(to: Element.self, capacity: c) { start in - UnsafeMutableBufferPointer(start: start, count: c) + unsafe UnsafeMutableBufferPointer(start: start, count: c) } _count -= c - return _overrideLifetime( + return unsafe _overrideLifetime( InputSpan(buffer: buffer, initializedCount: c), mutating: &self) } @@ -632,10 +632,10 @@ internal func _withTemporaryInputSpan) throws(E) -> R ) throws(E) -> R { - try _withUnsafeTemporaryAllocation( + unsafe try _withUnsafeTemporaryAllocation( of: Element.self, capacity: capacity ) { buffer throws(E) in - var span = InputSpan(buffer: buffer, initializedCount: 0) + var span = unsafe InputSpan(buffer: buffer, initializedCount: 0) return try body(&span) } } diff --git a/Sources/SpanPreview/MutableSpan+InputSpanHelpers.swift b/Sources/SpanPreview/MutableSpan+InputSpanHelpers.swift index 0f2dcb4a..e67ab34d 100644 --- a/Sources/SpanPreview/MutableSpan+InputSpanHelpers.swift +++ b/Sources/SpanPreview/MutableSpan+InputSpanHelpers.swift @@ -34,20 +34,20 @@ extension MutableSpan where Element: ~Copyable { "updateSubrange source count doesn't match target") guard !subrange.isEmpty else { return } self.withUnsafeMutableBufferPointer { dst in - source.withUnsafeMutableBufferPointer { src, c in + unsafe source.withUnsafeMutableBufferPointer { src, c in // FIXME: Make sure this calls memcpy when Element is bitwise movable. #if false // FIXME: UMBP.moveUpdate(fromContentsOf:) is broken as of 2026-09-17 (rdar://187733648) - let i = dst + let i = unsafe dst ._extracting(unchecked: subrange) .moveUpdate(fromContentsOf: src._extracting(last: c)) precondition(i == subrange.count) #else - var d = dst._ptr(at: subrange.lowerBound) - var s = src._ptr(at: src.count - c) + var d = unsafe dst._ptr(at: subrange.lowerBound) + var s = unsafe src._ptr(at: src.count - c) for i in 0 ..< c { - d.pointee = s.move() - d += 1 - s += 1 + unsafe d.pointee = s.move() + unsafe d += 1 + unsafe s += 1 } #endif c = 0 @@ -68,18 +68,18 @@ extension MutableSpan where Element: ~Copyable { "updateSubrange source count doesn't match target") guard !self.isEmpty else { return } self.withUnsafeMutableBufferPointer { dst in - source.withUnsafeMutableBufferPointer { src, c in + unsafe source.withUnsafeMutableBufferPointer { src, c in // FIXME: Make sure this calls memcpy when Element is bitwise movable. #if false // FIXME: UMBP.moveUpdate(fromContentsOf:) is broken as of 2026-09-17 (rdar://187733648) - let i = dst.moveUpdate(fromContentsOf: src._extracting(last: c)) + let i = unsafe dst.moveUpdate(fromContentsOf: src._extracting(last: c)) assert(i == count) #else - var d = dst._ptr(at: 0) - var s = src._ptr(at: src.count - c) + var d = unsafe dst._ptr(at: 0) + var s = unsafe src._ptr(at: src.count - c) for i in 0 ..< c { - d.pointee = s.move() - d += 1 - s += 1 + unsafe d.pointee = s.move() + unsafe d += 1 + unsafe s += 1 } #endif c = 0 diff --git a/Sources/SpanPreview/OutputSpan+InputSpanHelpers.swift b/Sources/SpanPreview/OutputSpan+InputSpanHelpers.swift index 4d543b9f..7dc0f8e7 100644 --- a/Sources/SpanPreview/OutputSpan+InputSpanHelpers.swift +++ b/Sources/SpanPreview/OutputSpan+InputSpanHelpers.swift @@ -24,11 +24,11 @@ extension OutputSpan where Element: ~Copyable { @_lifetime(source: copy source) package mutating func _append(moving source: inout InputSpan) { // FIXME: This needs to be in the stdlib. - source.withUnsafeMutableBufferPointer { src, srcCount in - let srcItems = src._extracting( + unsafe source.withUnsafeMutableBufferPointer { src, srcCount in + let srcItems = unsafe src._extracting( uncheckedFrom: src.count &- srcCount, to: src.count) - self._append(moving: srcItems) + unsafe self._append(moving: srcItems) srcCount = 0 } } @@ -38,8 +38,8 @@ extension OutputSpan where Element: ~Copyable { package mutating func _consumeAll( consumingWith consumer: (inout InputSpan) throws(Failure) -> Void ) throws(Failure) { - try self.withUnsafeMutableBufferPointer { buffer, count throws(Failure) in - var span = InputSpan( + unsafe try self.withUnsafeMutableBufferPointer { buffer, count throws(Failure) in + var span = unsafe InputSpan( buffer: buffer._extracting(first: count), initializedCount: count) try consumer(&span) diff --git a/Sources/TrailingElementsModule/TrailingArray.swift b/Sources/TrailingElementsModule/TrailingArray.swift index 46b74f6a..c5ff7982 100644 --- a/Sources/TrailingElementsModule/TrailingArray.swift +++ b/Sources/TrailingElementsModule/TrailingArray.swift @@ -20,6 +20,7 @@ /// the information in the header (via the `trailingCount` property), so that /// it is not stored separately. @frozen +@safe public struct TrailingArray: ~Copyable where Header: ~Copyable { @@ -27,12 +28,14 @@ where Header: ~Copyable /// Header instance in cases where the alignment of Element exceeds that /// of the Header and we have overallocated to compensate. @usableFromInline + @unsafe var _storage: UnsafeMutableRawPointer /// Pointer to the header. @_alwaysEmitIntoClient + @unsafe var _pointer: UnsafeMutablePointer
{ - Self.headerPointer(fromStorage: _storage) + unsafe Self.headerPointer(fromStorage: _storage) } /// The element type stored within the buffer. @@ -44,12 +47,11 @@ where Header: ~Copyable @_alwaysEmitIntoClient private init(_headerOnly header: consuming Header) { let (bytes, alignment) = Self.allocationSize(header: header) - _storage = UnsafeMutableRawPointer.allocate( + unsafe _storage = UnsafeMutableRawPointer.allocate( byteCount: bytes, - alignment: alignment - ) + alignment: alignment) - _pointer.initialize(to: header) + unsafe _pointer.initialize(to: header) } @available(SwiftStdlib 5.1, *) @@ -80,16 +82,16 @@ where Header: ~Copyable @_alwaysEmitIntoClient public init(header: consuming Header, repeating element: Element) { self.init(_headerOnly: header) - rawElements.initialize(repeating: element) + unsafe rawElements.initialize(repeating: element) } /// Deinitialize each of the trailing elements, then the header, then /// deallocate the underlying storage. @_alwaysEmitIntoClient deinit { - rawElements.deinitialize() - _pointer.deinitialize(count: 1) - _storage.deallocate() + unsafe rawElements.deinitialize() + unsafe _pointer.deinitialize(count: 1) + unsafe _storage.deallocate() } /// Take ownership over a pointer to memory containing the header followed @@ -109,9 +111,9 @@ where Header: ~Copyable consuming pointer: UnsafeMutablePointer
, storage: UnsafeMutableRawPointer ) { - self._storage = storage + unsafe self._storage = storage precondition( - self._pointer == pointer, + unsafe self._pointer == pointer, "header pointer does not account for the alignment of the elements" ) } @@ -126,21 +128,21 @@ where Header: ~Copyable pointer: UnsafeMutablePointer
, storage: UnsafeMutableRawPointer ) { - let pointer = self._pointer - let storage = _storage + let pointer = unsafe self._pointer + let storage = unsafe _storage discard self - return (pointer, storage) + return unsafe (pointer, storage) } /// Access the header portion of the buffer. @_alwaysEmitIntoClient public var header: Header { unsafeAddress { - UnsafePointer(_pointer) + unsafe UnsafePointer(_pointer) } unsafeMutableAddress { - _pointer + unsafe _pointer } } @@ -158,26 +160,27 @@ where Header: ~Copyable /// Indices covering all of the trailing elements. Always `0.. { 0.. { 0 ..< count } /// Access the trailing element at the given index. @_alwaysEmitIntoClient public subscript(index: Int) -> Element { get { precondition(index >= 0 && index < count) - return rawElements[index] + return unsafe rawElements[index] } set { precondition(index >= 0 && index < count) - rawElements[index] = newValue + unsafe rawElements[index] = newValue } } /// Access the flexible array elements. @_alwaysEmitIntoClient + @unsafe var rawElements: UnsafeMutableBufferPointer { - UnsafeMutableBufferPointer( + unsafe UnsafeMutableBufferPointer( start: UnsafeMutableRawPointer(_pointer.advanced(by: 1)) .assumingMemoryBound(to: Element.self), count: header.trailingCount @@ -190,7 +193,7 @@ where Header: ~Copyable public var elements: Span { @_lifetime(self) get { - _overrideLifetime(rawElements.span, borrowing: self) + unsafe _overrideLifetime(rawElements.span, borrowing: self) } } @@ -201,8 +204,8 @@ where Header: ~Copyable public var mutableElements: MutableSpan { @_lifetime(self) mutating get { - let elements = self.rawElements.mutableSpan - return _overrideLifetime(elements, mutating: &self) + let elements = unsafe self.rawElements.mutableSpan + return unsafe _overrideLifetime(elements, mutating: &self) } } @@ -212,7 +215,7 @@ where Header: ~Copyable public mutating func withUnsafeMutablePointerToHeader( _ body: (UnsafeMutablePointer
) throws(E) -> R ) throws(E) -> R { - return try body(_pointer) + return unsafe try body(_pointer) } /// Execute the given closure, providing it with an unsafe buffer pointer @@ -221,7 +224,7 @@ where Header: ~Copyable public mutating func withUnsafeMutablePointerToElements( _ body: (UnsafeMutableBufferPointer) throws(E) -> R ) throws(E) -> R { - return try body(rawElements) + return unsafe try body(rawElements) } /// Execute the given closure, providing it with unsafe pointers to the @@ -230,7 +233,7 @@ where Header: ~Copyable public mutating func withUnsafeMutablePointers( _ body: (UnsafeMutablePointer
, UnsafeMutableBufferPointer) throws(E) -> R ) throws(E) -> R { - return try body(_pointer, rawElements) + return unsafe try body(_pointer, rawElements) } /// Determine the allocation size and alignment needed for the given header @@ -272,12 +275,12 @@ where Header: ~Copyable // Normal case: the header has sufficient alignment to include the // elements, so the storage refers directly to the header. if elementAlignment <= headerAlignment { - return storage.assumingMemoryBound(to: Header.self) + return unsafe storage.assumingMemoryBound(to: Header.self) } // The header is stored right before the elements, with padding bytes // between the start of the allocation and up to the header. - return storage.advanced(by: MemoryLayout
.stride) + return unsafe storage.advanced(by: MemoryLayout
.stride) .alignedUp(for: Element.self) .advanced(by: -MemoryLayout
.stride) .assumingMemoryBound(to: Header.self) @@ -306,10 +309,10 @@ extension TrailingArray where Header: Copyable { repeating element: Element, body: (inout TrailingArray
) throws(E) -> R ) throws(E) -> R { - return try _withTemporaryValue( + return unsafe try _withTemporaryValue( header: header, uninitializedTrailingElements: () ) { (value) throws(E) in - value.rawElements.initialize(repeating: element) + unsafe value.rawElements.initialize(repeating: element) return try body(&value) } } @@ -326,7 +329,7 @@ extension TrailingArray where Header: Copyable { initializingTrailingElementsWith initializer: (inout OutputSpan) throws(E) -> Void, body: (inout TrailingArray
) throws(E) -> R ) throws(E) -> R { - return try _withTemporaryValue( + return unsafe try _withTemporaryValue( header: header, uninitializedTrailingElements: () ) { (value) throws(E) in try value._initializeTrailingElements(initializer: initializer) @@ -357,12 +360,13 @@ extension TrailingArray { ) { buffer in // Initialize the header within the temporary allocation. let storagePointer = buffer.baseAddress! - let headerPointer = TrailingArray.headerPointer(fromStorage: storagePointer) - headerPointer.initialize(to: header) + let headerPointer = unsafe TrailingArray.headerPointer(fromStorage: storagePointer) + unsafe headerPointer.initialize(to: header) /// Create a trailing array over that temporary storage. - var managedBuffer = TrailingArray(consuming: headerPointer, - storage: storagePointer) + var managedBuffer = unsafe TrailingArray( + consuming: headerPointer, + storage: storagePointer) let resultOrError: Result do throws(E) { resultOrError = .success(try body(&managedBuffer)) @@ -371,13 +375,13 @@ extension TrailingArray { } // Deinitialize the elements and header. - managedBuffer.rawElements.deinitialize() - managedBuffer._pointer.deinitialize(count: 1) + unsafe managedBuffer.rawElements.deinitialize() + unsafe managedBuffer._pointer.deinitialize(count: 1) // Tell the trailing buffer not to free the storage. - let (finalPointer, finalStorage) = managedBuffer.leakStorage() - precondition(finalPointer == headerPointer) - precondition(finalStorage == storagePointer) + let (finalPointer, finalStorage) = unsafe managedBuffer.leakStorage() + precondition(unsafe finalPointer == headerPointer) + precondition(unsafe finalStorage == storagePointer) return resultOrError } @@ -399,7 +403,7 @@ extension TrailingArray where Header.Element: BitwiseCopyable { uninitializedTrailingElements: (), body: (inout TrailingArray
) throws(E) -> R ) throws(E) -> R { - return try _withTemporaryValue( + return unsafe try _withTemporaryValue( header: header, uninitializedTrailingElements: () ) { (value) throws(E) in try body(&value) diff --git a/Sources/TrailingElementsModule/TrailingPadding.swift b/Sources/TrailingElementsModule/TrailingPadding.swift index eac52f0c..2aedf46f 100644 --- a/Sources/TrailingElementsModule/TrailingPadding.swift +++ b/Sources/TrailingElementsModule/TrailingPadding.swift @@ -27,9 +27,11 @@ /// type, whose count is computable from the header, use /// `IntrusiveManagedPointer` instead. @frozen +@safe public struct TrailingPadding: ~Copyable { /// Pointer to the header, followed by the padding. @usableFromInline + @unsafe let _pointer: UnsafeMutablePointer
/// Create a new instance with the given header and total size. The total @@ -39,10 +41,10 @@ public struct TrailingPadding: ~Copyable { public init(header: consuming Header, totalSize size: Int) { precondition(size >= MemoryLayout
.size, "must allocate enough storage for the underlying stored type") - _pointer = UnsafeMutableRawPointer + unsafe _pointer = UnsafeMutableRawPointer .allocate(byteCount: size, alignment: MemoryLayout
.alignment) .assumingMemoryBound(to: Header.self) - _pointer.initialize(to: header) + unsafe _pointer.initialize(to: header) } /// Take ownership over a pointer to memory containing the header followed @@ -52,44 +54,46 @@ public struct TrailingPadding: ~Copyable { /// deinitialized and freed. @_alwaysEmitIntoClient public init(consuming pointer: UnsafeMutablePointer
) { - self._pointer = pointer + unsafe self._pointer = pointer } /// Deinitializes the header, then deallocates the underlying memory. @_alwaysEmitIntoClient deinit { - _pointer.deinitialize(count: 1) - _pointer.deallocate() + unsafe _pointer.deinitialize(count: 1) + unsafe _pointer.deallocate() } /// Access the header portion of the value. @_alwaysEmitIntoClient public var header: Header { unsafeAddress { - UnsafePointer(_pointer) + unsafe UnsafePointer(_pointer) } unsafeMutableAddress { - _pointer + unsafe _pointer } } /// Executes the given closure with the pointer to the header itself. @_alwaysEmitIntoClient + @unsafe public func withUnsafeMutablePointerToHeader( _ body: (UnsafeMutablePointer
) throws(E) -> R ) throws(E) -> R { - return try body(_pointer) + return unsafe try body(_pointer) } /// Take ownership over the stored memory, returning its pointer. The /// underlying storage will not be freed by the `TrailingPadding` instance, /// as it is the responsibility of the caller. @_alwaysEmitIntoClient + @unsafe public consuming func leakStorage() -> UnsafeMutablePointer
{ - let pointer = self._pointer + let pointer = unsafe self._pointer discard self - return pointer + return unsafe pointer } } @@ -117,22 +121,22 @@ extension TrailingPadding where Header: Copyable { alignment: MemoryLayout
.alignment ) { buffer in /// Create a tail-allocated storage over that temporary storage. - let pointer = buffer.baseAddress!.assumingMemoryBound(to: Header.self) - pointer.initialize(to: header) - var tailAllocated = TrailingPadding(consuming: pointer) + let pointer = unsafe buffer.baseAddress!.assumingMemoryBound(to: Header.self) + unsafe pointer.initialize(to: header) + var tailAllocated = unsafe TrailingPadding(consuming: pointer) do throws(E) { let result = try body(&tailAllocated) // Tell the tail-allocated buffer not to free the storage. - let finalPointer = tailAllocated.leakStorage() - precondition(finalPointer == pointer) + let finalPointer = unsafe tailAllocated.leakStorage() + precondition(unsafe finalPointer == pointer) return .success(result) } catch { // Tell the tail-allocated buffer not to free the storage. - let finalPointer = tailAllocated.leakStorage() - precondition(finalPointer == pointer) + let finalPointer = unsafe tailAllocated.leakStorage() + precondition(unsafe finalPointer == pointer) return .failure(error) } diff --git a/Tests/SortedCollectionsTests/BTree/Node Utils.swift b/Tests/SortedCollectionsTests/BTree/Node Utils.swift index 04a2723b..668ba281 100644 --- a/Tests/SortedCollectionsTests/BTree/Node Utils.swift +++ b/Tests/SortedCollectionsTests/BTree/Node Utils.swift @@ -77,11 +77,11 @@ struct NodeTemplateBuilder { case let c as NodeTemplate: children.append(c) default: - preconditionFailure("NodeTemplate child must be either key or child.") + preconditionFailure("NodeTemplate child must be either key or child") } } precondition(children.count == 0 || children.count == keys.count + 1, - "NodeTemplate must be either leaf or internal node.") + "NodeTemplate must be either leaf or internal node") return NodeTemplate(keys: keys, children: children.isEmpty ? nil : children) } } diff --git a/Tests/SortedCollectionsTests/SortedSet/SortedSet Tests.swift b/Tests/SortedCollectionsTests/SortedSet/SortedSet Tests.swift index d18799f8..a2f3d21b 100644 --- a/Tests/SortedCollectionsTests/SortedSet/SortedSet Tests.swift +++ b/Tests/SortedCollectionsTests/SortedSet/SortedSet Tests.swift @@ -294,7 +294,7 @@ class SortedSetTests: CollectionTestCase { return } expectEqual(context.debugDescription, - "Decoded elements out of order.") + "Decoded elements out of order") } } }