diff --git a/.github/workflows/pull_request.yml b/.github/workflows/pull_request.yml index 58affdbf8..b5499a3c4 100644 --- a/.github/workflows/pull_request.yml +++ b/.github/workflows/pull_request.yml @@ -26,7 +26,7 @@ jobs: linux_6_3_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_nightly_next_arguments_override: "-Xswiftc -warnings-as-errors --explicit-target-dependency-import-check error" linux_nightly_main_arguments_override: "--explicit-target-dependency-import-check error" - linux_env_vars: '{"SWIFTNIO_RUN_SLOW_TESTS": "1", "SWIFTNIO_CI": "1"}' + linux_env_vars: '{"SWIFTNIO_CI": "1"}' windows_6_3_enabled: true windows_nightly_next_enabled: true windows_nightly_main_enabled: true @@ -94,7 +94,7 @@ jobs: with: runner_pool: general build_scheme: swift-nio-Package - env_vars: '{"SWIFTNIO_RUN_SLOW_TESTS": "1", "SWIFTNIO_CI": "1"}' + env_vars: '{"SWIFTNIO_CI": "1"}' static-sdk: name: Static Linux Swift SDK diff --git a/Sources/NIOCore/AsyncAwaitSupport.swift b/Sources/NIOCore/AsyncAwaitSupport.swift index 6a31d64c1..7b1afd77d 100644 --- a/Sources/NIOCore/AsyncAwaitSupport.swift +++ b/Sources/NIOCore/AsyncAwaitSupport.swift @@ -22,9 +22,21 @@ @usableFromInline typealias NIOUnsafeContinuation = CheckedContinuation -#if compiler(>=6.1) +#if compiler(>=6.2) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @inlinable +nonisolated(nonsending) func withNIOUnsafeThrowingContinuation( + _ fn: (NIOUnsafeContinuation) -> Void +) async throws -> sending T { + try await withCheckedThrowingContinuation(fn) +} +#endif // compiler 6.2 + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +#if compiler(>=6.2) +@available(*, deprecated, message: "Use the 'nonisolated(nonsending)' overload without an 'isolation' parameter.") +#endif +@inlinable func withNIOUnsafeThrowingContinuation( isolation: isolated (any Actor)? = #isolation, _ fn: (NIOUnsafeContinuation) -> Void @@ -32,16 +44,6 @@ func withNIOUnsafeThrowingContinuation( try await withCheckedThrowingContinuation(isolation: isolation, fn) } #else -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -@inlinable -func withNIOUnsafeThrowingContinuation( - isolation: isolated (any Actor)? = #isolation, - _ fn: (NIOUnsafeContinuation) -> Void -) async throws -> T { - try await withCheckedThrowingContinuation(isolation: isolation, fn) -} -#endif // compiler 6.0 -#else /// A Swift Continuation that behaves like a `CheckedContinuation` in Debug mode /// and like a `UnsafeContinuation` in release mode. /// @@ -51,25 +53,27 @@ func withNIOUnsafeThrowingContinuation( @usableFromInline typealias NIOUnsafeContinuation = UnsafeContinuation -#if compiler(>=6.1) +#if compiler(>=6.2) @available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) @inlinable +nonisolated(nonsending) func withNIOUnsafeThrowingContinuation( + _ fn: (NIOUnsafeContinuation) -> Void +) async throws -> sending T { + try await withUnsafeThrowingContinuation(fn) +} +#endif // compiler 6.2 + +@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) +#if compiler(>=6.2) +@available(*, deprecated, message: "Use the 'nonisolated(nonsending)' overload without an 'isolation' parameter.") +#endif +@inlinable func withNIOUnsafeThrowingContinuation( isolation: isolated (any Actor)? = #isolation, _ fn: (NIOUnsafeContinuation) -> Void ) async throws -> sending T { try await withUnsafeThrowingContinuation(isolation: isolation, fn) } -#else -@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *) -@inlinable -func withNIOUnsafeThrowingContinuation( - isolation: isolated (any Actor)? = #isolation, - _ fn: (NIOUnsafeContinuation) -> Void -) async throws -> T { - try await withUnsafeThrowingContinuation(isolation: isolation, fn) -} -#endif // compiler 6.0 #endif // release build extension EventLoopFuture { diff --git a/Sources/NIOCore/ByteBuffer-core.swift b/Sources/NIOCore/ByteBuffer-core.swift index 4e46fd80d..2d5cbe5a4 100644 --- a/Sources/NIOCore/ByteBuffer-core.swift +++ b/Sources/NIOCore/ByteBuffer-core.swift @@ -43,11 +43,16 @@ extension _ByteBufferSlice: Equatable {} /// fits within 24 bits, otherwise the behaviour is undefined. @usableFromInline struct _ByteBufferSlice: Sendable { - @usableFromInline private(set) var upperBound: ByteBuffer._Index - @usableFromInline private(set) var _begin: _UInt24 + /// - Note: Must only be modified by `_ByteBufferSlice` itself, use ``upperBound`` to read it. + @usableFromInline var _upperBound: ByteBuffer._Index + /// - Note: Must only be modified by `_ByteBufferSlice` itself, use ``lowerBound`` to read it. + @usableFromInline var _begin: _UInt24 @inlinable var lowerBound: ByteBuffer._Index { UInt32(self._begin) } + @inlinable var upperBound: ByteBuffer._Index { + self._upperBound + } @inlinable var count: Int { // Safe: the only constructors that set this enforce that upperBound > lowerBound, so // this cannot underflow. @@ -55,7 +60,7 @@ struct _ByteBufferSlice: Sendable { } @inlinable init() { self._begin = .init(0) - self.upperBound = .init(0) + self._upperBound = .init(0) } @inlinable static var maxSupportedLowerBound: ByteBuffer._Index { ByteBuffer._Index(_UInt24.max) @@ -65,7 +70,7 @@ struct _ByteBufferSlice: Sendable { extension _ByteBufferSlice { @inlinable init(_ range: Range) { self._begin = _UInt24(range.lowerBound) - self.upperBound = range.upperBound + self._upperBound = range.upperBound } } @@ -329,14 +334,26 @@ public struct ByteBuffer { // MARK: Internal _Storage for CoW /// Note: This class is **not** thread-safe @usableFromInline final class _Storage { - @usableFromInline private(set) var capacity: _Capacity - @usableFromInline private(set) var bytes: UnsafeMutableRawPointer + /// - Note: Must only be modified by `_Storage` itself, use ``capacity`` to read it. + @usableFromInline var _capacity: _Capacity + /// - Note: Must only be modified by `_Storage` itself, use ``bytes`` to read it. + @usableFromInline var _bytes: UnsafeMutableRawPointer @usableFromInline let allocator: ByteBufferAllocator + @inlinable + var capacity: _Capacity { + self._capacity + } + + @inlinable + var bytes: UnsafeMutableRawPointer { + self._bytes + } + @inlinable init(bytesNoCopy: UnsafeMutableRawPointer, capacity: _Capacity, allocator: ByteBufferAllocator) { - self.bytes = bytesNoCopy - self.capacity = capacity + self._bytes = bytesNoCopy + self._capacity = capacity self.allocator = allocator } @@ -386,8 +403,8 @@ public struct ByteBuffer { let ptr = self.allocator.reallocate(self.bytes, size_t(self.capacity), size_t(newCapacity))! // bind the memory so we can assume it elsewhere to be bound to UInt8 ptr.bindMemory(to: UInt8.self, capacity: Int(newCapacity)) - self.bytes = ptr - self.capacity = newCapacity + self._bytes = ptr + self._capacity = newCapacity } private func deallocate() { diff --git a/Sources/NIOCore/CircularBuffer.swift b/Sources/NIOCore/CircularBuffer.swift index e9d114b66..f13ecf1fd 100644 --- a/Sources/NIOCore/CircularBuffer.swift +++ b/Sources/NIOCore/CircularBuffer.swift @@ -17,13 +17,25 @@ /// expansions from happening frequently. Expansions will always force an allocation and a copy to happen. public struct CircularBuffer: CustomStringConvertible { @usableFromInline - internal private(set) var _buffer: ContiguousArray + internal var _buffer: ContiguousArray + /// - Note: Must only be modified by `CircularBuffer` itself, use ``headBackingIndex`` to read it. @usableFromInline - internal private(set) var headBackingIndex: Int + internal var _headBackingIndex: Int + /// - Note: Must only be modified by `CircularBuffer` itself, use ``tailBackingIndex`` to read it. @usableFromInline - internal private(set) var tailBackingIndex: Int + internal var _tailBackingIndex: Int + + @inlinable + internal var headBackingIndex: Int { + self._headBackingIndex + } + + @inlinable + internal var tailBackingIndex: Int { + self._tailBackingIndex + } @inlinable internal var mask: Int { @@ -32,12 +44,12 @@ public struct CircularBuffer: CustomStringConvertible { @inlinable internal mutating func advanceHeadIdx(by: Int) { - self.headBackingIndex = indexAdvanced(index: self.headBackingIndex, by: by) + self._headBackingIndex = indexAdvanced(index: self.headBackingIndex, by: by) } @inlinable internal mutating func advanceTailIdx(by: Int) { - self.tailBackingIndex = indexAdvanced(index: self.tailBackingIndex, by: by) + self._tailBackingIndex = indexAdvanced(index: self.tailBackingIndex, by: by) } @inlinable @@ -63,9 +75,15 @@ public struct CircularBuffer: CustomStringConvertible { /// - Note: Every index is invalidated as soon as you perform a length-changing operating on the `CircularBuffer` /// but remains valid when you replace one item by another using the subscript. public struct Index: Comparable, Sendable { - @usableFromInline private(set) var _backingIndex: UInt32 - @usableFromInline private(set) var _backingCheck: _UInt24 - @usableFromInline private(set) var isIndexGEQHeadIndex: Bool + @usableFromInline var _backingIndex: UInt32 + @usableFromInline var _backingCheck: _UInt24 + /// - Note: Must only be modified by `Index` itself, use ``isIndexGEQHeadIndex`` to read it. + @usableFromInline var _isIndexGEQHeadIndex: Bool + + @inlinable + internal var isIndexGEQHeadIndex: Bool { + self._isIndexGEQHeadIndex + } @inlinable internal var backingIndex: Int { @@ -74,7 +92,7 @@ public struct CircularBuffer: CustomStringConvertible { @inlinable internal init(backingIndex: Int, backingCount: Int, backingIndexOfHead: Int) { - self.isIndexGEQHeadIndex = backingIndex >= backingIndexOfHead + self._isIndexGEQHeadIndex = backingIndex >= backingIndexOfHead self._backingCheck = .max self._backingIndex = UInt32(backingIndex) debugOnly { @@ -315,8 +333,8 @@ extension CircularBuffer: RandomAccessCollection { precondition(self.distance(from: bounds.upperBound, to: self.endIndex) >= 0) var newRing = self - newRing.headBackingIndex = bounds.lowerBound.backingIndex - newRing.tailBackingIndex = bounds.upperBound.backingIndex + newRing._headBackingIndex = bounds.lowerBound.backingIndex + newRing._tailBackingIndex = bounds.upperBound.backingIndex return newRing } set { @@ -335,8 +353,8 @@ extension CircularBuffer { @inlinable public init(initialCapacity: Int) { let capacity = Int(UInt32(initialCapacity).nextPowerOf2()) - self.headBackingIndex = 0 - self.tailBackingIndex = 0 + self._headBackingIndex = 0 + self._tailBackingIndex = 0 self._buffer = ContiguousArray(repeating: nil, count: capacity) assert(self._buffer.count == capacity) } @@ -399,8 +417,8 @@ extension CircularBuffer { let paddingCount = newCapacity &- newTailIndex newBacking.append(contentsOf: repeatElement(nil, count: paddingCount)) - self.headBackingIndex = 0 - self.tailBackingIndex = newTailIndex + self._headBackingIndex = 0 + self._tailBackingIndex = newTailIndex self._buffer = newBacking assert(self.verifyInvariants()) } @@ -428,8 +446,8 @@ extension CircularBuffer { let paddingCount = newCapacity &- newTailIndex newBacking.append(contentsOf: repeatElement(nil, count: paddingCount)) - self.headBackingIndex = 0 - self.tailBackingIndex = newTailIndex + self._headBackingIndex = 0 + self._tailBackingIndex = newTailIndex self._buffer = newBacking assert(self.verifyInvariants()) } @@ -478,8 +496,8 @@ extension CircularBuffer { self._buffer.removeAll(keepingCapacity: false) self._buffer.append(nil) } - self.headBackingIndex = 0 - self.tailBackingIndex = 0 + self._headBackingIndex = 0 + self._tailBackingIndex = 0 assert(self.verifyInvariants()) } @@ -587,7 +605,7 @@ extension CircularBuffer: RangeReplaceableCollection { idx = self.indexAdvanced(index: idx, by: -1) self._buffer[idx] = nil } - self.tailBackingIndex = idx + self._tailBackingIndex = idx } /// Removes the specified number of elements from the beginning of the @@ -609,7 +627,7 @@ extension CircularBuffer: RangeReplaceableCollection { self._buffer[idx] = nil idx = self.indexAdvanced(index: idx, by: 1) } - self.headBackingIndex = idx + self._headBackingIndex = idx } /// Removes and returns the first element of the `CircularBuffer`. @@ -707,8 +725,8 @@ extension CircularBuffer: RangeReplaceableCollection { newBuffer.append(contentsOf: repeatElement(nil, count: repetitionCount)) } self._buffer = newBuffer - self.headBackingIndex = 0 - self.tailBackingIndex = newBuffer.count &- repetitionCount + self._headBackingIndex = 0 + self._tailBackingIndex = newBuffer.count &- repetitionCount } assert(self.verifyInvariants()) } diff --git a/Sources/NIOCore/SingleStepByteToMessageDecoder.swift b/Sources/NIOCore/SingleStepByteToMessageDecoder.swift index a7a4f991b..1fef5ea3a 100644 --- a/Sources/NIOCore/SingleStepByteToMessageDecoder.swift +++ b/Sources/NIOCore/SingleStepByteToMessageDecoder.swift @@ -194,12 +194,18 @@ public final class NIOSingleStepByteToMessageProcessor Decoder.InboundOut? { if decodeMode == .normal { - return try self.decoder.decode(buffer: &buffer) + return try self._decoder.decode(buffer: &buffer) } else { - return try self.decoder.decodeLast(buffer: &buffer, seenEOF: seenEOF) + return try self._decoder.decodeLast(buffer: &buffer, seenEOF: seenEOF) } } @@ -310,7 +316,7 @@ public final class NIOSingleStepByteToMessageProcessor Decoder.InboundOut? { if decodeMode == .normal { - return try self.decoder.decode(buffer: &buffer) + return try self._decoder.decode(buffer: &buffer) } else { - return try self.decoder.decodeLast(buffer: &buffer, seenEOF: seenEOF) + return try self._decoder.decodeLast(buffer: &buffer, seenEOF: seenEOF) } } @@ -340,7 +346,7 @@ public final class NIOSingleStepByteToMessageProcessor 0, - self.decoder.shouldReclaimBytes(buffer: self._buffer!) + self._decoder.shouldReclaimBytes(buffer: self._buffer!) { self._buffer!.discardReadBytes() } diff --git a/Sources/_NIODataStructures/Heap.swift b/Sources/_NIODataStructures/Heap.swift index 0fa44b111..f5179b29a 100644 --- a/Sources/_NIODataStructures/Heap.swift +++ b/Sources/_NIODataStructures/Heap.swift @@ -30,11 +30,19 @@ import ucrt @usableFromInline internal struct Heap { @usableFromInline - internal private(set) var storage: [Element] + internal var _storage: [Element] + + /// Read-only view of the heap's backing storage. + /// + /// - Note: `_storage` must only be modified by `Heap` itself. + @inlinable + internal var storage: [Element] { + self._storage + } @inlinable internal init() { - self.storage = [] + self._storage = [] } @inlinable @@ -68,18 +76,18 @@ internal struct Heap { let right = self.rightIndex(index) var root: Int - if left <= (self.storage.count - 1) && self.comparator(storage[left], storage[index]) { + if left <= (self._storage.count - 1) && self.comparator(self._storage[left], self._storage[index]) { root = left } else { root = index } - if right <= (self.storage.count - 1) && self.comparator(storage[right], storage[root]) { + if right <= (self._storage.count - 1) && self.comparator(self._storage[right], self._storage[root]) { root = right } if root != index { - self.storage.swapAt(index, root) + self._storage.swapAt(index, root) self._heapify(root) } } @@ -88,23 +96,23 @@ internal struct Heap { @inlinable mutating func _heapRootify(index: Int, key: Element) { var index = index - if self.comparator(storage[index], key) { + if self.comparator(self._storage[index], key) { fatalError("New key must be closer to the root than current key") } - self.storage[index] = key - while index > 0 && self.comparator(self.storage[index], self.storage[self.parentIndex(index)]) { - self.storage.swapAt(index, self.parentIndex(index)) + self._storage[index] = key + while index > 0 && self.comparator(self._storage[index], self._storage[self.parentIndex(index)]) { + self._storage.swapAt(index, self.parentIndex(index)) index = self.parentIndex(index) } } @inlinable internal mutating func append(_ value: Element) { - var i = self.storage.count - self.storage.append(value) - while i > 0 && self.comparator(self.storage[i], self.storage[self.parentIndex(i)]) { - self.storage.swapAt(i, self.parentIndex(i)) + var i = self._storage.count + self._storage.append(value) + while i > 0 && self.comparator(self._storage[i], self._storage[self.parentIndex(i)]) { + self._storage.swapAt(i, self.parentIndex(i)) i = self.parentIndex(i) } } @@ -118,7 +126,7 @@ internal struct Heap { @discardableResult @inlinable internal mutating func remove(value: Element) -> Bool { - if let idx = self.storage.firstIndex(of: value) { + if let idx = self._storage.firstIndex(of: value) { self._remove(index: idx) return true } else { @@ -129,11 +137,11 @@ internal struct Heap { @discardableResult @inlinable internal mutating func removeFirst(where shouldBeRemoved: (Element) throws -> Bool) rethrows -> Element? { - guard self.storage.count > 0 else { + guard self._storage.count > 0 else { return nil } - guard let index = try self.storage.firstIndex(where: shouldBeRemoved) else { + guard let index = try self._storage.firstIndex(where: shouldBeRemoved) else { return nil } @@ -143,18 +151,18 @@ internal struct Heap { @discardableResult @inlinable mutating func _remove(index: Int) -> Element? { - guard self.storage.count > 0 else { + guard self._storage.count > 0 else { return nil } - let element = self.storage[index] - if self.storage.count == 1 || self.storage[index] == self.storage[self.storage.count - 1] { - self.storage.removeLast() - } else if !self.comparator(self.storage[index], self.storage[self.storage.count - 1]) { - self._heapRootify(index: index, key: self.storage[self.storage.count - 1]) - self.storage.removeLast() + let element = self._storage[index] + if self._storage.count == 1 || self._storage[index] == self._storage[self._storage.count - 1] { + self._storage.removeLast() + } else if !self.comparator(self._storage[index], self._storage[self._storage.count - 1]) { + self._heapRootify(index: index, key: self._storage[self._storage.count - 1]) + self._storage.removeLast() } else { - self.storage[index] = self.storage[self.storage.count - 1] - self.storage.removeLast() + self._storage[index] = self._storage[self._storage.count - 1] + self._storage.removeLast() self._heapify(index) } return element @@ -164,10 +172,10 @@ internal struct Heap { extension Heap: CustomDebugStringConvertible { @inlinable var debugDescription: String { - guard self.storage.count > 0 else { + guard self._storage.count > 0 else { return "" } - let descriptions = self.storage.map { String(describing: $0) } + let descriptions = self._storage.map { String(describing: $0) } let maxLen: Int = descriptions.map { $0.count }.max()! // storage checked non-empty above let paddedDescs = descriptions.map { (desc: String) -> String in var desc = desc @@ -188,11 +196,11 @@ extension Heap: CustomDebugStringConvertible { let rcIdx = self.rightIndex(rootIndex) var leftSpace = 0 var rightSpace = 0 - if lcIdx < self.storage.count { + if lcIdx < self._storage.count { let sws = subtreeWidths(rootIndex: lcIdx) leftSpace += sws.0 + sws.1 + maxLen } - if rcIdx < self.storage.count { + if rcIdx < self._storage.count { let sws = subtreeWidths(rootIndex: rcIdx) rightSpace += sws.0 + sws.1 + maxLen } @@ -239,17 +247,17 @@ struct HeapIterator: IteratorProtocol { extension Heap: Sequence { @inlinable var startIndex: Int { - self.storage.startIndex + self._storage.startIndex } @inlinable var endIndex: Int { - self.storage.endIndex + self._storage.endIndex } @inlinable var underestimatedCount: Int { - self.storage.count + self._storage.count } @inlinable @@ -259,7 +267,7 @@ extension Heap: Sequence { @inlinable subscript(position: Int) -> Element { - self.storage[position] + self._storage[position] } @inlinable @@ -269,7 +277,7 @@ extension Heap: Sequence { @inlinable var count: Int { - self.storage.count + self._storage.count } } diff --git a/Tests/NIOCoreTests/ByteBufferCrashTests.swift b/Tests/NIOCoreTests/ByteBufferCrashTests.swift index d685d659a..6d37b9c2e 100644 --- a/Tests/NIOCoreTests/ByteBufferCrashTests.swift +++ b/Tests/NIOCoreTests/ByteBufferCrashTests.swift @@ -93,20 +93,15 @@ import Testing } } - @Test( - // Allocating ~4GB is slow, so this test is opt-in via a truthy SWIFTNIO_RUN_SLOW_TESTS. - .disabled( - if: !slowTestsEnabled(), - "Set SWIFTNIO_RUN_SLOW_TESTS to run this slow (~4GB of memory written) test" - ), - .disabled(if: MemoryLayout.size < 8, "Doesn't work on 32-bit machines") - ) + @Test(.disabled(if: MemoryLayout.size < 8, "Doesn't work on 32-bit machines")) func setBytesWithoutContigiousStorageMoreThanUInt32MaxBytes() async { await #expect(processExitsWith: .failure) { - let circularBuffer = CircularBuffer(repeating: 0, count: Int(UInt32.max) + 1) + // `Repeated` doesn't offer contiguous storage, so this takes the slow path in + // `setBytes` without actually having to materialise more than `UInt32.max` bytes. + let bytes = repeatElement(UInt8(0), count: Int(UInt32.max) + 1) var bb = ByteBuffer() bb.reserveCapacity(64) - bb.setBytes(circularBuffer, at: bb.writerIndex) + bb.setBytes(bytes, at: bb.writerIndex) } } @@ -212,15 +207,4 @@ private func isDebugAssertConfiguration() -> Bool { ) return isDebugAssert } - -/// Whether opt-in slow tests should run, gated on a truthy `SWIFTNIO_RUN_SLOW_TESTS` -/// environment variable. Unset (the default) means slow tests do not run. -private func slowTestsEnabled() -> Bool { - switch ProcessInfo.processInfo.environment["SWIFTNIO_RUN_SLOW_TESTS"]?.lowercased() { - case "true", "y", "yes", "on", "1": - return true - default: - return false - } -} #endif